xmlbeans-2.6.0/0000755000175000017500000000000013041512717011451 5ustar apoapoxmlbeans-2.6.0/LICENSE.txt0000644000175000017500000002613611361341576013312 0ustar apoapo 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. xmlbeans-2.6.0/src/0000755000175000017500000000000011714325344012243 5ustar apoapoxmlbeans-2.6.0/src/typestore/0000755000175000017500000000000011361341572014300 5ustar apoapoxmlbeans-2.6.0/src/typestore/org/0000755000175000017500000000000011361341572015067 5ustar apoapoxmlbeans-2.6.0/src/typestore/org/apache/0000755000175000017500000000000011361341572016310 5ustar apoapoxmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/0000755000175000017500000000000011361341572020121 5ustar apoapoxmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/0000755000175000017500000000000011361341572021062 5ustar apoapoxmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/values/0000755000175000017500000000000013041512717022357 5ustar apoapoxmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/values/TypeStoreUser.java0000644000175000017500000001401211361341572026017 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.xmlbeans.QNameSet; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.SchemaField; /** * Represents the strongly-typed user of a typestore. * A typestore is responsible for all the lexical aspects of XML, and * a typestore user is responsible for all strongly-typed aspects. * Where there is interaction between the two models, it is represented * by the TypeStore and TypeStoreUser interfaces. */ public interface TypeStoreUser { /** * Called to attach to the given textStore. When a TypeStoreUser is * attached, it is put into a completely invalidated state. */ void attach_store(TypeStore store); /** * Returns the schema type of this user */ SchemaType get_schema_type(); /** * Returns the store to which this typestoreuser is attached, or * null if none. */ TypeStore get_store(); /** * A store will call back on invalidate_value when its text has * changed and it therefore knows that any cached type value is * invalid. It is the responsibilty of the type to call fetch_text * and reparse next time the user does a strongly-typed get. */ void invalidate_value(); /** * A store can call uses_invalidate_value to know if calls to * invalidate_value will be fruitful. If uses_invalidate_value * returns false, invalidate_value need never be called. */ boolean uses_invalidate_value(); /** * A store will call back on build_text when it knows its own text * is invalid and needs to fill it in. If forExternal is true, then * the value returned will be used to replenish the store's cache of * the value. Otherwise, the value is being computed for purposes * other than validation, like persistence. * * Also, the only member on TypeStore which may be called while build_text * is on the stack is find_prefix_for_nsuri which must have the * forExternal state passed to it as it is passed here. */ String build_text(NamespaceManager nsm); /** * A store will call back on build_nil after you've called invalidate_nil * and it needs to know what the nil value is. */ boolean build_nil(); /** * A store calls back on invalidate_nilvalue when the value of * the xsi:nil tag has changed. */ void invalidate_nilvalue(); /** * A store calls back on invalidate_element_order when a rearrangment * of sibling elements to the left of this element means that the * nillable value may no longer be valid. */ void invalidate_element_order(); /** * A store will call back on validate_now to force us to look at * the text if we're in an invalid state. This function is allowed * and expected to throw an exception if the text isn't valid for * our type. */ void validate_now(); /** * A store calls back on this call in order to force a disconnect. * After this is done, the object should be considered invalid. */ void disconnect_store(); /** * 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. */ TypeStoreUser create_element_user(QName eltName, QName xsiType); /** * A typestore user can create a new TypeStoreUser instance for * a given attribute child, based on the attribute name. */ TypeStoreUser create_attribute_user(QName attrName); /** * Return the SchemaType which a child element of this name and xsi:type * would be. */ SchemaType get_element_type(QName eltName, QName xsiType); /** * Return the SchemaType which an attribute of this name would be. */ SchemaType get_attribute_type(QName attrName); /** * Returns the default element text, if it's consistent. If it's * not consistent, returns null, and requires a visitor walk. */ String get_default_element_text(QName eltName); /** * Returns the default attribute text for the attribute with * the given name. */ String get_default_attribute_text(QName attrName); /** * Returns the elementflags, if they're consistent. If they're * not, returns -1, and requires a vistor walk. */ int get_elementflags(QName eltName); /** * Returns the flags for an attribute. */ int get_attributeflags(QName attrName); /** * Returns the schema field for an attribute */ SchemaField get_attribute_field(QName attrName); /** * 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. */ boolean is_child_element_order_sensitive(); /** * A typestore user can return the element sort order to use for * insertion operations if needed. Settable elements should * be stored in this order if possible. */ QNameSet get_element_ending_delimiters(QName eltname); /** * A typestore user can return a visitor that is used to compute * default text and elementflags for an arbitrary element. */ TypeStoreVisitor new_visitor(); } xmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/values/TypeStoreUserFactory.java0000644000175000017500000000175411361341572027360 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Every SchemaTypeLoader is actually a TypeStoreUserFactory. * * To get and use the default TypeStoreUserFactory, do the following: * * TypeStoreUser user = ((TypeStoreUserFactory)SchemaTypeLoader.global()).createTypeStoreUser(store); */ public interface TypeStoreUserFactory { TypeStoreUser createTypeStoreUser(); } xmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/values/TypeStoreVisitor.java0000644000175000017500000000307611361341572026550 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 org.apache.xmlbeans.SchemaField; /** * This interface is used by the TypeStore to visit every element in order * to compute nillable flags and default values. */ public interface TypeStoreVisitor { /** * When using a visitor, you must call "visit" on every qname of * every element in order up to the one you're interested in. * * If you're using it for validation, call visit(null) at the end * of the sequence of children. If you're not validating, you can * just walk away once you get the info you need. */ boolean visit(QName eltName); /** * Returns the elementflags for this element. */ int get_elementflags(); /** * Returns the default text for this element. */ String get_default_text(); /** * Returns the schema field for this field. */ SchemaField get_schema_field(); } xmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/values/TypeStore.java0000644000175000017500000003101211361341572025157 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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.impl.common.ValidatorListener; import org.apache.xmlbeans.impl.common.XmlLocale; public interface TypeStore extends NamespaceManager { /** * Creates a new cursor positioned just before the part of the tree * where this TypeStore is located. */ XmlCursor new_cursor(); /** */ void validate ( ValidatorListener vEventSink ); /** * Get the SchemaTypeLoader associated with the store contianing this * TypeStore. */ SchemaTypeLoader get_schematypeloader ( ); /** * Change the type of this store (perhaps by applying xsi:type) and * return the new TypeStoreUser (or old one if the new type is not * different). */ TypeStoreUser change_type ( SchemaType sType ); TypeStoreUser substitute ( QName name, SchemaType sType ); /** * Tells if this store is an attribute or not */ boolean is_attribute ( ); /** * Get the value of xsi:type. Return null if none or this is an attribute * store. */ QName get_xsi_type ( ); /** * A user of a TypeStore calls invalidate_text when the underlying * value has changed and he wants the textstore to call him back with * a fetch_text (TypeStore/TypeStoreUsers work in pairs). */ void invalidate_text(); /** * A user of a TypeStore calls fetch_text when he knows his view * of the text is invalid and he wants to see what the actual text * value is. */ // 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; /** * A user of a TypeStore calls store_text when he wants the TypeStore * to remember the given text immediately. This typically happens when * the user has a noncanonical (but valid) string representation to save, * but doesn't have the storage in which to save it. */ void store_text(String text); /** * Here the TypeStore is responsible for locating the default value. * This is done as follows * (1) go to the parent TypeStoreUser * (2) ask it to get_default_element_text(qname) (or _attribute_), and return it if not null. * (2) otherwise, grab a new TypeStoreUserVisitor via v = parentuser.new_visitor(); * (3) call v.visit(name) on _every_ element qname up to and including this one in order * (4) return the result of v.get_default_text(). */ String compute_default_text(); /** * Here the TypeStore is responsible for figuring if this value is * nillable and/or fixed. This is done by * (1) go to the parent TypeStoreUser * (2) ask it to get_elementflags(qname), and return it if not -1. * (2) otherwise, grab a new TypeStoreUserVisitor via v = parentuser.new_visitor(); * (3) call v.visit(name) on _every_ element qname up to and including this one in order * (4) return the result of v.get_elementflags(). */ int compute_flags(); /** * Tells if this store was created with this option which tells the strongly typed * objects to perform lexical and value validation after a setter is called. */ boolean validate_on_set(); /** * Here the typestore is resposible for finding the schema field for * this object. This is done by * (1) otherwise, grab a new TypeStoreUserVisitor via v = parentuser.new_visitor(); * (2) call v.visit(name) on _every_ element qname up to and including this one in order * (3) return the result of v.get_schema_field(). */ 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 /** * Called when the value has been nilled or unnilled, so the textstore * knows it needs to update the xsi:nil attribute. */ void invalidate_nil(); /** * The TypeStore is reponsible for discovering if this value is nil. * This is done by (1) going to the element and (2) finding the * xsi:nil attribute if present and (3) return true if the collapsed * textual value is either exactly the string "true" or "1". */ boolean find_nil(); /** * Returns the count of elements with the given name owned by this * textstore. */ int count_elements(QName name); /** * Returns the count of elements that match of the names. */ int count_elements(QNameSet names); /** * Returns the TypeStoreUser underneath the ith element with the given * name owned by this textstore, or null if none was found. * * Do not throw an IndexOutOfBoundsException if i is bad - * return null instead. The reason is to allow us to fail * 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); /** * Like find_element_user but accepts a set of names to search for. */ TypeStoreUser find_element_user(QNameSet names, int i); /** * Returns all the TypeStoreUsers corresponding to elements with the * 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); /** * Returns all TypeStoreUsers corresponding to elements with one * of the names is the QNameSet. */ void find_all_element_users(QNameSet name, List fillMeUp); /** * Inserts a new element at the position that will make it * the ith element with the given name owned by this textstore, * and returns a TypeStoreUser for that element. * * Note that if there are no existing elements of the given * name, you may need to call back to discover the proper * ordering to use to insert the first one. Otherwise, * it should be inserted adjacent to existing elements with * the same name. * * 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); /** * Like the above method, except that it inserts an element named * name, after the ith member of set. */ TypeStoreUser insert_element_user(QNameSet set, QName name, int i); /** * Adds a new element at the last position adjacent to existing * elements of the same name. * * 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); /** * Removes the ith element with the given name. * * Should throw an IndexOutOfBoundsException if i < 0 * or if i > # of elts-1. */ void remove_element(QName name, int i); /** * Removes the ith element that matches names. */ void remove_element(QNameSet names, int i); /** * Returns the TypeStoreUser underneath the attribute with the given * name, or null if there is no such attribute. */ // BUGBUG - this should be called find_attribute // BUGBUG - this should be called find_attribute // BUGBUG - this should be called find_attribute // BUGBUG - this should be called find_attribute TypeStoreUser find_attribute_user(QName name); /** * Adds an attribute with the given name and returns a TypeStoreUser * underneath it. Should throw an IndexOutOfBoundsException if there * is already an existing attribute with the given name. */ // BUGBUG - this should be called add_attribute // BUGBUG - this should be called add_attribute // BUGBUG - this should be called add_attribute // BUGBUG - this should be called add_attribute TypeStoreUser add_attribute_user(QName name); /** * Removes the attribute with the given name. */ void remove_attribute(QName name); /** * Copies the contents of the given TypeStore (including attributes, * elements, and mixed content), to the target type store. * * SPECIAL NOTE: The xsi:type attribute should not be removed from * the target or copied from the soruce, and the TypeStoreUser attached * to this TypeStore should not be disconnected. * * This is for implementing obj.set(foo). */ TypeStoreUser copy_contents_from(TypeStore source); /** * Makes a copy of this store. * NOTE: Even if st is NO_TYPE, the store can be a document. This method will make an exact copy. */ TypeStoreUser copy(SchemaTypeLoader schemaTypeLoader, SchemaType schemaType, XmlOptions options); // BUGBUG - Need to use this in the future // /** // * Copies the contents of the given TypeStore (including attributes, // * elemets, mixed content), to the child element given by the given // * name and index. Any TypeStoreUser that might be currently attached // * to that element is disconnected. The xsi:type attribute of the // * element should be set according to the given QName (or deleted if // * the xsitype argument is null) // */ // void copy_to_element( // TypeStore source, QName xsitype, QName name, int i); /** * Copies the contents of the given array of XmlObject (including * attributes, elements, mixed content), over all the elements of the * given name under the current typestore. * * The lengths of the two arrays that are passed should be the same. * * If there are n current elements of the given name and m elements * in the source array, there are several cases for individual elements: * * 1. If i < n and i < m, then the contents of the ith source are copied * underneath the ith element; the ith element is not moved, but its * TypeStoreUser is disconnected. * 2. if i >= n and i < m, then first enough new elements are appended * so that there is an element with the name i, then rule #1 is followed. * 3. if i >= m and i < n, then the element #i and all its contents * are removed. */ void array_setter ( XmlObject[] sources, QName elementName ); /** * Visits all the elements immediately, using the given visitor. * A TypeStoreUser calls this when somebody has requested validation. */ void visit_elements(TypeStoreVisitor visitor); XmlObject[] exec_query ( String queryExpr, XmlOptions options ) throws XmlException; /** * Returns the monitor object, used for synchronizing access to the doc. * @deprecated */ Object get_root_object(); /** * Returns the locale object which is used to manage thread safty and the * gateway requirements for calls into the xml store */ XmlLocale get_locale ( ); } xmlbeans-2.6.0/src/typestore/org/apache/xmlbeans/impl/values/NamespaceManager.java0000644000175000017500000000205711361341572026417 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public interface NamespaceManager extends PrefixResolver { /** * Caled when the user needs a prefix by which to reference a given * Xml namespace. A suggested prefix is passed, which may be null; * the suggestion may be ignored. */ String find_prefix_for_nsuri ( String nsuri, String suggested_prefix ); } xmlbeans-2.6.0/src/zipcompare/0000755000175000017500000000000011361341574014415 5ustar apoapoxmlbeans-2.6.0/src/zipcompare/zipcompare/0000755000175000017500000000000013041512717016562 5ustar apoapoxmlbeans-2.6.0/src/zipcompare/zipcompare/ZipCompare.java0000644000175000017500000001066511361341574021512 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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(); } } } xmlbeans-2.6.0/src/toolschema/0000755000175000017500000000000013041512717014376 5ustar apoapoxmlbeans-2.6.0/src/toolschema/ltgfmt.xsdconfig0000644000175000017500000000155411361341572017610 0ustar apoapo org.apache.xmlbeans.impl.xb.ltgfmt xmlbeans-2.6.0/src/toolschema/xsdownload.xsdconfig0000644000175000017500000000156411361341572020476 0ustar apoapo org.apache.xmlbeans.impl.xb.xsdownload xmlbeans-2.6.0/src/toolschema/substwsdl.xsd0000644000175000017500000000377011361341572017161 0ustar apoapo xmlbeans-2.6.0/src/toolschema/substwsdl.xsdconfig0000644000175000017500000000156711361341572020351 0ustar apoapo org.apache.xmlbeans.impl.xb.substwsdl xmlbeans-2.6.0/src/toolschema/ltgfmt.xsd0000644000175000017500000000453611361341572016425 0ustar apoapo xmlbeans-2.6.0/src/toolschema/xsdownload.xsd0000644000175000017500000000277411361341572017314 0ustar apoapo xmlbeans-2.6.0/src/store/0000755000175000017500000000000011361341571013375 5ustar apoapoxmlbeans-2.6.0/src/store/org/0000755000175000017500000000000011361341572014165 5ustar apoapoxmlbeans-2.6.0/src/store/org/w3c/0000755000175000017500000000000011361341572014661 5ustar apoapoxmlbeans-2.6.0/src/store/org/w3c/dom/0000755000175000017500000000000013041512717015436 5ustar apoapoxmlbeans-2.6.0/src/store/org/w3c/dom/TypeInfo.java0000644000175000017500000000213411361341572020040 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.w3c.dom; public interface TypeInfo { public static final int DERIVATION_EXTENSION = 2; public static final int DERIVATION_LIST = 8; public static final int DERIVATION_RESTRICTION = 1; public static final int DERIVATION_UNION = 4; public String getTypeName ( ); public String getTypeNamespace ( ); public boolean isDerivedFrom ( String typeNamespaceArg, String typeNameArg, int derivationMethod ); }xmlbeans-2.6.0/src/store/org/w3c/dom/DOMConfiguration.java0000644000175000017500000000164011361341572021453 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.w3c.dom; public interface DOMConfiguration { public boolean canSetParameter ( String name, Object value ); public Object getParameter ( String name ); public DOMStringList getParameterNames ( ); public void setParameter ( String name, Object value ); }xmlbeans-2.6.0/src/store/org/w3c/dom/UserDataHandler.java0000644000175000017500000000200011361341572021301 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.w3c.dom; public interface UserDataHandler { public static final short NODE_ADOPTED = 5; public static final short NODE_CLONED = 1; public static final short NODE_DELETED = 3; public static final short NODE_IMPORTED = 2; public static final short NODE_RENAMED = 4; public void handle ( short operation, String key, Object data, Node src, Node dst ); }xmlbeans-2.6.0/src/store/org/w3c/dom/DOMStringList.java0000644000175000017500000000145211361341572020747 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.w3c.dom; public interface DOMStringList { public boolean contains ( String str ); public int getLength ( ); public String item ( int index ); }xmlbeans-2.6.0/src/store/org/apache/0000755000175000017500000000000011361341571015405 5ustar apoapoxmlbeans-2.6.0/src/store/org/apache/xmlbeans/0000755000175000017500000000000011361341571017216 5ustar apoapoxmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/0000755000175000017500000000000011361341571020157 5ustar apoapoxmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/0000755000175000017500000000000013041512717021312 5ustar apoapoxmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/PathDelegate.java0000644000175000017500000000574311361341572024517 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Saaj.java0000644000175000017500000002215711361341572023044 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.Iterator; import java.util.Locale; import javax.xml.transform.Source; 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 org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.w3c.dom.Text; 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 ); Object getSaajData ( Node n ); Element createSoapElement ( QName name, QName parentName ); Element importSoapElement ( Document doc, Element elem, boolean deep, QName parentName ); } 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 ); void soapNode_setValue ( org.apache.xmlbeans.impl.soap.Node node, String value ); SOAPElement soapNode_getParentElement ( org.apache.xmlbeans.impl.soap.Node node ); void soapNode_setParentElement ( org.apache.xmlbeans.impl.soap.Node node, SOAPElement soapElement ); void soapElement_removeContents ( SOAPElement soapElement ); String soapElement_getEncodingStyle ( SOAPElement soapElement ); void soapElement_setEncodingStyle ( SOAPElement soapElement, String encodingStyle ); boolean soapElement_removeNamespaceDeclaration ( SOAPElement soapElement, String prefix ); Iterator soapElement_getAllAttributes ( SOAPElement soapElement ); Iterator soapElement_getChildElements ( SOAPElement parent ); Iterator soapElement_getNamespacePrefixes ( SOAPElement soapElement ); SOAPElement soapElement_addAttribute ( SOAPElement soapElement, Name name, String value ) throws SOAPException; SOAPElement soapElement_addChildElement ( SOAPElement parent, SOAPElement oldChild ) throws SOAPException; SOAPElement soapElement_addChildElement ( SOAPElement soapElement, Name name ) throws SOAPException; SOAPElement soapElement_addChildElement ( SOAPElement soapElement, String localName ) throws SOAPException; SOAPElement soapElement_addChildElement ( SOAPElement soapElement, String localName, String prefix ) throws SOAPException; SOAPElement soapElement_addChildElement ( SOAPElement soapElement, String localName, String prefix, String uri ) throws SOAPException; SOAPElement soapElement_addNamespaceDeclaration ( SOAPElement soapElement, String prefix, String uri ); SOAPElement soapElement_addTextNode ( SOAPElement soapElement, String data ); String soapElement_getAttributeValue ( SOAPElement soapElement, Name name ); Iterator soapElement_getChildElements ( SOAPElement parent, Name name ); Name soapElement_getElementName ( SOAPElement soapElement ); String soapElement_getNamespaceURI ( SOAPElement soapElement, String prefix ); Iterator soapElement_getVisibleNamespacePrefixes ( SOAPElement soapElement ); boolean soapElement_removeAttribute ( SOAPElement soapElement, Name name ); SOAPBody soapEnvelope_addBody ( SOAPEnvelope soapEnvelope ) throws SOAPException; SOAPBody soapEnvelope_getBody ( SOAPEnvelope soapEnvelope ) throws SOAPException; SOAPHeader soapEnvelope_getHeader ( SOAPEnvelope soapEnvelope ) throws SOAPException; SOAPHeader soapEnvelope_addHeader ( SOAPEnvelope soapEnvelope ) throws SOAPException; Name soapEnvelope_createName ( SOAPEnvelope soapEnvelope, String localName ); Name soapEnvelope_createName ( SOAPEnvelope soapEnvelope, String localName, String prefix, String namespaceURI ); Iterator soapHeader_examineAllHeaderElements ( SOAPHeader soapHeader ); Iterator soapHeader_extractAllHeaderElements ( SOAPHeader soapHeader ); Iterator soapHeader_examineHeaderElements ( SOAPHeader soapHeader, String actor ); Iterator soapHeader_examineMustUnderstandHeaderElements ( SOAPHeader soapHeader, String mustUnderstandString ); Iterator soapHeader_extractHeaderElements ( SOAPHeader soapHeader, String actor ); SOAPHeaderElement soapHeader_addHeaderElement ( SOAPHeader soapHeader, Name name ); void soapPart_removeAllMimeHeaders ( SOAPPart soapPart ); void soapPart_removeMimeHeader ( SOAPPart soapPart, String name ); Iterator soapPart_getAllMimeHeaders ( SOAPPart soapPart ); SOAPEnvelope soapPart_getEnvelope ( SOAPPart soapPart ); Source soapPart_getContent ( SOAPPart soapPart ); void soapPart_setContent ( SOAPPart soapPart, Source source ); String[] soapPart_getMimeHeader ( SOAPPart soapPart, String name ); void soapPart_addMimeHeader ( SOAPPart soapPart, String name, String value ); void soapPart_setMimeHeader ( SOAPPart soapPart, String name, String value ); Iterator soapPart_getMatchingMimeHeaders ( SOAPPart soapPart, String[] names ); Iterator soapPart_getNonMatchingMimeHeaders ( SOAPPart soapPart, String[] names ); boolean soapBody_hasFault ( SOAPBody soapBody ); SOAPFault soapBody_addFault ( SOAPBody soapBody ) throws SOAPException; SOAPFault soapBody_getFault ( SOAPBody soapBody ); SOAPBodyElement soapBody_addBodyElement ( SOAPBody soapBody, Name name ); SOAPBodyElement soapBody_addDocument ( SOAPBody soapBody, Document document ); SOAPFault soapBody_addFault ( SOAPBody soapBody, Name name, String s ) throws SOAPException; SOAPFault soapBody_addFault ( SOAPBody soapBody, Name faultCode, String faultString, Locale locale ) throws SOAPException; Detail soapFault_addDetail ( SOAPFault soapFault ) throws SOAPException; Detail soapFault_getDetail ( SOAPFault soapFault ); String soapFault_getFaultActor ( SOAPFault soapFault ); String soapFault_getFaultCode ( SOAPFault soapFault ); Name soapFault_getFaultCodeAsName ( SOAPFault soapFault ); String soapFault_getFaultString ( SOAPFault soapFault ); Locale soapFault_getFaultStringLocale ( SOAPFault soapFault ); void soapFault_setFaultActor ( SOAPFault soapFault, String faultActorString ); void soapFault_setFaultCode ( SOAPFault soapFault, Name faultCodeName ) throws SOAPException; void soapFault_setFaultCode ( SOAPFault soapFault, String faultCode ) throws SOAPException; void soapFault_setFaultString ( SOAPFault soapFault, String faultString ); void soapFault_setFaultString ( SOAPFault soapFault, String faultString, Locale locale ); void soapHeaderElement_setMustUnderstand ( SOAPHeaderElement soapHeaderElement, boolean mustUnderstand ); boolean soapHeaderElement_getMustUnderstand ( SOAPHeaderElement soapHeaderElement ); void soapHeaderElement_setActor ( SOAPHeaderElement soapHeaderElement, String actor ); String soapHeaderElement_getActor ( SOAPHeaderElement soapHeaderElement ); boolean soapText_isComment ( org.apache.xmlbeans.impl.soap.Text text ); DetailEntry detail_addDetailEntry ( Detail detail, Name name ); Iterator detail_getDetailEntries ( Detail detail ); } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Jsr173.java0000644000175000017500000013200111361341572023145 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } } } } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Public2.java0000644000175000017500000002636411361341572023472 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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.impl.store.DomImpl.Dom; import org.apache.xmlbeans.impl.store.Saver.TextSaver; 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 javax.xml.namespace.QName; import org.apache.xmlbeans.SchemaField; import org.apache.xmlbeans.QNameSet; public final class Public2 { private static Locale newLocale ( Saaj saaj ) { XmlOptions options = null; if (saaj != null) { options = new XmlOptions(); options.put( org.apache.xmlbeans.impl.store.Saaj.SAAJ_IMPL, saaj ); } return Locale.getLocale( null, options ); } private static Locale newLocale ( ) { return Locale.getLocale( null, null ); } public static void setSync ( Document doc, boolean sync ) { assert doc instanceof Dom; Locale l = ((Dom) doc).locale(); l._noSync = ! sync; } public static String compilePath ( String path, XmlOptions options ) { return Path.compilePath( path, options ); } public static DOMImplementation getDomImplementation ( ) { return newLocale( ); } public static DOMImplementation getDomImplementation ( Saaj saaj ) { return newLocale( saaj ); } public static Document parse ( String s ) throws XmlException { Locale l = newLocale(); Dom d; if (l.noSync()) { l.enter(); try { d = l.load( s ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { d = l.load( s ); } finally { l.exit(); } } return (Document) d; } public static Document parse ( String s, XmlOptions options ) throws XmlException { Locale l = newLocale(); Dom d; if (l.noSync()) { l.enter(); try { d = l.load( s, options ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { d = l.load( s, options ); } finally { l.exit(); } } return (Document) d; } public static Document parse ( String s, Saaj saaj ) throws XmlException { Locale l = newLocale( saaj ); Dom d; if (l.noSync()) { l.enter(); try { d = l.load( s ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { d = l.load( s ); } finally { l.exit(); } } return (Document) d; } public static Document parse ( InputStream is, XmlOptions options ) throws XmlException, IOException { Locale l = newLocale(); Dom d; if (l.noSync()) { l.enter(); try { d = l.load( is, options ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { d = l.load( is, options ); } finally { l.exit(); } } return (Document) d; } public static Document parse ( InputStream is, Saaj saaj ) throws XmlException, IOException { Locale l = newLocale( saaj ); Dom d; if (l.noSync()) { l.enter(); try { d = l.load( is ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { d = l.load( is ); } finally { l.exit(); } } return (Document) d; } public static Node getNode ( XMLStreamReader s ) { return Jsr173.nodeFromStream( s ); } public static XMLStreamReader getStream ( Node n ) { assert n instanceof Dom; Dom d = (Dom) n; Locale l = d.locale(); if (l.noSync()) { l.enter(); try { return DomImpl.getXmlStreamReader( d ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { return DomImpl.getXmlStreamReader( d ); } finally { l.exit(); } } } public static String save ( Node n ) { return save( n, null ); } public static void save ( Node n, OutputStream os, XmlOptions options ) throws IOException { XmlCursor c = getCursor( n ); c.save( os, options ); c.dispose(); } public static String save ( Node n, XmlOptions options ) { assert n instanceof Dom; Dom d = (Dom) n; Locale l = d.locale(); if (l.noSync()) { l.enter(); try { return saveImpl( d, options ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { return saveImpl( d, options ); } finally { l.exit(); } } } private static String saveImpl ( Dom d, XmlOptions options ) { Cur c = d.tempCur(); String s = new TextSaver( c, options, null ).saveToString(); c.release(); return s; } public static String save ( XmlCursor c ) { return save( c, null ); } public static String save ( XmlCursor xc, XmlOptions options ) { Cursor cursor = (Cursor) xc; Locale l = cursor.locale(); if (l.noSync()) { l.enter(); try { return saveImpl( cursor, options ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { return saveImpl( cursor, options ); } finally { l.exit(); } } } private static String saveImpl ( Cursor cursor, XmlOptions options ) { Cur c = cursor.tempCur(); String s = new TextSaver( c, options, null ).saveToString(); c.release(); return s; } public static XmlCursor newStore ( ) { return newStore( null ); } public static XmlCursor newStore ( Saaj saaj ) { Locale l = newLocale( saaj ); if (l.noSync()) { l.enter(); try { return _newStore( l ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { return _newStore( l ); } finally { l.exit(); } } } public static XmlCursor _newStore ( Locale l ) { Cur c = l.tempCur(); c.createRoot(); Cursor cursor = new Cursor( c ); c.release(); return cursor; } public static XmlCursor getCursor ( Node n ) { assert n instanceof Dom; Dom d = (Dom) n; Locale l = d.locale(); if (l.noSync()) { l.enter(); try { return DomImpl.getXmlCursor( d ); } finally { l.exit(); } } else synchronized ( l ) { l.enter(); try { return DomImpl.getXmlCursor( d ); } finally { l.exit(); } } } public static void dump ( PrintStream o, Dom d ) { d.dump( o ); } public static void dump ( PrintStream o, Node n ) { dump( o, (Dom) n ); } public static void dump ( PrintStream o, XmlCursor c ) { ((Cursor) c).dump( o ); } public static void dump ( PrintStream o, XmlObject x ) { XmlCursor xc = x.newCursor(); Node n = xc.getDomNode(); Dom d = (Dom) n; xc.dispose(); dump( o, d ); } public static void dump ( Dom d ) { dump( System.out, d ); } public static void dump ( Node n ) { dump( System.out, n ); } public static void dump ( XmlCursor c ) { dump( System.out, c ); } public static void dump ( XmlObject x ) { dump( System.out, x ); } private static class TestTypeStoreUser implements TypeStoreUser { TestTypeStoreUser ( String value ) { _value = value; } public void attach_store(TypeStore store) { } public SchemaType get_schema_type() { throw new RuntimeException( "Not impl" ); } public TypeStore get_store() { throw new RuntimeException( "Not impl" ); } public void invalidate_value() { } public boolean uses_invalidate_value() { throw new RuntimeException( "Not impl" ); } public String build_text(NamespaceManager nsm) { return _value; } public boolean build_nil() { throw new RuntimeException( "Not impl" ); } public void invalidate_nilvalue() { throw new RuntimeException( "Not impl" ); } public void invalidate_element_order() { throw new RuntimeException( "Not impl" ); } public void validate_now() { throw new RuntimeException( "Not impl" ); } public void disconnect_store() { throw new RuntimeException( "Not impl" ); } public TypeStoreUser create_element_user(QName eltName, QName xsiType) { return new TestTypeStoreUser( "ELEM" ); } public TypeStoreUser create_attribute_user(QName attrName) { throw new RuntimeException( "Not impl" ); } public String get_default_element_text(QName eltName) { throw new RuntimeException( "Not impl" ); } public String get_default_attribute_text(QName attrName) { throw new RuntimeException( "Not impl" ); } public SchemaType get_element_type(QName eltName, QName xsiType) { throw new RuntimeException( "Not impl" ); } public SchemaType get_attribute_type(QName attrName) { throw new RuntimeException( "Not impl" ); } public int get_elementflags(QName eltName) { throw new RuntimeException( "Not impl" ); } public int get_attributeflags(QName attrName) { throw new RuntimeException( "Not impl" ); } public SchemaField get_attribute_field(QName attrName) { throw new RuntimeException( "Not impl" ); } public boolean is_child_element_order_sensitive() { throw new RuntimeException( "Not impl" ); } public QNameSet get_element_ending_delimiters(QName eltname) { throw new RuntimeException( "Not impl" ); } public TypeStoreVisitor new_visitor() { throw new RuntimeException( "Not impl" ); } private String _value; } public static void test ( ) throws Exception { Xobj x = (Xobj) Public2.parse( "XY" ); Locale l = x._locale; l.enter(); try { 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 ) { e.printStackTrace(); } finally { l.exit(); } } } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Query.java0000644000175000017500000004330512001607641023263 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 { ClassLoader cl = Query.class.getClassLoader(); String id = "META-INF/services/org.apache.xmlbeans.impl.store.QueryDelegate.QueryInterface"; InputStream in = cl.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; } } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Saver.java0000644000175000017500000040001311457660070023240 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } 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 valid in xml character content. See * http://www.w3.org/TR/REC-xml#NT-Char */ private boolean isBadChar ( char ch ) { return ! ( (ch >= 0x20 && ch <= 0xD7FF ) || (ch >= 0xE000 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0x10FFFF) || (ch == 0x9) || (ch == 0xA) || (ch == 0xD) ); } /** * 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= 0x20 && ch <= 0xD7FF ) || (ch >= 0xE000 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0x10FFFF) || (ch == 0x9) || (ch == 0xA) || (ch == 0xD) ); } 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 emitText ( 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 : 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" ); } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/QNameFactory.java0000644000175000017500000000226711361341572024517 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public interface QNameFactory { public QName getQName ( String uri, String local ); public QName getQName ( String uri, String local, String prefix ); public QName getQName ( char[] uriSrc, int uriPos, int uriCch, char[] localSrc, int localPos, int localCch ); public QName getQName ( char[] uriSrc, int uriPos, int uriCch, char[] localSrc, int localPos, int localCch, char[] prefixSrc, int prefixPos, int prefixCch ); } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Path.java0000644000175000017500000005315712001626600023054 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 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; static { ClassLoader cl = Path.class.getClassLoader(); String id = "META-INF/services/org.apache.xmlbeans.impl.store.PathDelegate.SelectPathInterface"; InputStream in = cl.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 synchronized 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; 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; if ((force & USE_XBEAN) != 0) path = getCompiledPathXbean(pathExpr, currentVar, namespaces); if (path == null && (force & USE_XQRL) != 0) path = getCompiledPathXqrl(pathExpr, currentVar); if (path == null && (force & USE_XDK) != 0) path = getCompiledPathXdk(pathExpr, currentVar); if (path == null && (force & USE_DELEGATE) != 0) path = getCompiledPathDelegate(pathExpr, currentVar, namespaces, delIntfName); if (path == null && (force & USE_XQRL2002) != 0) 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); } return path; } static private synchronized 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 synchronized 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 synchronized 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 synchronized 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 synchronized 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 synchronized 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; } } } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Cursor.java0000644000175000017500000033775211361341572023455 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/DomImpl.java0000644000175000017500000051334711361341572023535 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Locale.java0000644000175000017500000030402211714325344023360 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlErrorCodes; 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.InputSource; 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.lang.reflect.Method; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.IOException; 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.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; import javax.xml.namespace.QName; 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.XmlSaxHandler; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; 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.apache.xmlbeans.impl.piccolo.xml.Piccolo; import org.apache.xmlbeans.impl.piccolo.io.FileFormatException; 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(); // Here I check to see if there is a default namespace // mapping which is not empty on a non root container which // is in a namespace. This this case, I do not want to add // this mapping because it could not be persisted out this // way. if (prefix.length() == 0 && uri.length() > 0 && cName != null && cName.getNamespaceURI().length() > 0) { continue; } 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[(_numTempFramesLeft = _tempFrames.length) * 2]; 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 getPiccoloSaxLoader() { SaxLoader piccoloLoader = (SaxLoader) SystemCache.get().getSaxLoader(); if (piccoloLoader == null) { piccoloLoader = PiccoloSaxLoader.newInstance(); SystemCache.get().setSaxLoader(piccoloLoader); } return piccoloLoader; } private static SaxLoader getSaxLoader(XmlOptions options) { 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(); } SaxLoader sl; if (options.hasOption(XmlOptions.LOAD_USE_XMLREADER)) { XMLReader xr = (XMLReader) options.get( XmlOptions.LOAD_USE_XMLREADER); if (xr == null) throw new IllegalArgumentException("XMLReader is null"); sl = new XmlReaderSaxLoader(xr); // I've noticed that most XMLReaders don't like a null EntityResolver... if (er != null) xr.setEntityResolver(er); } else { sl = getPiccoloSaxLoader(); // Piccolo doesnot mind a null entity resolver ... sl.setEntityResolver(er); } return sl; } private static class XmlReaderSaxLoader extends SaxLoader { XmlReaderSaxLoader(XMLReader xr) { super(xr, null); } } private static class PiccoloSaxLoader extends SaxLoader { private PiccoloSaxLoader(Piccolo p) { super(p, p.getStartLocator()); _piccolo = p; } static PiccoloSaxLoader newInstance() { return new PiccoloSaxLoader(new Piccolo()); } void postLoad(Cur c) { XmlDocumentProperties props = getDocProps(c, true); props.setEncoding(_piccolo.getEncoding()); props.setVersion(_piccolo.getVersion()); super.postLoad(c); } private Piccolo _piccolo; } 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 (Piccolo) 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 (FileFormatException e) { _context.abort(); throw new XmlException(e.getMessage(), e); } 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(); } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Xobj.java0000644000175000017500000032372311476266350023102 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/CharUtil.java0000644000175000017500000006512411361341572023702 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Cur.java0000644000175000017500000030004011361341572022705 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() ; i++ ) { if (i== 36) { o.print( "..." ); break; } char ch = s.charAt( i ); 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) + ">" ); } 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; }xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/Validate.java0000644000175000017500000001662011361341572023715 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.ValidatorListener; import javax.xml.stream.Location; import org.apache.xmlbeans.XmlCursor; import javax.xml.namespace.QName; final class Validate implements ValidatorListener.Event { Validate ( Cur c, ValidatorListener sink ) { if (!c.isUserNode()) throw new IllegalStateException( "Inappropriate location to validate" ); _sink = sink; _cur = c; _textCur = c.tempCur(); _hasText = false; _cur.push(); try { process(); } finally { _cur.pop(); _cur = null; _sink = null; _textCur.release(); } } private void process ( ) { emitEvent( ValidatorListener.BEGIN ); if (_cur.isAttr()) { // 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()) emitText(); } else { assert _cur.isContainer(); // Do the attrs of the top container doAttrs(); for ( _cur.next() ; ! _cur.isAtEndOfLastPush() ; _cur.next() ) { switch ( _cur.kind() ) { case Cur.ELEM : 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(); break; default : throw new RuntimeException( "Unexpected kind: " + _cur.kind() ); } } } emitEvent( ValidatorListener.END ); } 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 { if (_cur.isNormalAttr() && !_cur.getUri().equals( Locale._xsi )) _sink.nextEvent( ValidatorListener.ATTR, this ); } while ( _cur.toNextAttr() ); _cur.toParent(); } _sink.nextEvent( ValidatorListener.ENDATTRS, this ); } private void emitText ( ) { assert _cur.isText(); if (_hasText) { if (_oneChunk) { if (_textSb == null) _textSb = new StringBuffer(); else _textSb.delete( 0, _textSb.length() ); assert _textCur.isText(); CharUtil.getString( _textSb, _textCur.getChars( -1 ), _textCur._offSrc, _textCur._cchSrc ); _oneChunk = false; } assert _textSb != null && _textSb.length() > 0; CharUtil.getString( _textSb, _cur.getChars( -1 ), _cur._offSrc, _cur._cchSrc ); } else { _hasText = true; _oneChunk = true; _textCur.moveToCur( _cur ); } } private void emitEvent ( int kind ) { assert kind != ValidatorListener.TEXT; assert kind != ValidatorListener.ATTR || !_hasText; assert kind != ValidatorListener.ENDATTRS || !_hasText; if (_hasText) { _sink.nextEvent( ValidatorListener.TEXT, this ); _hasText = false; } _sink.nextEvent( kind, this ); } public String getText ( ) { if (_cur.isAttr()) return _cur.getValueAsString(); assert _hasText; assert _oneChunk || (_textSb != null && _textSb.length() > 0); assert !_oneChunk || _textCur.isText(); return _oneChunk ? _textCur.getCharsAsString( -1 ) : _textSb.toString(); } public String getText ( int wsr ) { if (_cur.isAttr()) return _cur.getValueAsString( wsr ); assert _hasText; assert _oneChunk || (_textSb != null && _textSb.length() > 0); assert !_oneChunk || _textCur.isText(); if (_oneChunk) return _textCur.getCharsAsString( -1, wsr ); return Locale.applyWhiteSpaceRule( _textSb.toString(), wsr ); } public boolean textIsWhitespace ( ) { if (_cur.isAttr()) { return _cur._locale.getCharUtil().isWhiteSpace( _cur.getFirstChars(), _cur._offSrc, _cur._cchSrc ); } assert _hasText; if (_oneChunk) { return _cur._locale.getCharUtil().isWhiteSpace( _textCur.getChars( -1 ), _textCur._offSrc, _textCur._cchSrc ); } String s = _textSb.toString(); return _cur._locale.getCharUtil().isWhiteSpace( s, 0, s.length() ); } public String getNamespaceForPrefix ( String prefix ) { return _cur.namespaceForPrefix( prefix, true ); } public XmlCursor getLocationAsCursor ( ) { return new Cursor( _cur ); } public Location getLocation ( ) { return null; } public String getXsiType ( ) { return _cur.getAttrValue( Locale._xsiType ); } public String getXsiNil ( ) { return _cur.getAttrValue( Locale._xsiNil ); } public String getXsiLoc ( ) { return _cur.getAttrValue( Locale._xsiLoc ); } public String getXsiNoLoc ( ) { return _cur.getAttrValue( Locale._xsiNoLoc ); } public QName getName ( ) { return _cur.isAtLastPush() ? null : _cur.getName(); } // // // private ValidatorListener _sink; private Cur _cur; // Two ways to accumulate text. First, I can have a Cur positioned at the text. I do this // instead of getting the there there because white space rules are applied at a later point. // 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; private Cur _textCur; private StringBuffer _textSb; }xmlbeans-2.6.0/src/store/org/apache/xmlbeans/impl/store/QueryDelegate.java0000644000175000017500000000535311361341572024725 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeholder/0000755000175000017500000000000011361341570014417 5ustar apoapoxmlbeans-2.6.0/src/typeholder/org/0000755000175000017500000000000011361341570015206 5ustar apoapoxmlbeans-2.6.0/src/typeholder/org/apache/0000755000175000017500000000000011361341570016427 5ustar apoapoxmlbeans-2.6.0/src/typeholder/org/apache/xmlbeans/0000755000175000017500000000000011361341570020240 5ustar apoapoxmlbeans-2.6.0/src/typeholder/org/apache/xmlbeans/impl/0000755000175000017500000000000011361341570021201 5ustar apoapoxmlbeans-2.6.0/src/typeholder/org/apache/xmlbeans/impl/schema/0000755000175000017500000000000013041512717022441 5ustar apoapoxmlbeans-2.6.0/src/typeholder/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java0000644000175000017500000000662611361341570026602 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } } xmlbeans-2.6.0/src/typeimpl/0000755000175000017500000000000011361341573014106 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/0000755000175000017500000000000011361341573014675 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/0000755000175000017500000000000011361341573016116 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/0000755000175000017500000000000011361341574017730 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/0000755000175000017500000000000011365605076020675 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/util/0000755000175000017500000000000013041512717021642 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/util/XsTypeConverter.java0000644000175000017500000006054411361341574025646 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.GDate; import org.apache.xmlbeans.GDateBuilder; import org.apache.xmlbeans.GDateSpecification; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlCalendar; import org.apache.xmlbeans.XmlError; 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.util.Calendar; import java.util.Collection; import java.util.Date; import java.net.URI; 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)); } 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; } }xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/util/Diff.java0000644000175000017500000000373311361341574023367 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.IOException; import java.io.LineNumberReader; import java.io.Reader; import java.util.List; /** * This needs to be here so that it can be accessed by FilerImpl */ public class Diff { public static void readersAsText(Reader r1, String name1, Reader r2, String name2, List diffs) throws IOException { LineNumberReader reader1 = new LineNumberReader(r1); LineNumberReader reader2 = new LineNumberReader(r2); String line1 = reader1.readLine(); String line2 = reader2.readLine(); while (line1 != null && line2 != null) { if (!line1.equals(line2)) { diffs.add("File \"" + name1 + "\" and file \"" + name2 + "\" differ at line " + reader1.getLineNumber() + ":" + "\n" + line1 + "\n========\n" + line2); break; } line1 = reader1.readLine(); line2 = reader2.readLine(); } if (line1 == null && line2 != null) diffs.add("File \"" + name2 + "\" has extra lines at line " + reader2.getLineNumber() + ":\n" + line2); if (line1 != null && line2 == null) diffs.add("File \"" + name1 + "\" has extra lines at line " + reader1.getLineNumber() + ":\n" + line1); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/util/Base64.java0000644000175000017500000003063011361341574023537 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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: Base64.java 111285 2004-12-08 16:54:26Z cezar $ */ 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/util/FilerImpl.java0000644000175000017500000001534011361341574024377 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/util/HexBin.java0000644000175000017500000001105411361341574023667 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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: HexBin.java 125124 2005-01-14 00:23:54Z kkrouse $ */ 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) { 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; }xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java0000644000175000017500000007243111361341574030472 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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.impl.common.ValidatorListener; import org.apache.xmlbeans.impl.common.XmlWhitespace; import org.apache.xmlbeans.impl.common.QNameHelper; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.Location; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.util.StreamReaderDelegate; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * This class is a wrapper over a generic XMLStreamReader that provides validation. * There are 3 cases: *
1) the XMLStreamReader represents a document, it contains only one element document * - in this case the user schema type should be null or it should be a document SchemaType *
2) the XMLStreamReader represents an xml-fragment (content only) - must have at least one user type or xsi:type *
a) it has an xsi:type - if user schema type is available it has to be a base type of xsi:type *
b) it doesn't have xsi:type - user must provide a schema type * otherwise will error and will not do validation *
3) the XMLStreamReader represents a global attribute - i.e. user schema type is null and only one attribute *
* * @author Cezar Andrei (cezar.andrei at bea.com) * Date: Feb 13, 2004 */ 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"); private static final QName XSI_SL = new QName(URI_XSI, "schemaLocation"); private static final QName XSI_NSL = new QName(URI_XSI, "noNamespaceSchemaLocation"); private SchemaType _contentType; private SchemaTypeLoader _stl; private XmlOptions _options; private Collection _errorListener; protected Validator _validator; private final ElementEventImpl _elemEvent; private final AttributeEventImpl _attEvent; private final SimpleEventImpl _simpleEvent; private PackTextXmlStreamReader _packTextXmlStreamReader; private int _state; private final int STATE_FIRSTEVENT = 0; private final int STATE_VALIDATING = 1; private final int STATE_ATTBUFFERING = 2; private final int STATE_ERROR = 3; private List _attNamesList; private List _attValuesList; private SchemaType _xsiType; private int _depth; /** * Default constructor. Use init(...) to set the params. * See {@link #init} */ public ValidatingXMLStreamReader() { super(); _elemEvent = new ElementEventImpl(); _attEvent = new AttributeEventImpl(); _simpleEvent = new SimpleEventImpl(); _packTextXmlStreamReader = new PackTextXmlStreamReader(); } /** * Used in case of reusing the same ValidatinXMLStreamReader object * @param xsr The stream to be validated * @param startWithCurrentEvent Validation will start if true with the current event or if false with the next event in the stream * @param contentType The schemaType of the content. This can be null for document and global Att validation * @param stl SchemaTypeLoader context of validation * @param options Validator options * @param errorListener Errors and warnings listener */ public void init(XMLStreamReader xsr, boolean startWithCurrentEvent, SchemaType contentType, SchemaTypeLoader stl, XmlOptions options, Collection errorListener) { _packTextXmlStreamReader.init(xsr); // setParent(xsr); setParent(_packTextXmlStreamReader); _contentType = contentType; _stl = stl; _options = options; _errorListener = errorListener; // _elemEvent.setXMLStreamReader(xsr); // _attEvent.setXMLStreamReader(xsr); // _simpleEvent.setXMLStreamReader(xsr); _elemEvent.setXMLStreamReader(_packTextXmlStreamReader); _attEvent.setXMLStreamReader(_packTextXmlStreamReader); _simpleEvent.setXMLStreamReader(_packTextXmlStreamReader); _validator = null; _state = STATE_FIRSTEVENT; if (_attNamesList!=null) { _attNamesList.clear(); _attValuesList.clear(); } _xsiType = null; _depth = 0; if (startWithCurrentEvent) { int evType = getEventType(); validate_event(evType); } } private static class PackTextXmlStreamReader extends StreamReaderDelegate implements XMLStreamReader { private boolean _hasBufferedText; private StringBuffer _buffer = new StringBuffer(); private int _textEventType; void init(XMLStreamReader xmlstream) { setParent(xmlstream); _hasBufferedText = false; _buffer.delete(0, _buffer.length()); } public int next() throws XMLStreamException { if (_hasBufferedText) { clearBuffer(); return super.getEventType(); } int evType = super.next(); if (evType == XMLEvent.CHARACTERS || evType == XMLEvent.CDATA || evType == XMLEvent.SPACE) { _textEventType = evType; bufferText(); } return evType; } private void clearBuffer() { _buffer.delete(0, _buffer.length()); _hasBufferedText = false; } private void bufferText() throws XMLStreamException { if (super.hasText()) _buffer.append( super.getText()); _hasBufferedText = true; while (hasNext()) { int evType = super.next(); switch (evType) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: case XMLEvent.SPACE: if (super.hasText()) _buffer.append(super.getText()); case XMLEvent.COMMENT: //ignore continue; default: return; } } } public String getText() { assert _hasBufferedText; return _buffer.toString(); } public int getTextLength() { assert _hasBufferedText; return _buffer.length(); } public int getTextStart() { assert _hasBufferedText; return 0; } public char[] getTextCharacters() { assert _hasBufferedText; return _buffer.toString().toCharArray(); } public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) { assert _hasBufferedText; _buffer.getChars(sourceStart, sourceStart + length, target, targetStart); return length; } public boolean isWhiteSpace() { assert _hasBufferedText; return XmlWhitespace.isAllSpace(_buffer); } public boolean hasText() { if (_hasBufferedText) return true; else return super.hasText(); } public int getEventType() { if (_hasBufferedText) return _textEventType; else return super.getEventType(); } } private static class ElementEventImpl implements ValidatorListener.Event { private static final int BUF_LENGTH = 1024; private char[] _buf = new char[BUF_LENGTH]; private int _length; private boolean _supportForGetTextCharacters = true; private XMLStreamReader _xmlStream; private void setXMLStreamReader(XMLStreamReader xsr) { _xmlStream = xsr; } // can return null, used only to locate errors public XmlCursor getLocationAsCursor() { return null; } public javax.xml.stream.Location getLocation() { return _xmlStream.getLocation(); } // fill up chars with the xsi:type attribute value if there is one othervise return false public String getXsiType() // BEGIN xsi:type { return _xmlStream.getAttributeValue(URI_XSI, "type"); } // fill up chars with xsi:nill attribute value if any public String getXsiNil() // BEGIN xsi:nil { return _xmlStream.getAttributeValue(URI_XSI, "nil"); } // not used curently public String getXsiLoc() // BEGIN xsi:schemaLocation { return _xmlStream.getAttributeValue(URI_XSI, "schemaLocation"); } // not used curently public String getXsiNoLoc() // BEGIN xsi:noNamespaceSchemaLocation { return _xmlStream.getAttributeValue(URI_XSI, "noNamespaceSchemaLocation"); } // On START and ATTR public QName getName() { // avoid construction of a new QName object after the bug in getName() is fixed. if (_xmlStream.hasName()) return new QName(_xmlStream.getNamespaceURI(), _xmlStream.getLocalName()); else return null; } // On TEXT and ATTR public String getText() { _length = 0; addTextToBuffer(); return new String( _buf, 0, _length ); // return _xmlStream.getText(); } public String getText(int wsr) { return XmlWhitespace.collapse( _xmlStream.getText(), wsr ); } public boolean textIsWhitespace() { return _xmlStream.isWhiteSpace(); } public String getNamespaceForPrefix(String prefix) { return _xmlStream.getNamespaceURI(prefix); } private void addTextToBuffer() { int textLength = _xmlStream.getTextLength(); ensureBufferLength(textLength); if (_supportForGetTextCharacters) try { _length = _xmlStream.getTextCharacters(0, _buf, _length, textLength); } catch(Exception e) { _supportForGetTextCharacters = false; } if(!_supportForGetTextCharacters) { System.arraycopy(_xmlStream.getTextCharacters(), _xmlStream.getTextStart(), _buf, _length, textLength); _length = _length + textLength; } } 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 static final class AttributeEventImpl implements ValidatorListener.Event { private int _attIndex; private XMLStreamReader _xmlStream; private void setXMLStreamReader(XMLStreamReader xsr) { _xmlStream = xsr; } // can return null, used only to locate errors public XmlCursor getLocationAsCursor() { return null; } public javax.xml.stream.Location getLocation() { return _xmlStream.getLocation(); } // fill up chars with the xsi:type attribute value if there is one othervise return false public String getXsiType() // BEGIN xsi:type { throw new IllegalStateException(); } // fill up chars with xsi:nill attribute value if any public String getXsiNil() // BEGIN xsi:nil { throw new IllegalStateException(); } // not used curently public String getXsiLoc() // BEGIN xsi:schemaLocation { throw new IllegalStateException(); } // not used curently public String getXsiNoLoc() // BEGIN xsi:noNamespaceSchemaLocation { throw new IllegalStateException(); } // On START and ATTR public QName getName() { assert _xmlStream.isStartElement() : "Not on Start Element."; String uri = _xmlStream.getAttributeNamespace(_attIndex); QName qn = new QName(uri==null ? "" : uri, _xmlStream.getAttributeLocalName(_attIndex)); //System.out.println(" Att QName: " + qn); return qn; } // On TEXT and ATTR public String getText() { assert _xmlStream.isStartElement() : "Not on Start Element."; return _xmlStream.getAttributeValue(_attIndex); } public String getText(int wsr) { assert _xmlStream.isStartElement() : "Not on Start Element."; return XmlWhitespace.collapse( _xmlStream.getAttributeValue(_attIndex), wsr ); } public boolean textIsWhitespace() { throw new IllegalStateException(); } public String getNamespaceForPrefix(String prefix) { assert _xmlStream.isStartElement() : "Not on Start Element."; return _xmlStream.getNamespaceURI(prefix); } private void setAttributeIndex(int attIndex) { _attIndex = attIndex; } } /** * This is used as implementation of Event for validating global attributes * and for pushing the buffered attributes */ private static final class SimpleEventImpl implements ValidatorListener.Event { private String _text; private QName _qname; private XMLStreamReader _xmlStream; private void setXMLStreamReader(XMLStreamReader xsr) { _xmlStream = xsr; } // should return null, getLocation will be used, used only to locate errors public XmlCursor getLocationAsCursor() { return null; } public javax.xml.stream.Location getLocation() { return _xmlStream.getLocation(); } // fill up chars with the xsi:type attribute value if there is one othervise return false public String getXsiType() // BEGIN xsi:type { return null; } // fill up chars with xsi:nill attribute value if any public String getXsiNil() // BEGIN xsi:nil { return null; } // not used curently public String getXsiLoc() // BEGIN xsi:schemaLocation { return null; } // not used curently public String getXsiNoLoc() // BEGIN xsi:noNamespaceSchemaLocation { return null; } // On START and ATTR public QName getName() { return _qname; } // On TEXT and ATTR public String getText() { return _text; } public String getText(int wsr) { return XmlWhitespace.collapse( _text, wsr ); } public boolean textIsWhitespace() { return false; } public String getNamespaceForPrefix(String prefix) { return _xmlStream.getNamespaceURI(prefix); } } /* public methods in XMLStreamReader */ public Object getProperty(String s) throws IllegalArgumentException { return super.getProperty(s); } public int next() throws XMLStreamException { int evType = super.next(); //debugEvent(evType); validate_event(evType); return evType; } private void validate_event(int evType) { if (_state==STATE_ERROR) return; if (_depth<0) throw new IllegalArgumentException("ValidatingXMLStreamReader cannot go further than the subtree is was initialized on."); switch(evType) { case XMLEvent.START_ELEMENT: _depth++; if (_state == STATE_ATTBUFFERING) pushBufferedAttributes(); if (_validator==null) { // avoid construction of a new QName object after the bug in getName() is fixed. QName qname = new QName(getNamespaceURI(), getLocalName()); if (_contentType==null) _contentType = typeForGlobalElement(qname); if (_state==STATE_ERROR) break; initValidator(_contentType); _validator.nextEvent(Validator.BEGIN, _elemEvent); } _validator.nextEvent(Validator.BEGIN, _elemEvent); int attCount = getAttributeCount(); validate_attributes(attCount); break; case XMLEvent.ATTRIBUTE: if (getAttributeCount()==0) break; if (_state == STATE_FIRSTEVENT || _state == STATE_ATTBUFFERING) { // buffer all Attributes for (int i=0; i 1 than the validator will add an error } else { addError("No content type provided for validation of a content model."); _state = STATE_ERROR; return; } } // here validationType is the right type, start pushing all acumulated attributes initValidator(validationType); _validator.nextEvent(Validator.BEGIN, _simpleEvent); // validate attributes from _attNamesList validate_attributes(_attNamesList.size()); _attNamesList = null; _attValuesList = null; _state = STATE_VALIDATING; } private boolean isSpecialAttribute(QName qn) { if (qn.getNamespaceURI().equals(URI_XSI)) return qn.getLocalPart().equals(XSI_TYPE.getLocalPart()) || qn.getLocalPart().equals(XSI_NIL.getLocalPart()) || qn.getLocalPart().equals(XSI_SL.getLocalPart()) || qn.getLocalPart().equals(XSI_NSL.getLocalPart()); return false; } /** * Initializes the validator for the given schemaType * @param schemaType */ private void initValidator(SchemaType schemaType) { assert schemaType!=null; _validator = new Validator(schemaType, null, _stl, _options, _errorListener); } private SchemaType typeForGlobalElement(QName qname) { assert qname!=null; SchemaType docType = _stl.findDocumentType(qname); if (docType==null) { addError("Schema document type not found for element '" + qname + "'."); _state = STATE_ERROR; } return docType; } private void addError(String msg) { String source = null; Location location = getLocation(); if (location != null) { source = location.getPublicId(); if (source==null) source = location.getSystemId(); _errorListener.add(XmlError.forLocation(msg, source, location)); } else _errorListener.add(XmlError.forMessage(msg)); } protected void validate_attributes(int attCount) { for(int i=0; i 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/0000755000175000017500000000000013041512717022164 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlLongImpl.java0000644000175000017500000000141611361341573025236 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlLong; public class XmlLongImpl extends JavaLongHolder implements XmlLong { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyTypeImpl.java0000644000175000017500000000176511361341573025737 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaType; /** * This class implements the anyType for XML. * */ public class XmlAnyTypeImpl extends XmlComplexContentImpl implements XmlObject { public XmlAnyTypeImpl() { super(type); } public XmlAnyTypeImpl(SchemaType type) { super(type); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java0000644000175000017500000032557011361341573025530 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlTimeImpl.java0000644000175000017500000000172411361341573025237 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlTime; import org.apache.xmlbeans.SchemaType; public class XmlTimeImpl extends JavaGDateHolderEx implements XmlTime { public XmlTimeImpl() { super(XmlTime.type, false); } public XmlTimeImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlEntityImpl.java0000644000175000017500000000174111361341573025614 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlENTITY; import org.apache.xmlbeans.SchemaType; public class XmlEntityImpl extends JavaStringHolderEx implements XmlENTITY { public XmlEntityImpl() { super(XmlENTITY.type, false); } public XmlEntityImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDecimalImpl.java0000644000175000017500000000143111361341573025672 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDecimal; public class XmlDecimalImpl extends JavaDecimalHolder implements XmlDecimal { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaNotationHolderEx.java0000644000175000017500000001052511361341573027065 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlErrorCodes; import org.apache.xmlbeans.impl.common.ValidationContext; import org.apache.xmlbeans.impl.common.PrefixResolver; import org.apache.xmlbeans.impl.common.QNameHelper; import javax.xml.namespace.QName; public abstract class JavaNotationHolderEx extends JavaNotationHolder { private SchemaType _schemaType; public SchemaType schemaType() { return _schemaType; } public JavaNotationHolderEx(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); } protected void set_notation(String v) { set_text(v); } protected void set_xmlanysimple(XmlAnySimpleType value) { QName v; if (_validateOnSet()) { v = validateLexical(value.getStringValue(), _schemaType, _voorVc, NamespaceContext.getCurrent()); if (v != null) validateValue(v, _schemaType, _voorVc); } else v = JavaNotationHolder.validateLexical(value.getStringValue(), _voorVc, NamespaceContext.getCurrent()); super.set_QName(v); } public static QName validateLexical(String v, SchemaType sType, ValidationContext context, PrefixResolver resolver) { QName name = JavaQNameHolder.validateLexical(v, context, resolver); // 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[] { "NOTATION", v, QNameHelper.readable(sType) }); } } check(v, sType); return name; } private static boolean check(String v, SchemaType sType) { // check against length XmlObject len = sType.getFacet(SchemaType.FACET_LENGTH); if (len != null) { int m = ((XmlObjectBase)len).getBigIntegerValue().intValue(); if (!(v.length() != m)) return false; } // 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)) return false; } // 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)) return false; } return true; } public static void validateValue(QName v, SchemaType sType, ValidationContext context) { XmlObject[] vals = sType.getEnumerationValues(); if (vals != null) { for (int i = 0; i < vals.length; i++) if (v.equals(((XmlObjectBase)vals[i]).getQNameValue())) return; context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, new Object[] { "NOTATION", v, QNameHelper.readable(sType) }); } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGYearMonthImpl.java0000644000175000017500000000177011361341573026357 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlGYearMonth; public class XmlGYearMonthImpl extends JavaGDateHolderEx implements XmlGYearMonth { public XmlGYearMonthImpl() { super(XmlGYearMonth.type, false); } public XmlGYearMonthImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java0000644000175000017500000001364011365604634026674 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNonNegativeIntegerImpl.java0000644000175000017500000000205211361341573030067 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNonNegativeInteger; import org.apache.xmlbeans.SchemaType; public class XmlNonNegativeIntegerImpl extends JavaIntegerHolderEx implements XmlNonNegativeInteger { public XmlNonNegativeIntegerImpl() { super(XmlNonNegativeInteger.type, false); } public XmlNonNegativeIntegerImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNormalizedStringImpl.java0000644000175000017500000000203411361341573027627 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNormalizedString; public class XmlNormalizedStringImpl extends JavaStringHolderEx implements XmlNormalizedString { public XmlNormalizedStringImpl() { super(XmlNormalizedString.type, false); } public XmlNormalizedStringImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringRestriction.java0000644000175000017500000000165111361341573027212 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlString; public class XmlStringRestriction extends JavaStringHolderEx implements XmlString { public XmlStringRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNameImpl.java0000644000175000017500000000172511361341573025222 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlName; public class XmlNameImpl extends JavaStringHolderEx implements XmlName { public XmlNameImpl() { super(XmlName.type, false); } public XmlNameImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java0000644000175000017500000000637011361341573026375 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolder.java0000644000175000017500000000671511361341573026050 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDateTimeImpl.java0000644000175000017500000000175411361341573026040 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDateTime; public class XmlDateTimeImpl extends JavaGDateHolderEx implements XmlDateTime { public XmlDateTimeImpl() { super(XmlDateTime.type, false); } public XmlDateTimeImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java0000644000175000017500000000176311361341573031000 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlValueDisconnectedException extends RuntimeException { XmlValueDisconnectedException ( ) { } XmlValueDisconnectedException ( String message ) { super( message ); } XmlValueDisconnectedException ( String message, Throwable cause ) { super( message, cause ); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java0000644000175000017500000000701711361341573026211 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeRestriction.java0000644000175000017500000000200611361341573030502 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlAnySimpleTypeRestriction extends XmlAnySimpleTypeImpl { public XmlAnySimpleTypeRestriction(SchemaType type, boolean complex) { _schemaType = type; initComplexType(complex, false); } private SchemaType _schemaType; public SchemaType schemaType() { return _schemaType; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDurationImpl.java0000644000175000017500000000176011361341573026126 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDuration; import org.apache.xmlbeans.SchemaType; public class XmlDurationImpl extends JavaGDurationHolderEx implements XmlDuration { public XmlDurationImpl() { super(XmlDuration.type, false); } public XmlDurationImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntegerImpl.java0000644000175000017500000000143211361341573025732 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlInteger; public class XmlIntegerImpl extends JavaIntegerHolder implements XmlInteger { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedByteImpl.java0000644000175000017500000000200211361341573026727 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlUnsignedByte; import org.apache.xmlbeans.SchemaType; public class XmlUnsignedByteImpl extends JavaIntHolderEx implements XmlUnsignedByte { public XmlUnsignedByteImpl() { super(XmlUnsignedByte.type, false); } public XmlUnsignedByteImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlShortImpl.java0000644000175000017500000000173011361341573025435 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlShort; import org.apache.xmlbeans.SchemaType; public class XmlShortImpl extends JavaIntHolderEx implements XmlShort { public XmlShortImpl() { super(XmlShort.type, false); } public XmlShortImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java0000644000175000017500000000770111361341573026341 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlHexBinaryRestriction.java0000644000175000017500000000167011361341573027636 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlHexBinary; public class XmlHexBinaryRestriction extends JavaHexBinaryHolderEx implements XmlHexBinary { public XmlHexBinaryRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGDayImpl.java0000644000175000017500000000172411361341573025165 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlGDay; import org.apache.xmlbeans.SchemaType; public class XmlGDayImpl extends JavaGDateHolderEx implements XmlGDay { public XmlGDayImpl() { super(XmlGDay.type, false); } public XmlGDayImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringEnumeration.java0000644000175000017500000000166411361341573027177 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlString; public class XmlStringEnumeration extends JavaStringEnumerationHolderEx implements XmlString { public XmlStringEnumeration(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNmTokensImpl.java0000644000175000017500000000174511361341573026102 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNMTOKENS; public class XmlNmTokensImpl extends XmlListImpl implements XmlNMTOKENS { public XmlNmTokensImpl() { super(XmlNMTOKENS.type, false);} public XmlNmTokensImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueNotSupportedException.java0000644000175000017500000000201411361341573031032 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlError; public class XmlValueNotSupportedException extends XmlValueOutOfRangeException { public XmlValueNotSupportedException() {} public XmlValueNotSupportedException(String message) { super(message); } public XmlValueNotSupportedException(String code, Object[] args) { super(XmlError.formattedMessage(code, args)); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java0000644000175000017500000001222311361341573026330 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGMonthImpl.java0000644000175000017500000000174011361341573025533 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlGMonth; public class XmlGMonthImpl extends JavaGDateHolderEx implements XmlGMonth { public XmlGMonthImpl() { super(XmlGMonth.type, false); } public XmlGMonthImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlFloatImpl.java0000644000175000017500000000142211361341573025401 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlFloat; public class XmlFloatImpl extends JavaFloatHolder implements XmlFloat { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedIntImpl.java0000644000175000017500000000177511361341573026576 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlUnsignedInt; import org.apache.xmlbeans.SchemaType; public class XmlUnsignedIntImpl extends JavaLongHolderEx implements XmlUnsignedInt { public XmlUnsignedIntImpl() { super(XmlUnsignedInt.type, false); } public XmlUnsignedIntImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java0000644000175000017500000006042311361341573025432 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlByteImpl.java0000644000175000017500000000172211361341573025242 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlByte; import org.apache.xmlbeans.SchemaType; public class XmlByteImpl extends JavaIntHolderEx implements XmlByte { public XmlByteImpl() { super(XmlByte.type, false); } public XmlByteImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlQNameRestriction.java0000644000175000017500000000164411361341573026747 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlQName; public class XmlQNameRestriction extends JavaQNameHolderEx implements XmlQName { public XmlQNameRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlListImpl.java0000644000175000017500000002477711361341573025271 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNotationImpl.java0000644000175000017500000000143511361341573026133 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNOTATION; public class XmlNotationImpl extends JavaNotationHolder implements XmlNOTATION { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java0000644000175000017500000001160711361341573026300 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlObject; import org.apache.xmlbeans.XmlCursor; import java.util.ArrayList; import java.util.Map; import java.lang.reflect.Proxy; import java.lang.ref.SoftReference; import org.apache.xmlbeans.xml.stream.StartElement; public class NamespaceContext implements PrefixResolver { private static final int TYPE_STORE = 1; private static final int XML_OBJECT = 2; private static final int MAP = 3; private static final int START_ELEMENT = 4; private static final int RESOLVER = 5; private Object _obj; private int _code; public NamespaceContext(Map prefixToUriMap) { _code = MAP; _obj = prefixToUriMap; } public NamespaceContext(TypeStore typeStore) { _code = TYPE_STORE; _obj = typeStore; } public NamespaceContext(XmlObject xmlObject) { _code = XML_OBJECT; _obj = xmlObject; } public NamespaceContext(StartElement start) { _code = START_ELEMENT; _obj = start; } public NamespaceContext(PrefixResolver resolver) { _code = RESOLVER; _obj = resolver; } /** * Stack management if (heaven help us) we ever need to do * nested compilation of schema type system. */ private static final class NamespaceContextStack { NamespaceContext current; ArrayList stack = new ArrayList(); final void push(NamespaceContext next) { stack.add(current); current = next; } final void pop() { current = (NamespaceContext)stack.get(stack.size() - 1); stack.remove(stack.size() - 1); } } private static ThreadLocal tl_namespaceContextStack = new ThreadLocal(); private static NamespaceContextStack getNamespaceContextStack() { NamespaceContextStack namespaceContextStack = (NamespaceContextStack) tl_namespaceContextStack.get(); if (namespaceContextStack==null) { namespaceContextStack = new NamespaceContextStack(); tl_namespaceContextStack.set(namespaceContextStack); } return namespaceContextStack; } public static void push(NamespaceContext next) { getNamespaceContextStack().push(next); } public static void pop() { NamespaceContextStack nsContextStack = getNamespaceContextStack(); nsContextStack.pop(); if (nsContextStack.stack.size()==0) tl_namespaceContextStack.set(null); } public static PrefixResolver getCurrent() { return getNamespaceContextStack().current; } public String getNamespaceForPrefix(String prefix) { if (prefix != null && prefix.equals("xml")) return "http://www.w3.org/XML/1998/namespace"; switch (_code) { case XML_OBJECT: { TypeStoreUser impl; Object obj = _obj; if (Proxy.isProxyClass(obj.getClass())) obj = Proxy.getInvocationHandler(obj); if (obj instanceof TypeStoreUser) return ((TypeStoreUser)obj).get_store().getNamespaceForPrefix(prefix); XmlCursor cur = ((XmlObject)_obj).newCursor(); if (cur != null) { if (cur.currentTokenType() == XmlCursor.TokenType.ATTR) cur.toParent(); try { return cur.namespaceForPrefix(prefix); } finally { cur.dispose(); } } } case MAP: return (String)((Map)_obj).get(prefix); case TYPE_STORE: return ((TypeStore)_obj).getNamespaceForPrefix(prefix); case START_ELEMENT: return ((StartElement)_obj).getNamespaceUri(prefix); case RESOLVER: return ((PrefixResolver)_obj).getNamespaceForPrefix(prefix); default: assert false : "Improperly initialized NamespaceContext."; return null; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyUriImpl.java0000644000175000017500000000137711361341573025554 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlAnyUriImpl extends JavaUriHolder implements org.apache.xmlbeans.XmlAnyURI { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdRefsImpl.java0000644000175000017500000000173111361341573025513 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlIDREFS; public class XmlIdRefsImpl extends XmlListImpl implements XmlIDREFS { public XmlIdRefsImpl() { super(XmlIDREFS.type, false); } public XmlIdRefsImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolder.java0000644000175000017500000000457611361341573026365 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlErrorCodes; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlBoolean; import org.apache.xmlbeans.impl.common.ValidationContext; public abstract class JavaBooleanHolder extends XmlObjectBase { public SchemaType schemaType() { return BuiltinSchemaTypeSystem.ST_BOOLEAN; } private boolean _value; // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- // gets raw text value protected String compute_text(NamespaceManager nsm) { return _value ? "true" : "false"; } protected void set_text(String s) { _value = validateLexical(s, _voorVc); } public static boolean validateLexical(String v, ValidationContext context) { if (v.equals("true") || v.equals("1")) return true; if (v.equals("false") || v.equals("0")) return false; context.invalid(XmlErrorCodes.BOOLEAN, new Object[]{ v }); return false; } protected void set_nil() { _value = false; } // numerics: fractional public boolean getBooleanValue() { check_dated(); return _value; } // setters protected void set_boolean(boolean f) { _value = f; } // comparators protected int compare_to(XmlObject i) { // no ordering defined between true and false return _value == ((XmlBoolean)i).getBooleanValue() ? 0 : 2; } protected boolean equal_to(XmlObject i) { return _value == ((XmlBoolean)i).getBooleanValue(); } protected int value_hash_code() { return _value ? 957379554 : 676335975; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyUriRestriction.java0000644000175000017500000000162411361341573027153 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlAnyUriRestriction extends JavaUriHolderEx implements org.apache.xmlbeans.XmlAnyURI { public XmlAnyUriRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringEnumerationHolderEx.java0000644000175000017500000000430511361341573030746 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.StringEnumAbstractBase; import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.impl.common.ValidationContext; import org.apache.xmlbeans.impl.common.QNameHelper; public abstract class JavaStringEnumerationHolderEx extends JavaStringHolderEx { public JavaStringEnumerationHolderEx(SchemaType type, boolean complex) { super(type, complex); } private StringEnumAbstractBase _val; // update the intval when setting via text, nil. protected void set_text(String s) { StringEnumAbstractBase se = schemaType().enumForString(s); if (se == null) throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_ENUM_VALID, new Object[] { "string", s, QNameHelper.readable(schemaType()) }); super.set_text(s); _val = se; } public static void validateLexical(String v, SchemaType sType, ValidationContext context) { JavaStringHolderEx.validateLexical(v, sType, context); } protected void set_nil() { _val = null; super.set_nil(); } // set/get the enum public StringEnumAbstractBase getEnumValue() { check_dated(); return _val; } protected void set_enum(StringEnumAbstractBase se) { Class ejc = schemaType().getEnumJavaClass(); if (ejc != null && !se.getClass().equals(ejc)) throw new XmlValueOutOfRangeException(); super.set_text(se.toString()); _val = se; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDateImpl.java0000644000175000017500000000172411361341573025216 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDate; import org.apache.xmlbeans.SchemaType; public class XmlDateImpl extends JavaGDateHolderEx implements XmlDate { public XmlDateImpl() { super(XmlDate.type, false); } public XmlDateImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDoubleRestriction.java0000644000175000017500000000165111361341573027156 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDouble; import org.apache.xmlbeans.SchemaType; public class XmlDoubleRestriction extends JavaDoubleHolderEx implements XmlDouble { public XmlDoubleRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolder.java0000644000175000017500000000660211361341573025530 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGYearImpl.java0000644000175000017500000000173111361341573025346 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlGYear; public class XmlGYearImpl extends JavaGDateHolderEx implements XmlGYear { public XmlGYearImpl() { super(XmlGYear.type, false); } public XmlGYearImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlTokenImpl.java0000644000175000017500000000173311361341573025421 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlToken; public class XmlTokenImpl extends JavaStringHolderEx implements XmlToken { public XmlTokenImpl() { super(XmlToken.type, false); } public XmlTokenImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDecimalRestriction.java0000644000175000017500000000165611361341573027307 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDecimal; import org.apache.xmlbeans.SchemaType; public class XmlDecimalRestriction extends JavaDecimalHolderEx implements XmlDecimal { public XmlDecimalRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedLongImpl.java0000644000175000017500000000200611361341573026727 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlUnsignedLong; import org.apache.xmlbeans.SchemaType; public class XmlUnsignedLongImpl extends JavaIntegerHolderEx implements XmlUnsignedLong { public XmlUnsignedLongImpl() { super(XmlUnsignedLong.type, false); } public XmlUnsignedLongImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java0000644000175000017500000001036311361341573026666 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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]; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlQNameImpl.java0000644000175000017500000000142211361341573025335 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlQName; public class XmlQNameImpl extends JavaQNameHolder implements XmlQName { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java0000644000175000017500000000773011361341573026510 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBooleanImpl.java0000644000175000017500000000143111361341573025713 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlBoolean; public class XmlBooleanImpl extends JavaBooleanHolder implements XmlBoolean { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java0000644000175000017500000001014111361341573027155 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlLanguageImpl.java0000644000175000017500000000175411361341573026067 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlLanguage; import org.apache.xmlbeans.SchemaType; public class XmlLanguageImpl extends JavaStringHolderEx implements XmlLanguage { public XmlLanguageImpl() { super(XmlLanguage.type, false); } public XmlLanguageImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java0000644000175000017500000011262411361341573027305 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 ] ); } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/StringEnumValue.java0000644000175000017500000000153211361341573026123 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.StringEnumAbstractBase; public class StringEnumValue extends StringEnumAbstractBase { public StringEnumValue(String s, int i) { super(s, i); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntegerRestriction.java0000644000175000017500000000165611361341573027346 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlInteger; public class XmlIntegerRestriction extends JavaIntegerHolderEx implements XmlInteger { public XmlIntegerRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64Holder.java0000644000175000017500000001043611361341573026022 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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]; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlPositiveIntegerImpl.java0000644000175000017500000000202711361341573027456 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlPositiveInteger; import org.apache.xmlbeans.SchemaType; public class XmlPositiveIntegerImpl extends JavaIntegerHolderEx implements XmlPositiveInteger { public XmlPositiveIntegerImpl() { super(XmlPositiveInteger.type, false); } public XmlPositiveIntegerImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedShortImpl.java0000644000175000017500000000200711361341573027130 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlUnsignedShort; import org.apache.xmlbeans.SchemaType; public class XmlUnsignedShortImpl extends JavaIntHolderEx implements XmlUnsignedShort { public XmlUnsignedShortImpl() { super(XmlUnsignedShort.type, false); } public XmlUnsignedShortImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java0000644000175000017500000000405411361341573026651 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlErrorCodes; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.impl.common.ValidationContext; import org.apache.xmlbeans.impl.common.QNameHelper; public abstract class JavaBooleanHolderEx extends JavaBooleanHolder { private SchemaType _schemaType; public SchemaType schemaType() { return _schemaType; } 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) { // the only new facet that can apply to booleans is pattern! if (!sType.matchPatternFacet(v)) context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, new Object[] { "boolean", v, QNameHelper.readable(sType) }); } public JavaBooleanHolderEx(SchemaType type, boolean complex) { _schemaType = type; initComplexType(complex, false); } protected void set_text(String s) { if (_validateOnSet()) validatePattern(s, _schemaType, _voorVc); super.set_text(s); } protected void validate_simpleval(String lexical, ValidationContext ctx) { validateLexical(lexical, schemaType(), ctx); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueNotNillableException.java0000644000175000017500000000135011361341573030571 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlValueNotNillableException extends RuntimeException { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolder.java0000644000175000017500000000372411361341573025537 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlAnyURI; import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.impl.common.ValidationContext; import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; public abstract class JavaUriHolder extends XmlObjectBase { public JavaUriHolder() {} public SchemaType schemaType() { return BuiltinSchemaTypeSystem.ST_ANY_URI; } private String _value; public String compute_text(NamespaceManager nsm) { return _value == null ? "" : _value; } protected void set_text(String s) { if (_validateOnSet()) validateLexical(s, _voorVc); _value = s; } public static void validateLexical(String v, ValidationContext context) { // Enough validation to get schema for schema working if (v.startsWith( "##" )) context.invalid(XmlErrorCodes.ANYURI, new Object[] { v }); } protected void set_nil() { _value = null; } // string setter and getter already handled by XmlObjectBase // comparators protected boolean equal_to(XmlObject obj) { return _value.equals(((XmlAnyURI)obj).getStringValue()); } protected int value_hash_code() { return _value.hashCode(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java0000644000175000017500000001420511361341573025775 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java0000644000175000017500000001262711361341573027173 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java0000644000175000017500000001062011361341573026534 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java0000644000175000017500000000431211361341573027100 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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()); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringImpl.java0000644000175000017500000000142611361341573025606 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlString; public class XmlStringImpl extends JavaStringHolder implements XmlString { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaNotationHolder.java0000644000175000017500000000177511361341573026577 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.impl.schema.BuiltinSchemaTypeSystem; public abstract class JavaNotationHolder extends XmlQNameImpl { public SchemaType schemaType() { return BuiltinSchemaTypeSystem.ST_NOTATION; } // protected int get_wscanon_rule() // { return SchemaType.WS_PRESERVE; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntImpl.java0000644000175000017500000000141211361341573025065 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlInt; public class XmlIntImpl extends JavaIntHolder implements XmlInt { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlEntitiesImpl.java0000644000175000017500000000174611361341573026131 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlENTITIES; public class XmlEntitiesImpl extends XmlListImpl implements XmlENTITIES { public XmlEntitiesImpl() { super(XmlENTITIES.type, false); } public XmlEntitiesImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBooleanRestriction.java0000644000175000017500000000165611361341573027330 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlBoolean; import org.apache.xmlbeans.SchemaType; public class XmlBooleanRestriction extends JavaBooleanHolderEx implements XmlBoolean { public XmlBooleanRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java0000644000175000017500000001204311361341573026026 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java0000644000175000017500000001013011361341573026306 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlFloatRestriction.java0000644000175000017500000000164411361341573027013 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlFloat; import org.apache.xmlbeans.SchemaType; public class XmlFloatRestriction extends JavaFloatHolderEx implements XmlFloat { public XmlFloatRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolder.java0000644000175000017500000000331011361341573026235 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBase64BinaryRestriction.java0000644000175000017500000000170111361341573030131 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlBase64BinaryRestriction extends JavaBase64HolderEx implements XmlBase64Binary { public XmlBase64BinaryRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java0000644000175000017500000002272511361341573026263 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java0000644000175000017500000001347711361341573026035 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntRestriction.java0000644000175000017500000000163211361341573026475 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlInt; public class XmlIntRestriction extends JavaIntHolderEx implements XmlInt { public XmlIntRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNotationRestriction.java0000644000175000017500000000166311361341573027542 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNOTATION; import org.apache.xmlbeans.SchemaType; public class XmlNotationRestriction extends JavaNotationHolderEx implements XmlNOTATION { public XmlNotationRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdRefImpl.java0000644000175000017500000000173311361341573025332 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlIDREF; public class XmlIdRefImpl extends JavaStringHolderEx implements XmlIDREF { public XmlIdRefImpl() { super(XmlIDREF.type, false); } public XmlIdRefImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueOutOfRangeException.java0000644000175000017500000000200111361341573030371 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlError; public class XmlValueOutOfRangeException extends IllegalArgumentException { public XmlValueOutOfRangeException() {} public XmlValueOutOfRangeException(String message) { super(message); } public XmlValueOutOfRangeException(String code, Object[] args) { super(XmlError.formattedMessage(code, args)); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlLongRestriction.java0000644000175000017500000000163711361341573026647 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlLong; public class XmlLongRestriction extends JavaLongHolderEx implements XmlLong { public XmlLongRestriction(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlHexBinaryImpl.java0000644000175000017500000000144211361341573026227 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlHexBinary; public class XmlHexBinaryImpl extends JavaHexBinaryHolder implements XmlHexBinary { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java0000644000175000017500000001623011361341573026627 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java0000644000175000017500000001346111361341573026173 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolder.java0000644000175000017500000000625711361341573025703 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNmTokenImpl.java0000644000175000017500000000255611361341573025720 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNMTOKEN; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.impl.common.ValidationContext; import org.apache.xmlbeans.impl.common.XMLChar; public class XmlNmTokenImpl extends JavaStringHolderEx implements XmlNMTOKEN { public XmlNmTokenImpl() { super(XmlNMTOKEN.type, false); } public XmlNmTokenImpl(SchemaType type, boolean complex) { super(type, complex); } public static void validateLexical(String v, ValidationContext context) { if ( !XMLChar.isValidNmtoken(v) ) { context.invalid(XmlErrorCodes.NMTOKEN, new Object[] { v }); return; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNonPositiveIntegerImpl.java0000644000175000017500000000205211361341573030127 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNonPositiveInteger; public class XmlNonPositiveIntegerImpl extends JavaIntegerHolderEx implements XmlNonPositiveInteger { public XmlNonPositiveIntegerImpl() { super(XmlNonPositiveInteger.type, false); } public XmlNonPositiveIntegerImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolderEx.java0000644000175000017500000001166211361341573026276 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.PrefixResolver; import org.apache.xmlbeans.impl.common.QNameHelper; import javax.xml.namespace.QName; public abstract class JavaQNameHolderEx extends JavaQNameHolder { private SchemaType _schemaType; public SchemaType schemaType() { return _schemaType; } public JavaQNameHolderEx(SchemaType type, boolean complex) { _schemaType = type; initComplexType(complex, false); } protected int get_wscanon_rule() { return schemaType().getWhiteSpaceRule(); } protected void set_text(String s) { PrefixResolver resolver = NamespaceContext.getCurrent(); if (resolver == null && has_store()) resolver = get_store(); QName v; if (_validateOnSet()) { v = validateLexical(s, _schemaType, _voorVc, resolver); if (v != null) validateValue(v, _schemaType, _voorVc); } else v = JavaQNameHolder.validateLexical(s, _voorVc, resolver); super.set_QName(v); } protected void set_QName(QName name) { if (_validateOnSet()) validateValue(name, _schemaType, _voorVc); super.set_QName( name ); } protected void set_xmlanysimple(XmlAnySimpleType value) { QName v; if (_validateOnSet()) { v = validateLexical(value.getStringValue(), _schemaType, _voorVc, NamespaceContext.getCurrent()); if (v != null) validateValue(v, _schemaType, _voorVc); } else v = JavaQNameHolder.validateLexical(value.getStringValue(), _voorVc, NamespaceContext.getCurrent()); super.set_QName(v); } public static QName validateLexical(String v, SchemaType sType, ValidationContext context, PrefixResolver resolver) { QName name = JavaQNameHolder.validateLexical(v, context, resolver); // 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[] { "QName", v, QNameHelper.readable(sType) }); } } /* length, minLength and maxLength facets deprecated - see http://www.w3.org/TR/xmlschema-2/#QName XmlObject x; int i; if ((x = sType.getFacet(SchemaType.FACET_LENGTH)) != null) if ((i = ((XmlObjectBase)x).bigIntegerValue().intValue()) != v.length()) context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$STRING, new Object[] { "QName", v, new Integer(i), QNameHelper.readable(sType) }); if ((x = sType.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) if ((i = ((XmlObjectBase)x).bigIntegerValue().intValue()) > v.length()) context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING, new Object[] { "QName", v, new Integer(i), QNameHelper.readable(sType) }); if ((x = sType.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) if ((i = ((XmlObjectBase)x).bigIntegerValue().intValue()) < v.length()) context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING, new Object[] { "QName", v, new Integer(i), QNameHelper.readable(sType) }); */ return name; } public static void validateValue(QName v, SchemaType sType, ValidationContext context) { XmlObject[] vals = sType.getEnumerationValues(); if (vals != null) { for (int i = 0; i < vals.length; i++) if (v.equals(((XmlObjectBase)vals[i]).getQNameValue())) return; context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, new Object[] { "QName", v, QNameHelper.readable(sType) }); } } protected void validate_simpleval(String lexical, ValidationContext ctx) { validateValue(getQNameValue(), schemaType(), ctx); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBase64BinaryImpl.java0000644000175000017500000000151711361341573026532 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class XmlBase64BinaryImpl extends JavaBase64Holder implements XmlBase64Binary { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNCNameImpl.java0000644000175000017500000000254511361341573025444 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlErrorCodes; import org.apache.xmlbeans.XmlNCName; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.impl.common.ValidationContext; import org.apache.xmlbeans.impl.common.XMLChar; public class XmlNCNameImpl extends JavaStringHolderEx implements XmlNCName { public XmlNCNameImpl() { super(XmlNCName.type, false); } public XmlNCNameImpl(SchemaType type, boolean complex) { super(type, complex); } public static void validateLexical(String v, ValidationContext context) { if ( !XMLChar.isValidNCName(v) ) { context.invalid(XmlErrorCodes.NCNAME, new Object[] { v }); return; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNegativeIntegerImpl.java0000644000175000017500000000203011361341573027410 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlNegativeInteger; public class XmlNegativeIntegerImpl extends JavaIntegerHolderEx implements XmlNegativeInteger { public XmlNegativeIntegerImpl() { super(XmlNegativeInteger.type, false); } public XmlNegativeIntegerImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdImpl.java0000644000175000017500000000171111361341573024671 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlID; public class XmlIdImpl extends JavaStringHolderEx implements XmlID { public XmlIdImpl() { super(XmlID.type, false); } public XmlIdImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGMonthDayImpl.java0000644000175000017500000000176111361341573026174 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlGMonthDay; public class XmlGMonthDayImpl extends JavaGDateHolderEx implements XmlGMonthDay { public XmlGMonthDayImpl() { super(XmlGMonthDay.type, false); } public XmlGMonthDayImpl(SchemaType type, boolean complex) { super(type, complex); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDoubleImpl.java0000644000175000017500000000142511361341573025551 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlDouble; public class XmlDoubleImpl extends JavaDoubleHolder implements XmlDouble { } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/0000755000175000017500000000000013041512717021777 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/message_fr.properties0000644000175000017500000000376211361341574026244 0ustar apoapo parser.parse.1=Caract\u00e8re invalide. parser.parse.2=Num\u00e9ro de r\u00e9f\u00e9rence invalide. parser.next.1=Un \\ doit \u00eatre suivi d'un caract\u00e8re. parser.next.2='?' n'est pas possible ici. '(?:' ou '(?=' ou '(?!' ou '(?<' ou '(?#' ou '(?>'? parser.next.3='(?<=' ou '(?'? parser.next.3='(?<=' or '(? *

How to use

* *
*
A. Standard way *
*
 * RegularExpression re = new RegularExpression(regex);
 * if (re.matches(text)) { ... }
 * 
* *
B. Capturing groups *
*
 * RegularExpression re = new RegularExpression(regex);
 * Match match = new Match();
 * if (re.matches(text, match)) {
 *     ... // You can refer captured texts with methods of the Match class.
 * }
 * 
* *
* *

Case-insensitive matching

*
 * RegularExpression re = new RegularExpression(regex, "i");
 * if (re.matches(text) >= 0) { ...}
 * 
* *

Options

*

You can specify options to RegularExpression(regex, options) * or setPattern(regex, options). * This options parameter consists of the following characters. *

*
*
"i" *
This option indicates case-insensitive matching. *
"m" *
^ and $ consider the EOL characters within the text. *
"s" *
. matches any one character. *
"u" *
Redefines \d \D \w \W \s \S \b \B \< \> as becoming to Unicode. *
"w" *
By this option, \b \B \< \> are processed with the method of * 'Unicode Regular Expression Guidelines' Revision 4. * When "w" and "u" are specified at the same time, * \b \B \< \> are processed for the "w" option. *
"," *
The parser treats a comma in a character class as a range separator. * [a,b] matches a or , or b without this option. * [a,b] matches a or b with this option. * *
"X" *
* By this option, the engine confoms to XML Schema: Regular Expression. * The match() method does not do subsring matching * but entire string matching. * *
* *
*

Syntax

* * * * *
*

Differences from the Perl 5 regular expression

*
    *
  • There is 6-digit hexadecimal character representation (\u005cvHHHHHH.) *
  • Supports subtraction, union, and intersection operations for character classes. *
  • Not supported: \ooo (Octal character representations), * \G, \C, \lc, * \u005c uc, \L, \U, * \E, \Q, \N{name}, * (?{code}), (??{code}) *
*
* *

Meta characters are `. * + ? { [ ( ) | \ ^ $'.

*
    *
  • Character *
    *
    . (A period) *
    Matches any one character except the following characters. *
    LINE FEED (U+000A), CARRIAGE RETURN (U+000D), * PARAGRAPH SEPARATOR (U+2029), LINE SEPARATOR (U+2028) *
    This expression matches one code point in Unicode. It can match a pair of surrogates. *
    When the "s" option is specified, * it matches any character including the above four characters. * *
    \e \f \n \r \t *
    Matches ESCAPE (U+001B), FORM FEED (U+000C), LINE FEED (U+000A), * CARRIAGE RETURN (U+000D), HORIZONTAL TABULATION (U+0009) * *
    \cC *
    Matches a control character. * The C must be one of '@', 'A'-'Z', * '[', '\u005c', ']', '^', '_'. * It matches a control character of which the character code is less than * the character code of the C by 0x0040. *
    For example, a \cJ matches a LINE FEED (U+000A), * and a \c[ matches an ESCAPE (U+001B). * *
    a non-meta character *
    Matches the character. * *
    \ + a meta character *
    Matches the meta character. * *
    \u005cxHH \u005cx{HHHH} *
    Matches a character of which code point is HH (Hexadecimal) in Unicode. * You can write just 2 digits for \u005cxHH, and * variable length digits for \u005cx{HHHH}. * * * *
    \u005cvHHHHHH *
    Matches a character of which code point is HHHHHH (Hexadecimal) in Unicode. * *
    \g *
    Matches a grapheme. *
    It is equivalent to (?[\p{ASSIGNED}]-[\p{M}\p{C}])?(?:\p{M}|[\x{094D}\x{09CD}\x{0A4D}\x{0ACD}\x{0B3D}\x{0BCD}\x{0C4D}\x{0CCD}\x{0D4D}\x{0E3A}\x{0F84}]\p{L}|[\x{1160}-\x{11A7}]|[\x{11A8}-\x{11FF}]|[\x{FF9E}\x{FF9F}])* * *
    \X *
    Matches a combining character sequence. * It is equivalent to (?:\PM\pM*) *
    *
  • * *
  • Character class *
    + *
    [R1R2...Rn] (without "," option) + *
    [R1,R2,...,Rn] (with "," option) *
    Positive character class. It matches a character in ranges. *
    Rn: *
      *
    • A character (including \e \f \n \r \t \u005cxHH \u005cx{HHHH} \u005cvHHHHHH) *

      This range matches the character. *

    • C1-C2 *

      This range matches a character which has a code point that is >= C1's code point and <= C2's code point. + *

    • A POSIX character class: [:alpha:] [:alnum:] [:ascii:] [:cntrl:] [:digit:] [:graph:] [:lower:] [:print:] [:punct:] [:space:] [:upper:] [:xdigit:], + * and negative POSIX character classes in Perl like [:^alpha:] *

      ... *

    • \d \D \s \S \w \W \p{name} \P{name} *

      These expressions specifies the same ranges as the following expressions. *

    *

    Enumerated ranges are merged (union operation). * [a-ec-z] is equivalent to [a-z] * *

    [^R1R2...Rn] (without a "," option) *
    [^R1,R2,...,Rn] (with a "," option) *
    Negative character class. It matches a character not in ranges. * *
    (?[ranges]op[ranges]op[ranges] ... ) * (op is - or + or &.) *
    Subtraction or union or intersection for character classes. *
    For exmaple, (?[A-Z]-[CF]) is equivalent to [A-BD-EG-Z], and (?[0x00-0x7f]-[K]&[\p{Lu}]) is equivalent to [A-JL-Z]. *
    The result of this operations is a positive character class * even if an expression includes any negative character classes. * You have to take care on this in case-insensitive matching. * For instance, (?[^b]) is equivalent to [\x00-ac-\x{10ffff}], * which is equivalent to [^b] in case-sensitive matching. * But, in case-insensitive matching, (?[^b]) matches any character because * it includes 'B' and 'B' matches 'b' * though [^b] is processed as [^Bb]. * *
    [R1R2...-[RnRn+1...]] (with an "X" option)
    *
    Character class subtraction for the XML Schema. * You can use this syntax when you specify an "X" option. * *
    \d *
    Equivalent to [0-9]. *
    When a "u" option is set, it is equivalent to * \p{Nd}. * *
    \D *
    Equivalent to [^0-9] *
    When a "u" option is set, it is equivalent to * \P{Nd}. * *
    \s *
    Equivalent to [ \f\n\r\t] *
    When a "u" option is set, it is equivalent to * [ \f\n\r\t\p{Z}]. * *
    \S *
    Equivalent to [^ \f\n\r\t] *
    When a "u" option is set, it is equivalent to * [^ \f\n\r\t\p{Z}]. * *
    \w *
    Equivalent to [a-zA-Z0-9_] *
    When a "u" option is set, it is equivalent to * [\p{Lu}\p{Ll}\p{Lo}\p{Nd}_]. * *
    \W *
    Equivalent to [^a-zA-Z0-9_] *
    When a "u" option is set, it is equivalent to * [^\p{Lu}\p{Ll}\p{Lo}\p{Nd}_]. * *
    \p{name} *
    Matches one character in the specified General Category (the second field in UnicodeData.txt) or the specified Block. * The following names are available: *
    *
    Unicode General Categories: *
    * L, M, N, Z, C, P, S, Lu, Ll, Lt, Lm, Lo, Mn, Me, Mc, Nd, Nl, No, Zs, Zl, Zp, * Cc, Cf, Cn, Co, Cs, Pd, Ps, Pe, Pc, Po, Sm, Sc, Sk, So, * *
    (Currently the Cn category includes U+10000-U+10FFFF characters) *
    Unicode Blocks: *
    * Basic Latin, Latin-1 Supplement, Latin Extended-A, Latin Extended-B, * IPA Extensions, Spacing Modifier Letters, Combining Diacritical Marks, Greek, * Cyrillic, Armenian, Hebrew, Arabic, Devanagari, Bengali, Gurmukhi, Gujarati, * Oriya, Tamil, Telugu, Kannada, Malayalam, Thai, Lao, Tibetan, Georgian, * Hangul Jamo, Latin Extended Additional, Greek Extended, General Punctuation, * Superscripts and Subscripts, Currency Symbols, Combining Marks for Symbols, * Letterlike Symbols, Number Forms, Arrows, Mathematical Operators, * Miscellaneous Technical, Control Pictures, Optical Character Recognition, * Enclosed Alphanumerics, Box Drawing, Block Elements, Geometric Shapes, * Miscellaneous Symbols, Dingbats, CJK Symbols and Punctuation, Hiragana, * Katakana, Bopomofo, Hangul Compatibility Jamo, Kanbun, * Enclosed CJK Letters and Months, CJK Compatibility, CJK Unified Ideographs, * Hangul Syllables, High Surrogates, High Private Use Surrogates, Low Surrogates, * Private Use, CJK Compatibility Ideographs, Alphabetic Presentation Forms, * Arabic Presentation Forms-A, Combining Half Marks, CJK Compatibility Forms, * Small Form Variants, Arabic Presentation Forms-B, Specials, * Halfwidth and Fullwidth Forms * *
    Others: *
    ALL (Equivalent to [\u005cu0000-\u005cv10FFFF]) *
    ASSGINED (\p{ASSIGNED} is equivalent to \P{Cn}) *
    UNASSGINED * (\p{UNASSIGNED} is equivalent to \p{Cn}) *
    * *
    \P{name} *
    Matches one character not in the specified General Category or the specified Block. *
    *
  • * *
  • Selection and Quantifier *
    *
    X|Y *
    ... * *
    X* *
    Matches 0 or more X. * *
    X+ *
    Matches 1 or more X. * *
    X? *
    Matches 0 or 1 X. * *
    X{number} *
    Matches number times. * *
    X{min,} *
    ... * *
    X{min,max} *
    ... * *
    X*? *
    X+? *
    X?? *
    X{min,}? *
    X{min,max}? *
    Non-greedy matching. *
    *
  • * *
  • Grouping, Capturing, and Back-reference *
    *
    (?:X) *
    Grouping. "foo+" matches "foo" or "foooo". * If you want it matches "foofoo" or "foofoofoo", * you have to write "(?:foo)+". * *
    (X) *
    Grouping with capturing. * It make a group and applications can know * where in target text a group matched with methods of a Match instance * after matches(String,Match). * The 0th group means whole of this regular expression. * The Nth gorup is the inside of the Nth left parenthesis. * *

    For instance, a regular expression is * " *([^<:]*) +<([^>]*)> *" * and target text is * "From: TAMURA Kent <kent@trl.ibm.co.jp>": *

      *
    • Match.getCapturedText(0): * " TAMURA Kent <kent@trl.ibm.co.jp>" *
    • Match.getCapturedText(1): "TAMURA Kent" *
    • Match.getCapturedText(2): "kent@trl.ibm.co.jp" *
    * *
    \1 \2 \3 \4 \5 \6 \7 \8 \9 *
    * *
    (?>X) *
    Independent expression group. ................ * *
    (?options:X) *
    (?options-options2:X) *
    ............................ *
    The options or the options2 consists of 'i' 'm' 's' 'w'. * Note that it can not contain 'u'. * *
    (?options) *
    (?options-options2) *
    ...... *
    These expressions must be at the beginning of a group. *
    *
  • * *
  • Anchor *
    *
    \A *
    Matches the beginnig of the text. * *
    \Z *
    Matches the end of the text, or before an EOL character at the end of the text, * or CARRIAGE RETURN + LINE FEED at the end of the text. * *
    \z *
    Matches the end of the text. * *
    ^ *
    Matches the beginning of the text. It is equivalent to \A. *
    When a "m" option is set, * it matches the beginning of the text, or after one of EOL characters ( * LINE FEED (U+000A), CARRIAGE RETURN (U+000D), LINE SEPARATOR (U+2028), * PARAGRAPH SEPARATOR (U+2029).) * *
    $ *
    Matches the end of the text, or before an EOL character at the end of the text, * or CARRIAGE RETURN + LINE FEED at the end of the text. *
    When a "m" option is set, * it matches the end of the text, or before an EOL character. * *
    \b *
    Matches word boundary. * (See a "w" option) * *
    \B *
    Matches non word boundary. * (See a "w" option) * *
    \< *
    Matches the beginning of a word. * (See a "w" option) * *
    \> *
    Matches the end of a word. * (See a "w" option) *
    *
  • *
  • Lookahead and lookbehind *
    *
    (?=X) *
    Lookahead. * *
    (?!X) *
    Negative lookahead. * *
    (?<=X) *
    Lookbehind. *
    (Note for text capturing......) * *
    (?<!X) *
    Negative lookbehind. *
    *
  • * *
  • Misc. *
    *
    (?(condition)yes-pattern|no-pattern), *
    (?(condition)yes-pattern) *
    ...... *
    (?#comment) *
    Comment. A comment string consists of characters except ')'. * You can not write comments in character classes and before quantifiers. *
    *
  • *
* * *
*

BNF for the regular expression

*
 * regex ::= ('(?' options ')')? term ('|' term)*
 * term ::= factor+
 * factor ::= anchors | atom (('*' | '+' | '?' | minmax ) '?'? )?
 *            | '(?#' [^)]* ')'
 * minmax ::= '{' ([0-9]+ | [0-9]+ ',' | ',' [0-9]+ | [0-9]+ ',' [0-9]+) '}'
 * atom ::= char | '.' | char-class | '(' regex ')' | '(?:' regex ')' | '\' [0-9]
 *          | '\w' | '\W' | '\d' | '\D' | '\s' | '\S' | category-block | '\X'
 *          | '(?>' regex ')' | '(?' options ':' regex ')'
 *          | '(?' ('(' [0-9] ')' | '(' anchors ')' | looks) term ('|' term)? ')'
 * options ::= [imsw]* ('-' [imsw]+)?
 * anchors ::= '^' | '$' | '\A' | '\Z' | '\z' | '\b' | '\B' | '\<' | '\>'
 * looks ::= '(?=' regex ')'  | '(?!' regex ')'
 *           | '(?<=' regex ')' | '(?<!' regex ')'
 * char ::= '\\' | '\' [efnrtv] | '\c' [@-_] | code-point | character-1
 * category-block ::= '\' [pP] category-symbol-1
 *                    | ('\p{' | '\P{') (category-symbol | block-name
 *                                       | other-properties) '}'
 * category-symbol-1 ::= 'L' | 'M' | 'N' | 'Z' | 'C' | 'P' | 'S'
 * category-symbol ::= category-symbol-1 | 'Lu' | 'Ll' | 'Lt' | 'Lm' | Lo'
 *                     | 'Mn' | 'Me' | 'Mc' | 'Nd' | 'Nl' | 'No'
 *                     | 'Zs' | 'Zl' | 'Zp' | 'Cc' | 'Cf' | 'Cn' | 'Co' | 'Cs'
 *                     | 'Pd' | 'Ps' | 'Pe' | 'Pc' | 'Po'
 *                     | 'Sm' | 'Sc' | 'Sk' | 'So'
 * block-name ::= (See above)
 * other-properties ::= 'ALL' | 'ASSIGNED' | 'UNASSIGNED'
 * character-1 ::= (any character except meta-characters)
 *
 * char-class ::= '[' ranges ']'
 *                | '(?[' ranges ']' ([-+&] '[' ranges ']')? ')'
 * ranges ::= '^'? (range ','?)+
 * range ::= '\d' | '\w' | '\s' | '\D' | '\W' | '\S' | category-block
 *           | range-char | range-char '-' range-char
 * range-char ::= '\[' | '\]' | '\\' | '\' [,-efnrtv] | code-point | character-2
 * code-point ::= '\x' hex-char hex-char
 *                | '\x{' hex-char+ '}'
 *                | '\v' hex-char hex-char hex-char hex-char hex-char hex-char
 * hex-char ::= [0-9a-fA-F]
 * character-2 ::= (any character except \[]-,)
 * 
* *
*

TODO

* * *
* * @author TAMURA Kent <kent@trl.ibm.co.jp> * @version $Id: RegularExpression.java 111285 2004-12-08 16:54:26Z cezar $ */ public class RegularExpression implements java.io.Serializable { static final boolean DEBUG = false; /** * Compiles a token tree into an operation flow. */ private synchronized void compile(Token tok) { if (this.operations != null) return; this.numberOfClosures = 0; this.operations = this.compile(tok, null, false); } /** * Converts a token to an operation. */ private Op compile(Token tok, Op next, boolean reverse) { Op ret; switch (tok.type) { case Token.DOT: ret = Op.createDot(); ret.next = next; break; case Token.CHAR: ret = Op.createChar(tok.getChar()); ret.next = next; break; case Token.ANCHOR: ret = Op.createAnchor(tok.getChar()); ret.next = next; break; case Token.RANGE: case Token.NRANGE: ret = Op.createRange(tok); ret.next = next; break; case Token.CONCAT: ret = next; if (!reverse) { for (int i = tok.size()-1; i >= 0; i --) { ret = compile(tok.getChild(i), ret, false); } } else { for (int i = 0; i < tok.size(); i ++) { ret = compile(tok.getChild(i), ret, true); } } break; case Token.UNION: Op.UnionOp uni = Op.createUnion(tok.size()); for (int i = 0; i < tok.size(); i ++) { uni.addElement(compile(tok.getChild(i), next, reverse)); } ret = uni; // ret.next is null. break; case Token.CLOSURE: case Token.NONGREEDYCLOSURE: Token child = tok.getChild(0); int min = tok.getMin(); int max = tok.getMax(); if (min >= 0 && min == max) { // {n} ret = next; for (int i = 0; i < min; i ++) { ret = compile(child, ret, reverse); } break; } if (min > 0 && max > 0) max -= min; if (max > 0) { // X{2,6} -> XX(X(X(XX?)?)?)? ret = next; for (int i = 0; i < max; i ++) { Op.ChildOp q = Op.createQuestion(tok.type == Token.NONGREEDYCLOSURE); q.next = next; q.setChild(compile(child, ret, reverse)); ret = q; } } else { Op.ChildOp op; if (tok.type == Token.NONGREEDYCLOSURE) { op = Op.createNonGreedyClosure(); } else { // Token.CLOSURE if (child.getMinLength() == 0) op = Op.createClosure(this.numberOfClosures++); else op = Op.createClosure(-1); } op.next = next; op.setChild(compile(child, op, reverse)); ret = op; } if (min > 0) { for (int i = 0; i < min; i ++) { ret = compile(child, ret, reverse); } } break; case Token.EMPTY: ret = next; break; case Token.STRING: ret = Op.createString(tok.getString()); ret.next = next; break; case Token.BACKREFERENCE: ret = Op.createBackReference(tok.getReferenceNumber()); ret.next = next; break; case Token.PAREN: if (tok.getParenNumber() == 0) { ret = compile(tok.getChild(0), next, reverse); } else if (reverse) { next = Op.createCapture(tok.getParenNumber(), next); next = compile(tok.getChild(0), next, reverse); ret = Op.createCapture(-tok.getParenNumber(), next); } else { next = Op.createCapture(-tok.getParenNumber(), next); next = compile(tok.getChild(0), next, reverse); ret = Op.createCapture(tok.getParenNumber(), next); } break; case Token.LOOKAHEAD: ret = Op.createLook(Op.LOOKAHEAD, next, compile(tok.getChild(0), null, false)); break; case Token.NEGATIVELOOKAHEAD: ret = Op.createLook(Op.NEGATIVELOOKAHEAD, next, compile(tok.getChild(0), null, false)); break; case Token.LOOKBEHIND: ret = Op.createLook(Op.LOOKBEHIND, next, compile(tok.getChild(0), null, true)); break; case Token.NEGATIVELOOKBEHIND: ret = Op.createLook(Op.NEGATIVELOOKBEHIND, next, compile(tok.getChild(0), null, true)); break; case Token.INDEPENDENT: ret = Op.createIndependent(next, compile(tok.getChild(0), null, reverse)); break; case Token.MODIFIERGROUP: ret = Op.createModifier(next, compile(tok.getChild(0), null, reverse), ((Token.ModifierToken)tok).getOptions(), ((Token.ModifierToken)tok).getOptionsMask()); break; case Token.CONDITION: Token.ConditionToken ctok = (Token.ConditionToken)tok; int ref = ctok.refNumber; Op condition = ctok.condition == null ? null : compile(ctok.condition, null, reverse); Op yes = compile(ctok.yes, next, reverse); Op no = ctok.no == null ? null : compile(ctok.no, next, reverse); ret = Op.createCondition(next, ref, condition, yes, no); break; default: throw new RuntimeException("Unknown token type: "+tok.type); } // switch (tok.type) return ret; } //Public /** * Checks whether the target text contains this pattern or not. * * @return true if the target is matched to this regular expression. */ public boolean matches(char[] target) { return this.matches(target, 0, target .length , (Match)null); } /** * Checks whether the target text contains this pattern * in specified range or not. * * @param start Start offset of the range. * @param end End offset +1 of the range. * @return true if the target is matched to this regular expression. */ public boolean matches(char[] target, int start, int end) { return this.matches(target, start, end, (Match)null); } /** * Checks whether the target text contains this pattern or not. * * @param match A Match instance for storing matching result. * @return Offset of the start position in target; or -1 if not match. */ public boolean matches(char[] target, Match match) { return this.matches(target, 0, target .length , match); } /** * Checks whether the target text contains this pattern * in specified range or not. * * @param start Start offset of the range. * @param end End offset +1 of the range. * @param match A Match instance for storing matching result. * @return Offset of the start position in target; or -1 if not match. */ public boolean matches(char[] target, int start, int end, Match match) { synchronized (this) { if (this.operations == null) this.prepare(); if (this.context == null) this.context = new Context(); } Context con = null; synchronized (this.context) { con = this.context.inuse ? new Context() : this.context; con.reset(target, start, end, this.numberOfClosures); } if (match != null) { match.setNumberOfGroups(this.nofparen); match.setSource(target); } else if (this.hasBackReferences) { match = new Match(); match.setNumberOfGroups(this.nofparen); // Need not to call setSource() because // a caller can not access this match instance. } con.match = match; if (RegularExpression.isSet(this.options, XMLSCHEMA_MODE)) { int matchEnd = this. matchCharArray (con, this.operations, con.start, 1, this.options); //System.err.println("DEBUG: matchEnd="+matchEnd); if (matchEnd == con.limit) { if (con.match != null) { con.match.setBeginning(0, con.start); con.match.setEnd(0, matchEnd); } con.inuse = false; return true; } return false; } /* * The pattern has only fixed string. * The engine uses Boyer-Moore. */ if (this.fixedStringOnly) { //System.err.println("DEBUG: fixed-only: "+this.fixedString); int o = this.fixedStringTable.matches(target, con.start, con.limit); if (o >= 0) { if (con.match != null) { con.match.setBeginning(0, o); con.match.setEnd(0, o+this.fixedString.length()); } con.inuse = false; return true; } con.inuse = false; return false; } /* * The pattern contains a fixed string. * The engine checks with Boyer-Moore whether the text contains the fixed string or not. * If not, it return with false. */ if (this.fixedString != null) { int o = this.fixedStringTable.matches(target, con.start, con.limit); if (o < 0) { //System.err.println("Non-match in fixed-string search."); con.inuse = false; return false; } } int limit = con.limit-this.minlength; int matchStart; int matchEnd = -1; /* * Checks whether the expression starts with ".*". */ if (this.operations != null && this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) { if (isSet(this.options, SINGLE_LINE)) { matchStart = con.start; matchEnd = this. matchCharArray (con, this.operations, con.start, 1, this.options); } else { boolean previousIsEOL = true; for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target [ matchStart ] ; if (isEOLChar(ch)) { previousIsEOL = true; } else { if (previousIsEOL) { if (0 <= (matchEnd = this. matchCharArray (con, this.operations, matchStart, 1, this.options))) break; } previousIsEOL = false; } } } } /* * Optimization against the first character. */ else if (this.firstChar != null) { //System.err.println("DEBUG: with firstchar-matching: "+this.firstChar); RangeToken range = this.firstChar; if (RegularExpression.isSet(this.options, IGNORE_CASE)) { range = this.firstChar.getCaseInsensitiveToken(); for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target [ matchStart ] ; if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) { ch = REUtil.composeFromSurrogates(ch, target [ matchStart+1 ] ); if (!range.match(ch)) continue; } else { if (!range.match(ch)) { char ch1 = Character.toUpperCase((char)ch); if (!range.match(ch1)) if (!range.match(Character.toLowerCase(ch1))) continue; } } if (0 <= (matchEnd = this. matchCharArray (con, this.operations, matchStart, 1, this.options))) break; } } else { for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target [ matchStart ] ; if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target [ matchStart+1 ] ); if (!range.match(ch)) continue; if (0 <= (matchEnd = this. matchCharArray (con, this.operations, matchStart, 1, this.options))) break; } } } /* * Straightforward matching. */ else { for (matchStart = con.start; matchStart <= limit; matchStart ++) { if (0 <= (matchEnd = this. matchCharArray (con, this.operations, matchStart, 1, this.options))) break; } } if (matchEnd >= 0) { if (con.match != null) { con.match.setBeginning(0, matchStart); con.match.setEnd(0, matchEnd); } con.inuse = false; return true; } else { con.inuse = false; return false; } } /** * @return -1 when not match; offset of the end of matched string when match. */ private int matchCharArray (Context con, Op op, int offset, int dx, int opts) { char[] target = con.charTarget; while (true) { if (op == null) return isSet(opts, XMLSCHEMA_MODE) && offset != con.limit ? -1 : offset; if (offset > con.limit || offset < con.start) return -1; switch (op.type) { case Op.CHAR: if (isSet(opts, IGNORE_CASE)) { int ch = op.getData(); if (dx > 0) { if (offset >= con.limit || !matchIgnoreCase(ch, target [ offset ] )) return -1; offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0 || !matchIgnoreCase(ch, target [ o1 ] )) return -1; offset = o1; } } else { int ch = op.getData(); if (dx > 0) { if (offset >= con.limit || ch != target [ offset ] ) return -1; offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0 || ch != target [ o1 ] ) return -1; offset = o1; } } op = op.next; break; case Op.DOT: if (dx > 0) { if (offset >= con.limit) return -1; int ch = target [ offset ] ; if (isSet(opts, SINGLE_LINE)) { if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) offset ++; } else { if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target [ ++offset ] ); if (isEOLChar(ch)) return -1; } offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0) return -1; int ch = target [ o1 ] ; if (isSet(opts, SINGLE_LINE)) { if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) o1 --; } else { if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) ch = REUtil.composeFromSurrogates( target [ --o1 ] , ch); if (!isEOLChar(ch)) return -1; } offset = o1; } op = op.next; break; case Op.RANGE: case Op.NRANGE: if (dx > 0) { if (offset >= con.limit) return -1; int ch = target [ offset ] ; if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target [ ++offset ] ); RangeToken tok = op.getToken(); if (isSet(opts, IGNORE_CASE)) { tok = tok.getCaseInsensitiveToken(); if (!tok.match(ch)) { if (ch >= 0x10000) return -1; char uch; if (!tok.match(uch = Character.toUpperCase((char)ch)) && !tok.match(Character.toLowerCase(uch))) return -1; } } else { if (!tok.match(ch)) return -1; } offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0) return -1; int ch = target [ o1 ] ; if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) ch = REUtil.composeFromSurrogates( target [ --o1 ] , ch); RangeToken tok = op.getToken(); if (isSet(opts, IGNORE_CASE)) { tok = tok.getCaseInsensitiveToken(); if (!tok.match(ch)) { if (ch >= 0x10000) return -1; char uch; if (!tok.match(uch = Character.toUpperCase((char)ch)) && !tok.match(Character.toLowerCase(uch))) return -1; } } else { if (!tok.match(ch)) return -1; } offset = o1; } op = op.next; break; case Op.ANCHOR: boolean go = false; switch (op.getData()) { case '^': if (isSet(opts, MULTIPLE_LINES)) { if (!(offset == con.start || offset > con.start && isEOLChar( target [ offset-1 ] ))) return -1; } else { if (offset != con.start) return -1; } break; case '@': // Internal use only. // The @ always matches line beginnings. if (!(offset == con.start || offset > con.start && isEOLChar( target [ offset-1 ] ))) return -1; break; case '$': if (isSet(opts, MULTIPLE_LINES)) { if (!(offset == con.limit || offset < con.limit && isEOLChar( target [ offset ] ))) return -1; } else { if (!(offset == con.limit || offset+1 == con.limit && isEOLChar( target [ offset ] ) || offset+2 == con.limit && target [ offset ] == CARRIAGE_RETURN && target [ offset+1 ] == LINE_FEED)) return -1; } break; case 'A': if (offset != con.start) return -1; break; case 'Z': if (!(offset == con.limit || offset+1 == con.limit && isEOLChar( target [ offset ] ) || offset+2 == con.limit && target [ offset ] == CARRIAGE_RETURN && target [ offset+1 ] == LINE_FEED)) return -1; break; case 'z': if (offset != con.limit) return -1; break; case 'b': if (con.length == 0) return -1; { int after = getWordType(target, con.start, con.limit, offset, opts); if (after == WT_IGNORE) return -1; int before = getPreviousWordType(target, con.start, con.limit, offset, opts); if (after == before) return -1; } break; case 'B': if (con.length == 0) go = true; else { int after = getWordType(target, con.start, con.limit, offset, opts); go = after == WT_IGNORE || after == getPreviousWordType(target, con.start, con.limit, offset, opts); } if (!go) return -1; break; case '<': if (con.length == 0 || offset == con.limit) return -1; if (getWordType(target, con.start, con.limit, offset, opts) != WT_LETTER || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_OTHER) return -1; break; case '>': if (con.length == 0 || offset == con.start) return -1; if (getWordType(target, con.start, con.limit, offset, opts) != WT_OTHER || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_LETTER) return -1; break; } // switch anchor type op = op.next; break; case Op.BACKREFERENCE: { int refno = op.getData(); if (refno <= 0 || refno >= this.nofparen) throw new RuntimeException("Internal Error: Reference number must be more than zero: "+refno); if (con.match.getBeginning(refno) < 0 || con.match.getEnd(refno) < 0) return -1; // ******** int o2 = con.match.getBeginning(refno); int literallen = con.match.getEnd(refno)-o2; if (!isSet(opts, IGNORE_CASE)) { if (dx > 0) { if (!regionMatches(target, offset, con.limit, o2, literallen)) return -1; offset += literallen; } else { if (!regionMatches(target, offset-literallen, con.limit, o2, literallen)) return -1; offset -= literallen; } } else { if (dx > 0) { if (!regionMatchesIgnoreCase(target, offset, con.limit, o2, literallen)) return -1; offset += literallen; } else { if (!regionMatchesIgnoreCase(target, offset-literallen, con.limit, o2, literallen)) return -1; offset -= literallen; } } } op = op.next; break; case Op.STRING: { String literal = op.getString(); int literallen = literal.length(); if (!isSet(opts, IGNORE_CASE)) { if (dx > 0) { if (!regionMatches(target, offset, con.limit, literal, literallen)) return -1; offset += literallen; } else { if (!regionMatches(target, offset-literallen, con.limit, literal, literallen)) return -1; offset -= literallen; } } else { if (dx > 0) { if (!regionMatchesIgnoreCase(target, offset, con.limit, literal, literallen)) return -1; offset += literallen; } else { if (!regionMatchesIgnoreCase(target, offset-literallen, con.limit, literal, literallen)) return -1; offset -= literallen; } } } op = op.next; break; case Op.CLOSURE: { /* * Saves current position to avoid * zero-width repeats. */ int id = op.getData(); if (id >= 0) { int previousOffset = con.offsets[id]; if (previousOffset < 0 || previousOffset != offset) { con.offsets[id] = offset; } else { con.offsets[id] = -1; op = op.next; break; } } int ret = this. matchCharArray (con, op.getChild(), offset, dx, opts); if (id >= 0) con.offsets[id] = -1; if (ret >= 0) return ret; op = op.next; } break; case Op.QUESTION: { int ret = this. matchCharArray (con, op.getChild(), offset, dx, opts); if (ret >= 0) return ret; op = op.next; } break; case Op.NONGREEDYCLOSURE: case Op.NONGREEDYQUESTION: { int ret = this. matchCharArray (con, op.next, offset, dx, opts); if (ret >= 0) return ret; op = op.getChild(); } break; case Op.UNION: for (int i = 0; i < op.size(); i ++) { int ret = this. matchCharArray (con, op.elementAt(i), offset, dx, opts); if (DEBUG) { System.err.println("UNION: "+i+", ret="+ret); } if (ret >= 0) return ret; } return -1; case Op.CAPTURE: int refno = op.getData(); if (con.match != null && refno > 0) { int save = con.match.getBeginning(refno); con.match.setBeginning(refno, offset); int ret = this. matchCharArray (con, op.next, offset, dx, opts); if (ret < 0) con.match.setBeginning(refno, save); return ret; } else if (con.match != null && refno < 0) { int index = -refno; int save = con.match.getEnd(index); con.match.setEnd(index, offset); int ret = this. matchCharArray (con, op.next, offset, dx, opts); if (ret < 0) con.match.setEnd(index, save); return ret; } op = op.next; break; case Op.LOOKAHEAD: if (0 > this. matchCharArray (con, op.getChild(), offset, 1, opts)) return -1; op = op.next; break; case Op.NEGATIVELOOKAHEAD: if (0 <= this. matchCharArray (con, op.getChild(), offset, 1, opts)) return -1; op = op.next; break; case Op.LOOKBEHIND: if (0 > this. matchCharArray (con, op.getChild(), offset, -1, opts)) return -1; op = op.next; break; case Op.NEGATIVELOOKBEHIND: if (0 <= this. matchCharArray (con, op.getChild(), offset, -1, opts)) return -1; op = op.next; break; case Op.INDEPENDENT: { int ret = this. matchCharArray (con, op.getChild(), offset, dx, opts); if (ret < 0) return ret; offset = ret; op = op.next; } break; case Op.MODIFIER: { int localopts = opts; localopts |= op.getData(); localopts &= ~op.getData2(); //System.err.println("MODIFIER: "+Integer.toString(opts, 16)+" -> "+Integer.toString(localopts, 16)); int ret = this. matchCharArray (con, op.getChild(), offset, dx, localopts); if (ret < 0) return ret; offset = ret; op = op.next; } break; case Op.CONDITION: { Op.ConditionOp cop = (Op.ConditionOp)op; boolean matchp = false; if (cop.refNumber > 0) { if (cop.refNumber >= this.nofparen) throw new RuntimeException("Internal Error: Reference number must be more than zero: "+cop.refNumber); matchp = con.match.getBeginning(cop.refNumber) >= 0 && con.match.getEnd(cop.refNumber) >= 0; } else { matchp = 0 <= this. matchCharArray (con, cop.condition, offset, dx, opts); } if (matchp) { op = cop.yes; } else if (cop.no != null) { op = cop.no; } else { op = cop.next; } } break; default: throw new RuntimeException("Unknown operation type: "+op.type); } // switch (op.type) } // while } private static final int getPreviousWordType(char[] target, int begin, int end, int offset, int opts) { int ret = getWordType(target, begin, end, --offset, opts); while (ret == WT_IGNORE) ret = getWordType(target, begin, end, --offset, opts); return ret; } private static final int getWordType(char[] target, int begin, int end, int offset, int opts) { if (offset < begin || offset >= end) return WT_OTHER; return getWordType0( target [ offset ] , opts); } private static final boolean regionMatches(char[] target, int offset, int limit, String part, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = 0; while (partlen-- > 0) { if ( target [ offset++ ] != part.charAt(i++)) return false; } return true; } private static final boolean regionMatches(char[] target, int offset, int limit, int offset2, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = offset2; while (partlen-- > 0) { if ( target [ offset++ ] != target [ i++ ] ) return false; } return true; } /** * @see java.lang.String#regionMatches */ private static final boolean regionMatchesIgnoreCase(char[] target, int offset, int limit, String part, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = 0; while (partlen-- > 0) { char ch1 = target [ offset++ ] ; char ch2 = part.charAt(i++); if (ch1 == ch2) continue; char uch1 = Character.toUpperCase(ch1); char uch2 = Character.toUpperCase(ch2); if (uch1 == uch2) continue; if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) return false; } return true; } private static final boolean regionMatchesIgnoreCase(char[] target, int offset, int limit, int offset2, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = offset2; while (partlen-- > 0) { char ch1 = target [ offset++ ] ; char ch2 = target [ i++ ] ; if (ch1 == ch2) continue; char uch1 = Character.toUpperCase(ch1); char uch2 = Character.toUpperCase(ch2); if (uch1 == uch2) continue; if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) return false; } return true; } /** * Checks whether the target text contains this pattern or not. * * @return true if the target is matched to this regular expression. */ public boolean matches(String target) { return this.matches(target, 0, target .length() , (Match)null); } /** * Checks whether the target text contains this pattern * in specified range or not. * * @param start Start offset of the range. * @param end End offset +1 of the range. * @return true if the target is matched to this regular expression. */ public boolean matches(String target, int start, int end) { return this.matches(target, start, end, (Match)null); } /** * Checks whether the target text contains this pattern or not. * * @param match A Match instance for storing matching result. * @return Offset of the start position in target; or -1 if not match. */ public boolean matches(String target, Match match) { return this.matches(target, 0, target .length() , match); } /** * Checks whether the target text contains this pattern * in specified range or not. * * @param start Start offset of the range. * @param end End offset +1 of the range. * @param match A Match instance for storing matching result. * @return Offset of the start position in target; or -1 if not match. */ public boolean matches(String target, int start, int end, Match match) { synchronized (this) { if (this.operations == null) this.prepare(); if (this.context == null) this.context = new Context(); } Context con = null; synchronized (this.context) { con = this.context.inuse ? new Context() : this.context; con.reset(target, start, end, this.numberOfClosures); } if (match != null) { match.setNumberOfGroups(this.nofparen); match.setSource(target); } else if (this.hasBackReferences) { match = new Match(); match.setNumberOfGroups(this.nofparen); // Need not to call setSource() because // a caller can not access this match instance. } con.match = match; if (RegularExpression.isSet(this.options, XMLSCHEMA_MODE)) { if (DEBUG) { System.err.println("target string="+target); } int matchEnd = this. matchString (con, this.operations, con.start, 1, this.options); if (DEBUG) { System.err.println("matchEnd="+matchEnd); System.err.println("con.limit="+con.limit); } if (matchEnd == con.limit) { if (con.match != null) { con.match.setBeginning(0, con.start); con.match.setEnd(0, matchEnd); } con.inuse = false; return true; } return false; } /* * The pattern has only fixed string. * The engine uses Boyer-Moore. */ if (this.fixedStringOnly) { //System.err.println("DEBUG: fixed-only: "+this.fixedString); int o = this.fixedStringTable.matches(target, con.start, con.limit); if (o >= 0) { if (con.match != null) { con.match.setBeginning(0, o); con.match.setEnd(0, o+this.fixedString.length()); } con.inuse = false; return true; } con.inuse = false; return false; } /* * The pattern contains a fixed string. * The engine checks with Boyer-Moore whether the text contains the fixed string or not. * If not, it return with false. */ if (this.fixedString != null) { int o = this.fixedStringTable.matches(target, con.start, con.limit); if (o < 0) { //System.err.println("Non-match in fixed-string search."); con.inuse = false; return false; } } int limit = con.limit-this.minlength; int matchStart; int matchEnd = -1; /* * Checks whether the expression starts with ".*". */ if (this.operations != null && this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) { if (isSet(this.options, SINGLE_LINE)) { matchStart = con.start; matchEnd = this. matchString (con, this.operations, con.start, 1, this.options); } else { boolean previousIsEOL = true; for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target .charAt( matchStart ) ; if (isEOLChar(ch)) { previousIsEOL = true; } else { if (previousIsEOL) { if (0 <= (matchEnd = this. matchString (con, this.operations, matchStart, 1, this.options))) break; } previousIsEOL = false; } } } } /* * Optimization against the first character. */ else if (this.firstChar != null) { //System.err.println("DEBUG: with firstchar-matching: "+this.firstChar); RangeToken range = this.firstChar; if (RegularExpression.isSet(this.options, IGNORE_CASE)) { range = this.firstChar.getCaseInsensitiveToken(); for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target .charAt( matchStart ) ; if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) { ch = REUtil.composeFromSurrogates(ch, target .charAt( matchStart+1 ) ); if (!range.match(ch)) continue; } else { if (!range.match(ch)) { char ch1 = Character.toUpperCase((char)ch); if (!range.match(ch1)) if (!range.match(Character.toLowerCase(ch1))) continue; } } if (0 <= (matchEnd = this. matchString (con, this.operations, matchStart, 1, this.options))) break; } } else { for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target .charAt( matchStart ) ; if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target .charAt( matchStart+1 ) ); if (!range.match(ch)) continue; if (0 <= (matchEnd = this. matchString (con, this.operations, matchStart, 1, this.options))) break; } } } /* * Straightforward matching. */ else { for (matchStart = con.start; matchStart <= limit; matchStart ++) { if (0 <= (matchEnd = this. matchString (con, this.operations, matchStart, 1, this.options))) break; } } if (matchEnd >= 0) { if (con.match != null) { con.match.setBeginning(0, matchStart); con.match.setEnd(0, matchEnd); } con.inuse = false; return true; } else { con.inuse = false; return false; } } /** * @return -1 when not match; offset of the end of matched string when match. */ private int matchString (Context con, Op op, int offset, int dx, int opts) { String target = con.strTarget; while (true) { if (op == null) return isSet(opts, XMLSCHEMA_MODE) && offset != con.limit ? -1 : offset; if (offset > con.limit || offset < con.start) return -1; switch (op.type) { case Op.CHAR: if (isSet(opts, IGNORE_CASE)) { int ch = op.getData(); if (dx > 0) { if (offset >= con.limit || !matchIgnoreCase(ch, target .charAt( offset ) )) return -1; offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0 || !matchIgnoreCase(ch, target .charAt( o1 ) )) return -1; offset = o1; } } else { int ch = op.getData(); if (dx > 0) { if (offset >= con.limit || ch != target .charAt( offset ) ) return -1; offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0 || ch != target .charAt( o1 ) ) return -1; offset = o1; } } op = op.next; break; case Op.DOT: if (dx > 0) { if (offset >= con.limit) return -1; int ch = target .charAt( offset ) ; if (isSet(opts, SINGLE_LINE)) { if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) offset ++; } else { if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target .charAt( ++offset ) ); if (isEOLChar(ch)) return -1; } offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0) return -1; int ch = target .charAt( o1 ) ; if (isSet(opts, SINGLE_LINE)) { if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) o1 --; } else { if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) ch = REUtil.composeFromSurrogates( target .charAt( --o1 ) , ch); if (!isEOLChar(ch)) return -1; } offset = o1; } op = op.next; break; case Op.RANGE: case Op.NRANGE: if (dx > 0) { if (offset >= con.limit) return -1; int ch = target .charAt( offset ) ; if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target .charAt( ++offset ) ); RangeToken tok = op.getToken(); if (isSet(opts, IGNORE_CASE)) { tok = tok.getCaseInsensitiveToken(); if (!tok.match(ch)) { if (ch >= 0x10000) return -1; char uch; if (!tok.match(uch = Character.toUpperCase((char)ch)) && !tok.match(Character.toLowerCase(uch))) return -1; } } else { if (!tok.match(ch)) return -1; } offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0) return -1; int ch = target .charAt( o1 ) ; if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) ch = REUtil.composeFromSurrogates( target .charAt( --o1 ) , ch); RangeToken tok = op.getToken(); if (isSet(opts, IGNORE_CASE)) { tok = tok.getCaseInsensitiveToken(); if (!tok.match(ch)) { if (ch >= 0x10000) return -1; char uch; if (!tok.match(uch = Character.toUpperCase((char)ch)) && !tok.match(Character.toLowerCase(uch))) return -1; } } else { if (!tok.match(ch)) return -1; } offset = o1; } op = op.next; break; case Op.ANCHOR: boolean go = false; switch (op.getData()) { case '^': if (isSet(opts, MULTIPLE_LINES)) { if (!(offset == con.start || offset > con.start && isEOLChar( target .charAt( offset-1 ) ))) return -1; } else { if (offset != con.start) return -1; } break; case '@': // Internal use only. // The @ always matches line beginnings. if (!(offset == con.start || offset > con.start && isEOLChar( target .charAt( offset-1 ) ))) return -1; break; case '$': if (isSet(opts, MULTIPLE_LINES)) { if (!(offset == con.limit || offset < con.limit && isEOLChar( target .charAt( offset ) ))) return -1; } else { if (!(offset == con.limit || offset+1 == con.limit && isEOLChar( target .charAt( offset ) ) || offset+2 == con.limit && target .charAt( offset ) == CARRIAGE_RETURN && target .charAt( offset+1 ) == LINE_FEED)) return -1; } break; case 'A': if (offset != con.start) return -1; break; case 'Z': if (!(offset == con.limit || offset+1 == con.limit && isEOLChar( target .charAt( offset ) ) || offset+2 == con.limit && target .charAt( offset ) == CARRIAGE_RETURN && target .charAt( offset+1 ) == LINE_FEED)) return -1; break; case 'z': if (offset != con.limit) return -1; break; case 'b': if (con.length == 0) return -1; { int after = getWordType(target, con.start, con.limit, offset, opts); if (after == WT_IGNORE) return -1; int before = getPreviousWordType(target, con.start, con.limit, offset, opts); if (after == before) return -1; } break; case 'B': if (con.length == 0) go = true; else { int after = getWordType(target, con.start, con.limit, offset, opts); go = after == WT_IGNORE || after == getPreviousWordType(target, con.start, con.limit, offset, opts); } if (!go) return -1; break; case '<': if (con.length == 0 || offset == con.limit) return -1; if (getWordType(target, con.start, con.limit, offset, opts) != WT_LETTER || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_OTHER) return -1; break; case '>': if (con.length == 0 || offset == con.start) return -1; if (getWordType(target, con.start, con.limit, offset, opts) != WT_OTHER || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_LETTER) return -1; break; } // switch anchor type op = op.next; break; case Op.BACKREFERENCE: { int refno = op.getData(); if (refno <= 0 || refno >= this.nofparen) throw new RuntimeException("Internal Error: Reference number must be more than zero: "+refno); if (con.match.getBeginning(refno) < 0 || con.match.getEnd(refno) < 0) return -1; // ******** int o2 = con.match.getBeginning(refno); int literallen = con.match.getEnd(refno)-o2; if (!isSet(opts, IGNORE_CASE)) { if (dx > 0) { if (!regionMatches(target, offset, con.limit, o2, literallen)) return -1; offset += literallen; } else { if (!regionMatches(target, offset-literallen, con.limit, o2, literallen)) return -1; offset -= literallen; } } else { if (dx > 0) { if (!regionMatchesIgnoreCase(target, offset, con.limit, o2, literallen)) return -1; offset += literallen; } else { if (!regionMatchesIgnoreCase(target, offset-literallen, con.limit, o2, literallen)) return -1; offset -= literallen; } } } op = op.next; break; case Op.STRING: { String literal = op.getString(); int literallen = literal.length(); if (!isSet(opts, IGNORE_CASE)) { if (dx > 0) { if (!regionMatches(target, offset, con.limit, literal, literallen)) return -1; offset += literallen; } else { if (!regionMatches(target, offset-literallen, con.limit, literal, literallen)) return -1; offset -= literallen; } } else { if (dx > 0) { if (!regionMatchesIgnoreCase(target, offset, con.limit, literal, literallen)) return -1; offset += literallen; } else { if (!regionMatchesIgnoreCase(target, offset-literallen, con.limit, literal, literallen)) return -1; offset -= literallen; } } } op = op.next; break; case Op.CLOSURE: { /* * Saves current position to avoid * zero-width repeats. */ int id = op.getData(); if (id >= 0) { int previousOffset = con.offsets[id]; if (previousOffset < 0 || previousOffset != offset) { con.offsets[id] = offset; } else { con.offsets[id] = -1; op = op.next; break; } } int ret = this. matchString (con, op.getChild(), offset, dx, opts); if (id >= 0) con.offsets[id] = -1; if (ret >= 0) return ret; op = op.next; } break; case Op.QUESTION: { int ret = this. matchString (con, op.getChild(), offset, dx, opts); if (ret >= 0) return ret; op = op.next; } break; case Op.NONGREEDYCLOSURE: case Op.NONGREEDYQUESTION: { int ret = this. matchString (con, op.next, offset, dx, opts); if (ret >= 0) return ret; op = op.getChild(); } break; case Op.UNION: for (int i = 0; i < op.size(); i ++) { int ret = this. matchString (con, op.elementAt(i), offset, dx, opts); if (DEBUG) { System.err.println("UNION: "+i+", ret="+ret); } if (ret >= 0) return ret; } return -1; case Op.CAPTURE: int refno = op.getData(); if (con.match != null && refno > 0) { int save = con.match.getBeginning(refno); con.match.setBeginning(refno, offset); int ret = this. matchString (con, op.next, offset, dx, opts); if (ret < 0) con.match.setBeginning(refno, save); return ret; } else if (con.match != null && refno < 0) { int index = -refno; int save = con.match.getEnd(index); con.match.setEnd(index, offset); int ret = this. matchString (con, op.next, offset, dx, opts); if (ret < 0) con.match.setEnd(index, save); return ret; } op = op.next; break; case Op.LOOKAHEAD: if (0 > this. matchString (con, op.getChild(), offset, 1, opts)) return -1; op = op.next; break; case Op.NEGATIVELOOKAHEAD: if (0 <= this. matchString (con, op.getChild(), offset, 1, opts)) return -1; op = op.next; break; case Op.LOOKBEHIND: if (0 > this. matchString (con, op.getChild(), offset, -1, opts)) return -1; op = op.next; break; case Op.NEGATIVELOOKBEHIND: if (0 <= this. matchString (con, op.getChild(), offset, -1, opts)) return -1; op = op.next; break; case Op.INDEPENDENT: { int ret = this. matchString (con, op.getChild(), offset, dx, opts); if (ret < 0) return ret; offset = ret; op = op.next; } break; case Op.MODIFIER: { int localopts = opts; localopts |= op.getData(); localopts &= ~op.getData2(); //System.err.println("MODIFIER: "+Integer.toString(opts, 16)+" -> "+Integer.toString(localopts, 16)); int ret = this. matchString (con, op.getChild(), offset, dx, localopts); if (ret < 0) return ret; offset = ret; op = op.next; } break; case Op.CONDITION: { Op.ConditionOp cop = (Op.ConditionOp)op; boolean matchp = false; if (cop.refNumber > 0) { if (cop.refNumber >= this.nofparen) throw new RuntimeException("Internal Error: Reference number must be more than zero: "+cop.refNumber); matchp = con.match.getBeginning(cop.refNumber) >= 0 && con.match.getEnd(cop.refNumber) >= 0; } else { matchp = 0 <= this. matchString (con, cop.condition, offset, dx, opts); } if (matchp) { op = cop.yes; } else if (cop.no != null) { op = cop.no; } else { op = cop.next; } } break; default: throw new RuntimeException("Unknown operation type: "+op.type); } // switch (op.type) } // while } private static final int getPreviousWordType(String target, int begin, int end, int offset, int opts) { int ret = getWordType(target, begin, end, --offset, opts); while (ret == WT_IGNORE) ret = getWordType(target, begin, end, --offset, opts); return ret; } private static final int getWordType(String target, int begin, int end, int offset, int opts) { if (offset < begin || offset >= end) return WT_OTHER; return getWordType0( target .charAt( offset ) , opts); } private static final boolean regionMatches(String text, int offset, int limit, String part, int partlen) { if (limit-offset < partlen) return false; return text.regionMatches(offset, part, 0, partlen); } private static final boolean regionMatches(String text, int offset, int limit, int offset2, int partlen) { if (limit-offset < partlen) return false; return text.regionMatches(offset, text, offset2, partlen); } private static final boolean regionMatchesIgnoreCase(String text, int offset, int limit, String part, int partlen) { return text.regionMatches(true, offset, part, 0, partlen); } private static final boolean regionMatchesIgnoreCase(String text, int offset, int limit, int offset2, int partlen) { if (limit-offset < partlen) return false; return text.regionMatches(true, offset, text, offset2, partlen); } /** * Checks whether the target text contains this pattern or not. * * @return true if the target is matched to this regular expression. */ public boolean matches(CharacterIterator target) { return this.matches(target, (Match)null); } /** * Checks whether the target text contains this pattern or not. * * @param match A Match instance for storing matching result. * @return Offset of the start position in target; or -1 if not match. */ public boolean matches(CharacterIterator target, Match match) { int start = target.getBeginIndex(); int end = target.getEndIndex(); synchronized (this) { if (this.operations == null) this.prepare(); if (this.context == null) this.context = new Context(); } Context con = null; synchronized (this.context) { con = this.context.inuse ? new Context() : this.context; con.reset(target, start, end, this.numberOfClosures); } if (match != null) { match.setNumberOfGroups(this.nofparen); match.setSource(target); } else if (this.hasBackReferences) { match = new Match(); match.setNumberOfGroups(this.nofparen); // Need not to call setSource() because // a caller can not access this match instance. } con.match = match; if (RegularExpression.isSet(this.options, XMLSCHEMA_MODE)) { int matchEnd = this. matchCharacterIterator (con, this.operations, con.start, 1, this.options); //System.err.println("DEBUG: matchEnd="+matchEnd); if (matchEnd == con.limit) { if (con.match != null) { con.match.setBeginning(0, con.start); con.match.setEnd(0, matchEnd); } con.inuse = false; return true; } return false; } /* * The pattern has only fixed string. * The engine uses Boyer-Moore. */ if (this.fixedStringOnly) { //System.err.println("DEBUG: fixed-only: "+this.fixedString); int o = this.fixedStringTable.matches(target, con.start, con.limit); if (o >= 0) { if (con.match != null) { con.match.setBeginning(0, o); con.match.setEnd(0, o+this.fixedString.length()); } con.inuse = false; return true; } con.inuse = false; return false; } /* * The pattern contains a fixed string. * The engine checks with Boyer-Moore whether the text contains the fixed string or not. * If not, it return with false. */ if (this.fixedString != null) { int o = this.fixedStringTable.matches(target, con.start, con.limit); if (o < 0) { //System.err.println("Non-match in fixed-string search."); con.inuse = false; return false; } } int limit = con.limit-this.minlength; int matchStart; int matchEnd = -1; /* * Checks whether the expression starts with ".*". */ if (this.operations != null && this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) { if (isSet(this.options, SINGLE_LINE)) { matchStart = con.start; matchEnd = this. matchCharacterIterator (con, this.operations, con.start, 1, this.options); } else { boolean previousIsEOL = true; for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target .setIndex( matchStart ) ; if (isEOLChar(ch)) { previousIsEOL = true; } else { if (previousIsEOL) { if (0 <= (matchEnd = this. matchCharacterIterator (con, this.operations, matchStart, 1, this.options))) break; } previousIsEOL = false; } } } } /* * Optimization against the first character. */ else if (this.firstChar != null) { //System.err.println("DEBUG: with firstchar-matching: "+this.firstChar); RangeToken range = this.firstChar; if (RegularExpression.isSet(this.options, IGNORE_CASE)) { range = this.firstChar.getCaseInsensitiveToken(); for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target .setIndex( matchStart ) ; if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) { ch = REUtil.composeFromSurrogates(ch, target .setIndex( matchStart+1 ) ); if (!range.match(ch)) continue; } else { if (!range.match(ch)) { char ch1 = Character.toUpperCase((char)ch); if (!range.match(ch1)) if (!range.match(Character.toLowerCase(ch1))) continue; } } if (0 <= (matchEnd = this. matchCharacterIterator (con, this.operations, matchStart, 1, this.options))) break; } } else { for (matchStart = con.start; matchStart <= limit; matchStart ++) { int ch = target .setIndex( matchStart ) ; if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target .setIndex( matchStart+1 ) ); if (!range.match(ch)) continue; if (0 <= (matchEnd = this. matchCharacterIterator (con, this.operations, matchStart, 1, this.options))) break; } } } /* * Straightforward matching. */ else { for (matchStart = con.start; matchStart <= limit; matchStart ++) { if (0 <= (matchEnd = this. matchCharacterIterator (con, this.operations, matchStart, 1, this.options))) break; } } if (matchEnd >= 0) { if (con.match != null) { con.match.setBeginning(0, matchStart); con.match.setEnd(0, matchEnd); } con.inuse = false; return true; } else { con.inuse = false; return false; } } /** * @return -1 when not match; offset of the end of matched string when match. */ private int matchCharacterIterator (Context con, Op op, int offset, int dx, int opts) { CharacterIterator target = con.ciTarget; while (true) { if (op == null) return isSet(opts, XMLSCHEMA_MODE) && offset != con.limit ? -1 : offset; if (offset > con.limit || offset < con.start) return -1; switch (op.type) { case Op.CHAR: if (isSet(opts, IGNORE_CASE)) { int ch = op.getData(); if (dx > 0) { if (offset >= con.limit || !matchIgnoreCase(ch, target .setIndex( offset ) )) return -1; offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0 || !matchIgnoreCase(ch, target .setIndex( o1 ) )) return -1; offset = o1; } } else { int ch = op.getData(); if (dx > 0) { if (offset >= con.limit || ch != target .setIndex( offset ) ) return -1; offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0 || ch != target .setIndex( o1 ) ) return -1; offset = o1; } } op = op.next; break; case Op.DOT: if (dx > 0) { if (offset >= con.limit) return -1; int ch = target .setIndex( offset ) ; if (isSet(opts, SINGLE_LINE)) { if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) offset ++; } else { if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target .setIndex( ++offset ) ); if (isEOLChar(ch)) return -1; } offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0) return -1; int ch = target .setIndex( o1 ) ; if (isSet(opts, SINGLE_LINE)) { if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) o1 --; } else { if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) ch = REUtil.composeFromSurrogates( target .setIndex( --o1 ) , ch); if (!isEOLChar(ch)) return -1; } offset = o1; } op = op.next; break; case Op.RANGE: case Op.NRANGE: if (dx > 0) { if (offset >= con.limit) return -1; int ch = target .setIndex( offset ) ; if (REUtil.isHighSurrogate(ch) && offset+1 < con.limit) ch = REUtil.composeFromSurrogates(ch, target .setIndex( ++offset ) ); RangeToken tok = op.getToken(); if (isSet(opts, IGNORE_CASE)) { tok = tok.getCaseInsensitiveToken(); if (!tok.match(ch)) { if (ch >= 0x10000) return -1; char uch; if (!tok.match(uch = Character.toUpperCase((char)ch)) && !tok.match(Character.toLowerCase(uch))) return -1; } } else { if (!tok.match(ch)) return -1; } offset ++; } else { int o1 = offset-1; if (o1 >= con.limit || o1 < 0) return -1; int ch = target .setIndex( o1 ) ; if (REUtil.isLowSurrogate(ch) && o1-1 >= 0) ch = REUtil.composeFromSurrogates( target .setIndex( --o1 ) , ch); RangeToken tok = op.getToken(); if (isSet(opts, IGNORE_CASE)) { tok = tok.getCaseInsensitiveToken(); if (!tok.match(ch)) { if (ch >= 0x10000) return -1; char uch; if (!tok.match(uch = Character.toUpperCase((char)ch)) && !tok.match(Character.toLowerCase(uch))) return -1; } } else { if (!tok.match(ch)) return -1; } offset = o1; } op = op.next; break; case Op.ANCHOR: boolean go = false; switch (op.getData()) { case '^': if (isSet(opts, MULTIPLE_LINES)) { if (!(offset == con.start || offset > con.start && isEOLChar( target .setIndex( offset-1 ) ))) return -1; } else { if (offset != con.start) return -1; } break; case '@': // Internal use only. // The @ always matches line beginnings. if (!(offset == con.start || offset > con.start && isEOLChar( target .setIndex( offset-1 ) ))) return -1; break; case '$': if (isSet(opts, MULTIPLE_LINES)) { if (!(offset == con.limit || offset < con.limit && isEOLChar( target .setIndex( offset ) ))) return -1; } else { if (!(offset == con.limit || offset+1 == con.limit && isEOLChar( target .setIndex( offset ) ) || offset+2 == con.limit && target .setIndex( offset ) == CARRIAGE_RETURN && target .setIndex( offset+1 ) == LINE_FEED)) return -1; } break; case 'A': if (offset != con.start) return -1; break; case 'Z': if (!(offset == con.limit || offset+1 == con.limit && isEOLChar( target .setIndex( offset ) ) || offset+2 == con.limit && target .setIndex( offset ) == CARRIAGE_RETURN && target .setIndex( offset+1 ) == LINE_FEED)) return -1; break; case 'z': if (offset != con.limit) return -1; break; case 'b': if (con.length == 0) return -1; { int after = getWordType(target, con.start, con.limit, offset, opts); if (after == WT_IGNORE) return -1; int before = getPreviousWordType(target, con.start, con.limit, offset, opts); if (after == before) return -1; } break; case 'B': if (con.length == 0) go = true; else { int after = getWordType(target, con.start, con.limit, offset, opts); go = after == WT_IGNORE || after == getPreviousWordType(target, con.start, con.limit, offset, opts); } if (!go) return -1; break; case '<': if (con.length == 0 || offset == con.limit) return -1; if (getWordType(target, con.start, con.limit, offset, opts) != WT_LETTER || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_OTHER) return -1; break; case '>': if (con.length == 0 || offset == con.start) return -1; if (getWordType(target, con.start, con.limit, offset, opts) != WT_OTHER || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_LETTER) return -1; break; } // switch anchor type op = op.next; break; case Op.BACKREFERENCE: { int refno = op.getData(); if (refno <= 0 || refno >= this.nofparen) throw new RuntimeException("Internal Error: Reference number must be more than zero: "+refno); if (con.match.getBeginning(refno) < 0 || con.match.getEnd(refno) < 0) return -1; // ******** int o2 = con.match.getBeginning(refno); int literallen = con.match.getEnd(refno)-o2; if (!isSet(opts, IGNORE_CASE)) { if (dx > 0) { if (!regionMatches(target, offset, con.limit, o2, literallen)) return -1; offset += literallen; } else { if (!regionMatches(target, offset-literallen, con.limit, o2, literallen)) return -1; offset -= literallen; } } else { if (dx > 0) { if (!regionMatchesIgnoreCase(target, offset, con.limit, o2, literallen)) return -1; offset += literallen; } else { if (!regionMatchesIgnoreCase(target, offset-literallen, con.limit, o2, literallen)) return -1; offset -= literallen; } } } op = op.next; break; case Op.STRING: { String literal = op.getString(); int literallen = literal.length(); if (!isSet(opts, IGNORE_CASE)) { if (dx > 0) { if (!regionMatches(target, offset, con.limit, literal, literallen)) return -1; offset += literallen; } else { if (!regionMatches(target, offset-literallen, con.limit, literal, literallen)) return -1; offset -= literallen; } } else { if (dx > 0) { if (!regionMatchesIgnoreCase(target, offset, con.limit, literal, literallen)) return -1; offset += literallen; } else { if (!regionMatchesIgnoreCase(target, offset-literallen, con.limit, literal, literallen)) return -1; offset -= literallen; } } } op = op.next; break; case Op.CLOSURE: { /* * Saves current position to avoid * zero-width repeats. */ int id = op.getData(); if (id >= 0) { int previousOffset = con.offsets[id]; if (previousOffset < 0 || previousOffset != offset) { con.offsets[id] = offset; } else { con.offsets[id] = -1; op = op.next; break; } } int ret = this. matchCharacterIterator (con, op.getChild(), offset, dx, opts); if (id >= 0) con.offsets[id] = -1; if (ret >= 0) return ret; op = op.next; } break; case Op.QUESTION: { int ret = this. matchCharacterIterator (con, op.getChild(), offset, dx, opts); if (ret >= 0) return ret; op = op.next; } break; case Op.NONGREEDYCLOSURE: case Op.NONGREEDYQUESTION: { int ret = this. matchCharacterIterator (con, op.next, offset, dx, opts); if (ret >= 0) return ret; op = op.getChild(); } break; case Op.UNION: for (int i = 0; i < op.size(); i ++) { int ret = this. matchCharacterIterator (con, op.elementAt(i), offset, dx, opts); if (DEBUG) { System.err.println("UNION: "+i+", ret="+ret); } if (ret >= 0) return ret; } return -1; case Op.CAPTURE: int refno = op.getData(); if (con.match != null && refno > 0) { int save = con.match.getBeginning(refno); con.match.setBeginning(refno, offset); int ret = this. matchCharacterIterator (con, op.next, offset, dx, opts); if (ret < 0) con.match.setBeginning(refno, save); return ret; } else if (con.match != null && refno < 0) { int index = -refno; int save = con.match.getEnd(index); con.match.setEnd(index, offset); int ret = this. matchCharacterIterator (con, op.next, offset, dx, opts); if (ret < 0) con.match.setEnd(index, save); return ret; } op = op.next; break; case Op.LOOKAHEAD: if (0 > this. matchCharacterIterator (con, op.getChild(), offset, 1, opts)) return -1; op = op.next; break; case Op.NEGATIVELOOKAHEAD: if (0 <= this. matchCharacterIterator (con, op.getChild(), offset, 1, opts)) return -1; op = op.next; break; case Op.LOOKBEHIND: if (0 > this. matchCharacterIterator (con, op.getChild(), offset, -1, opts)) return -1; op = op.next; break; case Op.NEGATIVELOOKBEHIND: if (0 <= this. matchCharacterIterator (con, op.getChild(), offset, -1, opts)) return -1; op = op.next; break; case Op.INDEPENDENT: { int ret = this. matchCharacterIterator (con, op.getChild(), offset, dx, opts); if (ret < 0) return ret; offset = ret; op = op.next; } break; case Op.MODIFIER: { int localopts = opts; localopts |= op.getData(); localopts &= ~op.getData2(); //System.err.println("MODIFIER: "+Integer.toString(opts, 16)+" -> "+Integer.toString(localopts, 16)); int ret = this. matchCharacterIterator (con, op.getChild(), offset, dx, localopts); if (ret < 0) return ret; offset = ret; op = op.next; } break; case Op.CONDITION: { Op.ConditionOp cop = (Op.ConditionOp)op; boolean matchp = false; if (cop.refNumber > 0) { if (cop.refNumber >= this.nofparen) throw new RuntimeException("Internal Error: Reference number must be more than zero: "+cop.refNumber); matchp = con.match.getBeginning(cop.refNumber) >= 0 && con.match.getEnd(cop.refNumber) >= 0; } else { matchp = 0 <= this. matchCharacterIterator (con, cop.condition, offset, dx, opts); } if (matchp) { op = cop.yes; } else if (cop.no != null) { op = cop.no; } else { op = cop.next; } } break; default: throw new RuntimeException("Unknown operation type: "+op.type); } // switch (op.type) } // while } private static final int getPreviousWordType(CharacterIterator target, int begin, int end, int offset, int opts) { int ret = getWordType(target, begin, end, --offset, opts); while (ret == WT_IGNORE) ret = getWordType(target, begin, end, --offset, opts); return ret; } private static final int getWordType(CharacterIterator target, int begin, int end, int offset, int opts) { if (offset < begin || offset >= end) return WT_OTHER; return getWordType0( target .setIndex( offset ) , opts); } private static final boolean regionMatches(CharacterIterator target, int offset, int limit, String part, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = 0; while (partlen-- > 0) { if ( target .setIndex( offset++ ) != part.charAt(i++)) return false; } return true; } private static final boolean regionMatches(CharacterIterator target, int offset, int limit, int offset2, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = offset2; while (partlen-- > 0) { if ( target .setIndex( offset++ ) != target .setIndex( i++ ) ) return false; } return true; } /** * @see java.lang.String#regionMatches */ private static final boolean regionMatchesIgnoreCase(CharacterIterator target, int offset, int limit, String part, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = 0; while (partlen-- > 0) { char ch1 = target .setIndex( offset++ ) ; char ch2 = part.charAt(i++); if (ch1 == ch2) continue; char uch1 = Character.toUpperCase(ch1); char uch2 = Character.toUpperCase(ch2); if (uch1 == uch2) continue; if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) return false; } return true; } private static final boolean regionMatchesIgnoreCase(CharacterIterator target, int offset, int limit, int offset2, int partlen) { if (offset < 0) return false; if (limit-offset < partlen) return false; int i = offset2; while (partlen-- > 0) { char ch1 = target .setIndex( offset++ ) ; char ch2 = target .setIndex( i++ ) ; if (ch1 == ch2) continue; char uch1 = Character.toUpperCase(ch1); char uch2 = Character.toUpperCase(ch2); if (uch1 == uch2) continue; if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) return false; } return true; } // ================================================================ /** * A regular expression. * @serial */ String regex; /** * @serial */ int options; /** * The number of parenthesis in the regular expression. * @serial */ int nofparen; /** * Internal representation of the regular expression. * @serial */ Token tokentree; boolean hasBackReferences = false; transient int minlength; transient Op operations = null; transient int numberOfClosures; transient Context context = null; transient RangeToken firstChar = null; transient String fixedString = null; transient int fixedStringOptions; transient BMPattern fixedStringTable = null; transient boolean fixedStringOnly = false; static final class Context { CharacterIterator ciTarget; String strTarget; char[] charTarget; int start; int limit; int length; Match match; boolean inuse = false; int[] offsets; Context() { } private void resetCommon(int nofclosures) { this.length = this.limit-this.start; this.inuse = true; this.match = null; if (this.offsets == null || this.offsets.length != nofclosures) this.offsets = new int[nofclosures]; for (int i = 0; i < nofclosures; i ++) this.offsets[i] = -1; } void reset(CharacterIterator target, int start, int limit, int nofclosures) { this.ciTarget = target; this.start = start; this.limit = limit; this.resetCommon(nofclosures); } void reset(String target, int start, int limit, int nofclosures) { this.strTarget = target; this.start = start; this.limit = limit; this.resetCommon(nofclosures); } void reset(char[] target, int start, int limit, int nofclosures) { this.charTarget = target; this.start = start; this.limit = limit; this.resetCommon(nofclosures); } } /** * Prepares for matching. This method is called just before starting matching. */ void prepare() { if (Op.COUNT) Op.nofinstances = 0; this.compile(this.tokentree); /* if (this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) { // .* Op anchor = Op.createAnchor(isSet(this.options, SINGLE_LINE) ? 'A' : '@'); anchor.next = this.operations; this.operations = anchor; } */ if (Op.COUNT) System.err.println("DEBUG: The number of operations: "+Op.nofinstances); this.minlength = this.tokentree.getMinLength(); this.firstChar = null; if (!isSet(this.options, PROHIBIT_HEAD_CHARACTER_OPTIMIZATION) && !isSet(this.options, XMLSCHEMA_MODE)) { RangeToken firstChar = Token.createRange(); int fresult = this.tokentree.analyzeFirstCharacter(firstChar, this.options); if (fresult == Token.FC_TERMINAL) { firstChar.compactRanges(); this.firstChar = firstChar; if (DEBUG) System.err.println("DEBUG: Use the first character optimization: "+firstChar); } } if (this.operations != null && (this.operations.type == Op.STRING || this.operations.type == Op.CHAR) && this.operations.next == null) { if (DEBUG) System.err.print(" *** Only fixed string! *** "); this.fixedStringOnly = true; if (this.operations.type == Op.STRING) this.fixedString = this.operations.getString(); else if (this.operations.getData() >= 0x10000) { // Op.CHAR this.fixedString = REUtil.decomposeToSurrogates(this.operations.getData()); } else { char[] ac = new char[1]; ac[0] = (char)this.operations.getData(); this.fixedString = new String(ac); } this.fixedStringOptions = this.options; this.fixedStringTable = new BMPattern(this.fixedString, 256, isSet(this.fixedStringOptions, IGNORE_CASE)); } else if (!isSet(this.options, PROHIBIT_FIXED_STRING_OPTIMIZATION) && !isSet(this.options, XMLSCHEMA_MODE)) { Token.FixedStringContainer container = new Token.FixedStringContainer(); this.tokentree.findFixedString(container, this.options); this.fixedString = container.token == null ? null : container.token.getString(); this.fixedStringOptions = container.options; if (this.fixedString != null && this.fixedString.length() < 2) this.fixedString = null; // This pattern has a fixed string of which length is more than one. if (this.fixedString != null) { this.fixedStringTable = new BMPattern(this.fixedString, 256, isSet(this.fixedStringOptions, IGNORE_CASE)); if (DEBUG) { System.err.println("DEBUG: The longest fixed string: "+this.fixedString.length() +"/" //+this.fixedString +"/"+REUtil.createOptionString(this.fixedStringOptions)); System.err.print("String: "); REUtil.dumpString(this.fixedString); } } } } /** * An option. * If you specify this option, (X) * captures matched text, and (:?X) * does not capture. * * @see #RegularExpression(java.lang.String,int) * @see #setPattern(java.lang.String,int) static final int MARK_PARENS = 1<<0; */ /** * "i" */ static final int IGNORE_CASE = 1<<1; /** * "s" */ static final int SINGLE_LINE = 1<<2; /** * "m" */ static final int MULTIPLE_LINES = 1<<3; /** * "x" */ static final int EXTENDED_COMMENT = 1<<4; /** * This option redefines \d \D \w \W \s \S. * * @see #RegularExpression(java.lang.String,int) * @see #setPattern(java.lang.String,int) * @see #UNICODE_WORD_BOUNDARY */ static final int USE_UNICODE_CATEGORY = 1<<5; // "u" /** * An option. * This enables to process locale-independent word boundary for \b \B \< \>. *

By default, the engine considers a position between a word character * (\w) and a non word character * is a word boundary. *

By this option, the engine checks word boundaries with the method of * 'Unicode Regular Expression Guidelines' Revision 4. * * @see #RegularExpression(java.lang.String,int) * @see #setPattern(java.lang.String,int) */ static final int UNICODE_WORD_BOUNDARY = 1<<6; // "w" /** * "H" */ static final int PROHIBIT_HEAD_CHARACTER_OPTIMIZATION = 1<<7; /** * "F" */ static final int PROHIBIT_FIXED_STRING_OPTIMIZATION = 1<<8; /** * "X". XML Schema mode. */ static final int XMLSCHEMA_MODE = 1<<9; /** * ",". */ static final int SPECIAL_COMMA = 1<<10; private static final boolean isSet(int options, int flag) { return (options & flag) == flag; } /** * Creates a new RegularExpression instance. * * @param regex A regular expression * @exception org.apache.xerces.utils.regex.ParseException regex is not conforming to the syntax. */ public RegularExpression(String regex) throws ParseException { this.setPattern(regex, null); } /** * Creates a new RegularExpression instance with options. * * @param regex A regular expression * @param options A String consisted of "i" "m" "s" "u" "w" "," "X" * @exception org.apache.xerces.utils.regex.ParseException regex is not conforming to the syntax. */ public RegularExpression(String regex, String options) throws ParseException { this.setPattern(regex, options); } RegularExpression(String regex, Token tok, int parens, boolean hasBackReferences, int options) { this.regex = regex; this.tokentree = tok; this.nofparen = parens; this.options = options; this.hasBackReferences = hasBackReferences; } /** * */ public void setPattern(String newPattern) throws ParseException { this.setPattern(newPattern, this.options); } private void setPattern(String newPattern, int options) throws ParseException { this.regex = newPattern; this.options = options; RegexParser rp = RegularExpression.isSet(this.options, RegularExpression.XMLSCHEMA_MODE) ? new ParserForXMLSchema() : new RegexParser(); this.tokentree = rp.parse(this.regex, this.options); this.nofparen = rp.parennumber; this.hasBackReferences = rp.hasBackReferences; this.operations = null; this.context = null; } /** * */ public void setPattern(String newPattern, String options) throws ParseException { this.setPattern(newPattern, REUtil.parseOptions(options)); } /** * */ public String getPattern() { return this.regex; } /** * Represents this instence in String. */ public String toString() { return this.tokentree.toString(this.options); } /** * Returns a option string. * The order of letters in it may be different from a string specified * in a constructor or setPattern(). * * @see #RegularExpression(java.lang.String,java.lang.String) * @see #setPattern(java.lang.String,java.lang.String) */ public String getOptions() { return REUtil.createOptionString(this.options); } /** * Return true if patterns are the same and the options are equivalent. */ public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof RegularExpression)) return false; RegularExpression r = (RegularExpression)obj; return this.regex.equals(r.regex) && this.options == r.options; } boolean equals(String pattern, int options) { return this.regex.equals(pattern) && this.options == options; } /** * */ public int hashCode() { return (this.regex+"/"+this.getOptions()).hashCode(); } /** * Return the number of regular expression groups. * This method returns 1 when the regular expression has no capturing-parenthesis. * */ public int getNumberOfGroups() { return this.nofparen; } // ================================================================ private static final int WT_IGNORE = 0; private static final int WT_LETTER = 1; private static final int WT_OTHER = 2; private static final int getWordType0(char ch, int opts) { if (!isSet(opts, UNICODE_WORD_BOUNDARY)) { if (isSet(opts, USE_UNICODE_CATEGORY)) { return (Token.getRange("IsWord", true).match(ch)) ? WT_LETTER : WT_OTHER; } return isWordChar(ch) ? WT_LETTER : WT_OTHER; } switch (Character.getType(ch)) { case Character.UPPERCASE_LETTER: // L case Character.LOWERCASE_LETTER: // L case Character.TITLECASE_LETTER: // L case Character.MODIFIER_LETTER: // L case Character.OTHER_LETTER: // L case Character.LETTER_NUMBER: // N case Character.DECIMAL_DIGIT_NUMBER: // N case Character.OTHER_NUMBER: // N case Character.COMBINING_SPACING_MARK: // Mc return WT_LETTER; case Character.FORMAT: // Cf case Character.NON_SPACING_MARK: // Mn case Character.ENCLOSING_MARK: // Mc return WT_IGNORE; case Character.CONTROL: // Cc switch (ch) { case '\t': case '\n': case '\u000B': case '\f': case '\r': return WT_OTHER; default: return WT_IGNORE; } default: return WT_OTHER; } } // ================================================================ static final int LINE_FEED = 0x000A; static final int CARRIAGE_RETURN = 0x000D; static final int LINE_SEPARATOR = 0x2028; static final int PARAGRAPH_SEPARATOR = 0x2029; private static final boolean isEOLChar(int ch) { return ch == LINE_FEED || ch == CARRIAGE_RETURN || ch == LINE_SEPARATOR || ch == PARAGRAPH_SEPARATOR; } private static final boolean isWordChar(int ch) { // Legacy word characters if (ch == '_') return true; if (ch < '0') return false; if (ch > 'z') return false; if (ch <= '9') return true; if (ch < 'A') return false; if (ch <= 'Z') return true; if (ch < 'a') return false; return true; } private static final boolean matchIgnoreCase(int chardata, int ch) { if (chardata == ch) return true; if (chardata > 0xffff || ch > 0xffff) return false; char uch1 = Character.toUpperCase((char)chardata); char uch2 = Character.toUpperCase((char)ch); if (uch1 == uch2) return true; return Character.toLowerCase(uch1) == Character.toLowerCase(uch2); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/RangeToken.java0000644000175000017500000006210411361341574024706 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/message_ja.properties0000644000175000017500000000741711361341574026230 0ustar apoapoparser.parse.1=\u3078\u3093\u306a\u6587\u5b57. parser.parse.2=\u5b58\u5728\u3057\u306a\u3044\u30b0\u30eb\u30fc\u30d7\u756a\u53f7\u3067\u3059. parser.next.1=\\ \u306e\u5f8c\u306b1\u6587\u5b57\u5fc5\u8981\u3067\u3059. parser.next.2='?' \u3092\u3053\u3053\u306b\u66f8\u304f\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093. \u3082\u3057\u304b\u3057\u3066 '(?:' \u304b '(?=' \u304b '(?!' \u304b '(?<' \u304b '(?#' \u304b '(?>' \u3067\u3059\u304b? parser.next.3='(?<=' \u304b '(? 0) { ma.setNumberOfGroups(this.nofgroups); if (this.ciSource != null) ma.setSource(this.ciSource); if (this.strSource != null) ma.setSource(this.strSource); for (int i = 0; i < this.nofgroups; i ++) { ma.setBeginning(i, this.getBeginning(i)); ma.setEnd(i, this.getEnd(i)); } } return ma; } /** * */ protected void setNumberOfGroups(int n) { int oldn = this.nofgroups; this.nofgroups = n; if (oldn <= 0 || oldn < n || n*2 < oldn) { this.beginpos = new int[n]; this.endpos = new int[n]; } for (int i = 0; i < n; i ++) { this.beginpos[i] = -1; this.endpos[i] = -1; } } /** * */ protected void setSource(CharacterIterator ci) { this.ciSource = ci; this.strSource = null; this.charSource = null; } /** * */ protected void setSource(String str) { this.ciSource = null; this.strSource = str; this.charSource = null; } /** * */ protected void setSource(char[] chars) { this.ciSource = null; this.strSource = null; this.charSource = chars; } /** * */ protected void setBeginning(int index, int v) { this.beginpos[index] = v; } /** * */ protected void setEnd(int index, int v) { this.endpos[index] = v; } /** * Return the number of regular expression groups. * This method returns 1 when the regular expression has no capturing-parenthesis. */ public int getNumberOfGroups() { if (this.nofgroups <= 0) throw new IllegalStateException("A result is not set."); return this.nofgroups; } /** * Return a start position in the target text matched to specified regular expression group. * * @param index Less than getNumberOfGroups(). */ public int getBeginning(int index) { if (this.beginpos == null) throw new IllegalStateException("A result is not set."); if (index < 0 || this.nofgroups <= index) throw new IllegalArgumentException("The parameter must be less than " +this.nofgroups+": "+index); return this.beginpos[index]; } /** * Return an end position in the target text matched to specified regular expression group. * * @param index Less than getNumberOfGroups(). */ public int getEnd(int index) { if (this.endpos == null) throw new IllegalStateException("A result is not set."); if (index < 0 || this.nofgroups <= index) throw new IllegalArgumentException("The parameter must be less than " +this.nofgroups+": "+index); return this.endpos[index]; } /** * Return an substring of the target text matched to specified regular expression group. * * @param index Less than getNumberOfGroups(). */ public String getCapturedText(int index) { if (this.beginpos == null) throw new IllegalStateException("match() has never been called."); if (index < 0 || this.nofgroups <= index) throw new IllegalArgumentException("The parameter must be less than " +this.nofgroups+": "+index); String ret; int begin = this.beginpos[index], end = this.endpos[index]; if (begin < 0 || end < 0) return null; if (this.ciSource != null) { ret = REUtil.substring(this.ciSource, begin, end); } else if (this.strSource != null) { ret = this.strSource.substring(begin, end); } else { ret = new String(this.charSource, begin, end-begin); } return ret; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/ParserForXMLSchema.java0000644000175000017500000005363111746040262026260 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Hashtable; import java.util.Locale; /** * A regular expression parser for the XML Schema. * * @author TAMURA Kent <kent@trl.ibm.co.jp> */ class ParserForXMLSchema extends RegexParser { public ParserForXMLSchema() { //this.setLocale(Locale.getDefault()); } public ParserForXMLSchema(Locale locale) { //this.setLocale(locale); } Token processCaret() throws ParseException { this.next(); return Token.createChar('^'); } Token processDollar() throws ParseException { this.next(); return Token.createChar('$'); } Token processLookahead() throws ParseException { throw ex("parser.process.1", this.offset); } Token processNegativelookahead() throws ParseException { throw ex("parser.process.1", this.offset); } Token processLookbehind() throws ParseException { throw ex("parser.process.1", this.offset); } Token processNegativelookbehind() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_A() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_Z() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_z() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_b() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_B() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_lt() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_gt() throws ParseException { throw ex("parser.process.1", this.offset); } Token processStar(Token tok) throws ParseException { this.next(); return Token.createClosure(tok); } Token processPlus(Token tok) throws ParseException { // X+ -> XX* this.next(); return Token.createConcat(tok, Token.createClosure(tok)); } Token processQuestion(Token tok) throws ParseException { // X? -> X| this.next(); Token par = Token.createUnion(); par.addChild(tok); par.addChild(Token.createEmpty()); return par; } boolean checkQuestion(int off) { return false; } Token processParen() throws ParseException { this.next(); Token tok = Token.createParen(this.parseRegex(), 0); if (this.read() != super.T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // Skips ')' return tok; } Token processParen2() throws ParseException { throw ex("parser.process.1", this.offset); } Token processCondition() throws ParseException { throw ex("parser.process.1", this.offset); } Token processModifiers() throws ParseException { throw ex("parser.process.1", this.offset); } Token processIndependent() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_c() throws ParseException { this.next(); return this.getTokenForShorthand('c'); } Token processBacksolidus_C() throws ParseException { this.next(); return this.getTokenForShorthand('C'); } Token processBacksolidus_i() throws ParseException { this.next(); return this.getTokenForShorthand('i'); } Token processBacksolidus_I() throws ParseException { this.next(); return this.getTokenForShorthand('I'); } Token processBacksolidus_g() throws ParseException { throw this.ex("parser.process.1", this.offset-2); } Token processBacksolidus_X() throws ParseException { throw ex("parser.process.1", this.offset-2); } Token processBackreference() throws ParseException { throw ex("parser.process.1", this.offset-4); } int processCIinCharacterClass(RangeToken tok, int c) { tok.mergeRanges(this.getTokenForShorthand(c)); return -1; } /** * Parses a character-class-expression, not a character-class-escape. * * c-c-expression ::= '[' c-group ']' * c-group ::= positive-c-group | negative-c-group | c-c-subtraction * positive-c-group ::= (c-range | c-c-escape)+ * negative-c-group ::= '^' positive-c-group * c-c-subtraction ::= (positive-c-group | negative-c-group) subtraction * subtraction ::= '-' c-c-expression * c-range ::= single-range | from-to-range * single-range ::= multi-c-escape | category-c-escape | block-c-escape | * cc-normal-c ::= * from-to-range ::= cc-normal-c '-' cc-normal-c * * @param useNrage Ignored. * @return This returns no NrangeToken. */ protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException { this.setContext(S_INBRACKETS); this.next(); // '[' boolean nrange = false; RangeToken base = null; RangeToken tok; if (this.read() == T_CHAR && this.chardata == '^') { nrange = true; this.next(); // '^' base = Token.createRange(); base.addRange(0, Token.UTF16_MAX); tok = Token.createRange(); } else { tok = Token.createRange(); } int type; boolean firstloop = true; while ((type = this.read()) != T_EOF) { // Don't use 'cotinue' for this loop. // single-range | from-to-range | subtraction if (type == T_CHAR && this.chardata == ']' && !firstloop) { if (nrange) { base.subtractRanges(tok); tok = base; } break; } int c = this.chardata; boolean end = false; if (type == T_BACKSOLIDUS) { switch (c) { case 'd': case 'D': case 'w': case 'W': case 's': case 'S': tok.mergeRanges(this.getTokenForShorthand(c)); end = true; break; case 'i': case 'I': case 'c': case 'C': c = this.processCIinCharacterClass(tok, c); if (c < 0) end = true; break; case 'p': case 'P': int pstart = this.offset; RangeToken tok2 = this.processBacksolidus_pP(c); if (tok2 == null) throw this.ex("parser.atom.5", pstart); tok.mergeRanges(tok2); end = true; break; default: c = this.decodeEscaped(); } // \ + c } // backsolidus else if (type == T_XMLSCHEMA_CC_SUBTRACTION && !firstloop) { // Subraction if (nrange) { base.subtractRanges(tok); tok = base; } RangeToken range2 = this.parseCharacterClass(false); tok.subtractRanges(range2); if (this.read() != T_CHAR || this.chardata != ']') throw this.ex("parser.cc.5", this.offset); break; // Exit this loop } this.next(); if (!end) { // if not shorthands... if (type == T_CHAR) { if (c == '[') throw this.ex("parser.cc.6", this.offset-2); if (c == ']') throw this.ex("parser.cc.7", this.offset-2); //https://issues.apache.org/jira/browse/XMLBEANS-412 //unescaped single char '-' is a valid char after '[' and before ']' positive range only if (c== '-' && !firstloop && this.chardata!=']') throw this.ex("parser.cc.8", this.offset-2); } if (this.read() != T_CHAR || this.chardata != '-') { // Here is no '-'. tok.addRange(c, c); } else { // Found '-' // Is this '-' is a from-to token?? this.next(); // Skips '-' if ((type = this.read()) == T_EOF) throw this.ex("parser.cc.2", this.offset); // c '-' ']' -> '-' is a single-range. if (type == T_XMLSCHEMA_CC_SUBTRACTION) { throw this.ex("parser.cc.8", this.offset-1); } else if (type == T_CHAR && this.chardata == ']') { //'-' occurs after a single-range but before ']' tok.addRange(c,c); tok.addRange('-','-'); } else { int rangeend = this.chardata; if (type == T_CHAR) { if (rangeend == '[') throw this.ex("parser.cc.6", this.offset-1); if (rangeend == ']') throw this.ex("parser.cc.7", this.offset-1); if (rangeend == '-') { this.next(); if (this.chardata!=']') throw this.ex("parser.cc.8", this.offset-2); } } else if (type == T_BACKSOLIDUS) rangeend = this.decodeEscaped(); if (rangeend!='-' || this.chardata!=']') this.next(); if (c > rangeend) throw this.ex("parser.ope.3", this.offset-1); tok.addRange(c, rangeend); } } } firstloop = false; } if (this.read() == T_EOF) throw this.ex("parser.cc.2", this.offset); tok.sortRanges(); tok.compactRanges(); //tok.dumpRanges(); this.setContext(S_NORMAL); this.next(); // Skips ']' return tok; } protected RangeToken parseSetOperations() throws ParseException { throw this.ex("parser.process.1", this.offset); } Token getTokenForShorthand(int ch) { switch (ch) { case 'd': return ParserForXMLSchema.getRange("xml:isDigit", true); case 'D': return ParserForXMLSchema.getRange("xml:isDigit", false); case 'w': return ParserForXMLSchema.getRange("xml:isWord", true); case 'W': return ParserForXMLSchema.getRange("xml:isWord", false); case 's': return ParserForXMLSchema.getRange("xml:isSpace", true); case 'S': return ParserForXMLSchema.getRange("xml:isSpace", false); case 'c': return ParserForXMLSchema.getRange("xml:isNameChar", true); case 'C': return ParserForXMLSchema.getRange("xml:isNameChar", false); case 'i': return ParserForXMLSchema.getRange("xml:isInitialNameChar", true); case 'I': return ParserForXMLSchema.getRange("xml:isInitialNameChar", false); default: throw new RuntimeException("Internal Error: shorthands: \\u"+Integer.toString(ch, 16)); } } int decodeEscaped() throws ParseException { if (this.read() != T_BACKSOLIDUS) throw ex("parser.next.1", this.offset-1); int c = this.chardata; switch (c) { case 'n': c = '\n'; break; // LINE FEED U+000A case 'r': c = '\r'; break; // CRRIAGE RETURN U+000D case 't': c = '\t'; break; // HORIZONTAL TABULATION U+0009 case '\\': case '|': case '.': case '^': case '-': case '?': case '*': case '+': case '{': case '}': case '(': case ')': case '[': case ']': break; // return actucal char default: throw ex("parser.process.1", this.offset-2); } return c; } static private Hashtable ranges = null; static private Hashtable ranges2 = null; static synchronized protected RangeToken getRange(String name, boolean positive) { if (ranges == null) { ranges = new Hashtable(); ranges2 = new Hashtable(); Token tok = Token.createRange(); setupRange(tok, SPACES); ranges.put("xml:isSpace", tok); ranges2.put("xml:isSpace", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, DIGITS); ranges.put("xml:isDigit", tok); ranges2.put("xml:isDigit", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, DIGITS); ranges.put("xml:isDigit", tok); ranges2.put("xml:isDigit", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, LETTERS); tok.mergeRanges((Token)ranges.get("xml:isDigit")); ranges.put("xml:isWord", tok); ranges2.put("xml:isWord", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, NAMECHARS); ranges.put("xml:isNameChar", tok); ranges2.put("xml:isNameChar", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, LETTERS); tok.addRange('_', '_'); tok.addRange(':', ':'); ranges.put("xml:isInitialNameChar", tok); ranges2.put("xml:isInitialNameChar", Token.complementRanges(tok)); } RangeToken tok = positive ? (RangeToken)ranges.get(name) : (RangeToken)ranges2.get(name); return tok; } static void setupRange(Token range, String src) { int len = src.length(); for (int i = 0; i < len; i += 2) range.addRange(src.charAt(i), src.charAt(i+1)); } private static final String SPACES = "\t\n\r\r "; private static final String NAMECHARS = "\u002d\u002e\u0030\u003a\u0041\u005a\u005f\u005f\u0061\u007a\u00b7\u00b7\u00c0\u00d6" +"\u00d8\u00f6\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" +"\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345\u0360\u0361" +"\u0386\u038a\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c\u045e\u0481" +"\u0483\u0486\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9" +"\u0531\u0556\u0559\u0559\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd\u05bf\u05bf" +"\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" +"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9" +"\u0901\u0903\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963\u0966\u096f\u0981\u0983" +"\u0985\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09bc\u09bc" +"\u09be\u09c4\u09c7\u09c8\u09cb\u09cd\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" +"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" +"\u0a38\u0a39\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d\u0a59\u0a5c\u0a5e\u0a5e" +"\u0a66\u0a74\u0a81\u0a83\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0" +"\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" +"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39" +"\u0b3c\u0b43\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f\u0b61\u0b66\u0b6f" +"\u0b82\u0b83\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" +"\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" +"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" +"\u0c35\u0c39\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56\u0c60\u0c61\u0c66\u0c6f" +"\u0c82\u0c83\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cbe\u0cc4" +"\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" +"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d" +"\u0d57\u0d57\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a\u0e40\u0e4e\u0e50\u0e59" +"\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f" +"\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" +"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35" +"\u0f37\u0f37\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84\u0f86\u0f8b\u0f90\u0f95" +"\u0f97\u0f97\u0f99\u0fad\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6\u1100\u1100" +"\u1102\u1103\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159\u115f\u1161" +"\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" +"\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2" +"\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d" +"\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" +"\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126\u212a\u212b" +"\u212e\u212e\u2180\u2182\u3005\u3005\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" +"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe\u3105\u312c\u4e00\u9fa5\uac00\ud7a3" +""; private static final String LETTERS = "\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e\u0141\u0148" +"\u014a\u017e\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" +"\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6\u03da\u03da" +"\u03dc\u03dc\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" +"\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9" +"\u0531\u0556\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" +"\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6\u0905\u0939" +"\u093d\u093d\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" +"\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" +"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" +"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9" +"\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" +"\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95" +"\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" +"\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c" +"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" +"\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33" +"\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0" +"\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" +"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112\u113c\u113c" +"\u113e\u113e\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" +"\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e\u1172\u1173" +"\u1175\u1175\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15" +"\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" +"\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3" +"\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" +"\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c\u4e00\u9fa5" +"\uac00\ud7a3"; private static final String DIGITS = "\u0030\u0039\u0660\u0669\u06F0\u06F9\u0966\u096F\u09E6\u09EF\u0A66\u0A6F\u0AE6\u0AEF" +"\u0B66\u0B6F\u0BE7\u0BEF\u0C66\u0C6F\u0CE6\u0CEF\u0D66\u0D6F\u0E50\u0E59\u0ED0\u0ED9" +"\u0F20\u0F29"; } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/BMPattern.java0000644000175000017500000002012111361341574024476 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.text.CharacterIterator; /** * Boyer-Moore searcher. */ public class BMPattern { char[] pattern; int[] shiftTable; boolean ignoreCase; public BMPattern(String pat, boolean ignoreCase) { this(pat, 256, ignoreCase); } public BMPattern(String pat, int tableSize, boolean ignoreCase) { this.pattern = pat.toCharArray(); this.shiftTable = new int[tableSize]; this.ignoreCase = ignoreCase; int length = pattern.length; for (int i = 0; i < this.shiftTable.length; i ++) this.shiftTable[i] = length; for (int i = 0; i < length; i ++) { char ch = this.pattern[i]; int diff = length-i-1; int index = ch % this.shiftTable.length; if (diff < this.shiftTable[index]) this.shiftTable[index] = diff; if (this.ignoreCase) { ch = Character.toUpperCase(ch); index = ch % this.shiftTable.length; if (diff < this.shiftTable[index]) this.shiftTable[index] = diff; ch = Character.toLowerCase(ch); index = ch % this.shiftTable.length; if (diff < this.shiftTable[index]) this.shiftTable[index] = diff; } } } /** * * @return -1 if iterator does not contain this pattern. */ public int matches(CharacterIterator iterator, int start, int limit) { if (this.ignoreCase) return this.matchesIgnoreCase(iterator, start, limit); int plength = this.pattern.length; if (plength == 0) return start; int index = start+plength; while (index <= limit) { int pindex = plength; int nindex = index+1; char ch; do { if ((ch = iterator.setIndex(--index)) != this.pattern[--pindex]) break; if (pindex == 0) return index; } while (pindex > 0); index += this.shiftTable[ch % this.shiftTable.length]+1; if (index < nindex) index = nindex; } return -1; } /** * * @return -1 if str does not contain this pattern. */ public int matches(String str, int start, int limit) { if (this.ignoreCase) return this.matchesIgnoreCase(str, start, limit); int plength = this.pattern.length; if (plength == 0) return start; int index = start+plength; while (index <= limit) { //System.err.println("Starts at "+index); int pindex = plength; int nindex = index+1; char ch; do { if ((ch = str.charAt(--index)) != this.pattern[--pindex]) break; if (pindex == 0) return index; } while (pindex > 0); index += this.shiftTable[ch % this.shiftTable.length]+1; if (index < nindex) index = nindex; } return -1; } /** * * @return -1 if chars does not contain this pattern. */ public int matches(char[] chars, int start, int limit) { if (this.ignoreCase) return this.matchesIgnoreCase(chars, start, limit); int plength = this.pattern.length; if (plength == 0) return start; int index = start+plength; while (index <= limit) { //System.err.println("Starts at "+index); int pindex = plength; int nindex = index+1; char ch; do { if ((ch = chars[--index]) != this.pattern[--pindex]) break; if (pindex == 0) return index; } while (pindex > 0); index += this.shiftTable[ch % this.shiftTable.length]+1; if (index < nindex) index = nindex; } return -1; } int matchesIgnoreCase(CharacterIterator iterator, int start, int limit) { int plength = this.pattern.length; if (plength == 0) return start; int index = start+plength; while (index <= limit) { int pindex = plength; int nindex = index+1; char ch; do { char ch1 = ch = iterator.setIndex(--index); char ch2 = this.pattern[--pindex]; if (ch1 != ch2) { ch1 = Character.toUpperCase(ch1); ch2 = Character.toUpperCase(ch2); if (ch1 != ch2 && Character.toLowerCase(ch1) != Character.toLowerCase(ch2)) break; } if (pindex == 0) return index; } while (pindex > 0); index += this.shiftTable[ch % this.shiftTable.length]+1; if (index < nindex) index = nindex; } return -1; } int matchesIgnoreCase(String text, int start, int limit) { int plength = this.pattern.length; if (plength == 0) return start; int index = start+plength; while (index <= limit) { int pindex = plength; int nindex = index+1; char ch; do { char ch1 = ch = text.charAt(--index); char ch2 = this.pattern[--pindex]; if (ch1 != ch2) { ch1 = Character.toUpperCase(ch1); ch2 = Character.toUpperCase(ch2); if (ch1 != ch2 && Character.toLowerCase(ch1) != Character.toLowerCase(ch2)) break; } if (pindex == 0) return index; } while (pindex > 0); index += this.shiftTable[ch % this.shiftTable.length]+1; if (index < nindex) index = nindex; } return -1; } int matchesIgnoreCase(char[] chars, int start, int limit) { int plength = this.pattern.length; if (plength == 0) return start; int index = start+plength; while (index <= limit) { int pindex = plength; int nindex = index+1; char ch; do { char ch1 = ch = chars[--index]; char ch2 = this.pattern[--pindex]; if (ch1 != ch2) { ch1 = Character.toUpperCase(ch1); ch2 = Character.toUpperCase(ch2); if (ch1 != ch2 && Character.toLowerCase(ch1) != Character.toLowerCase(ch2)) break; } if (pindex == 0) return index; } while (pindex > 0); index += this.shiftTable[ch % this.shiftTable.length]+1; if (index < nindex) index = nindex; } return -1; } /* public static void main(String[] argv) { try { int[] shiftTable = new int[256]; initializeBoyerMoore(argv[0], shiftTable, true); int o = -1; CharacterIterator ite = new java.text.StringCharacterIterator(argv[1]); long start = System.currentTimeMillis(); //for (int i = 0; i < 10000; i ++) o = searchIgnoreCasesWithBoyerMoore(ite, 0, argv[0], shiftTable); start = System.currentTimeMillis()-start; System.out.println("Result: "+o+", Elapsed: "+start); } catch (Exception ex) { ex.printStackTrace(); } }*/ } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/RegexParser.java0000644000175000017500000012163411361341574025104 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Vector; /** * A Regular Expression Parser. */ class RegexParser { static final int T_CHAR = 0; static final int T_EOF = 1; static final int T_OR = 2; // '|' static final int T_STAR = 3; // '*' static final int T_PLUS = 4; // '+' static final int T_QUESTION = 5; // '?' static final int T_LPAREN = 6; // '(' static final int T_RPAREN = 7; // ')' static final int T_DOT = 8; // '.' static final int T_LBRACKET = 9; // '[' static final int T_BACKSOLIDUS = 10; // '\' static final int T_CARET = 11; // '^' static final int T_DOLLAR = 12; // '$' static final int T_LPAREN2 = 13; // '(?:' static final int T_LOOKAHEAD = 14; // '(?=' static final int T_NEGATIVELOOKAHEAD = 15; // '(?!' static final int T_LOOKBEHIND = 16; // '(?<=' static final int T_NEGATIVELOOKBEHIND = 17; // '(?' static final int T_SET_OPERATIONS = 19; // '(?[' static final int T_POSIX_CHARCLASS_START = 20; // '[:' in a character class static final int T_COMMENT = 21; // '(?#' static final int T_MODIFIERS = 22; // '(?' [\-,a-z,A-Z] static final int T_CONDITION = 23; // '(?(' static final int T_XMLSCHEMA_CC_SUBTRACTION = 24; // '-[' in a character class static class ReferencePosition { int refNumber; int position; ReferencePosition(int n, int pos) { this.refNumber = n; this.position = pos; } } int offset; String regex; int regexlen; int options; ResourceBundle resources; int chardata; int nexttoken; static protected final int S_NORMAL = 0; static protected final int S_INBRACKETS = 1; static protected final int S_INXBRACKETS = 2; int context = S_NORMAL; int parennumber = 1; boolean hasBackReferences; Vector references = null; public RegexParser() { this.setLocale(Locale.getDefault()); } public RegexParser(Locale locale) { this.setLocale(locale); } public void setLocale(Locale locale) { try { this.resources = ResourceBundle.getBundle("org.apache.xmlbeans.impl.regex.message", locale); } catch (MissingResourceException mre) { throw new RuntimeException("Installation Problem??? Couldn't load messages: " +mre.getMessage()); } } final ParseException ex(String key, int loc) { return new ParseException(this.resources.getString(key), loc); } private final boolean isSet(int flag) { return (this.options & flag) == flag; } synchronized Token parse(String regex, int options) throws ParseException { this.options = options; this.offset = 0; this.setContext(S_NORMAL); this.parennumber = 1; this.hasBackReferences = false; this.regex = regex; if (this.isSet(RegularExpression.EXTENDED_COMMENT)) this.regex = REUtil.stripExtendedComment(this.regex); this.regexlen = this.regex.length(); this.next(); Token ret = this.parseRegex(); if (this.offset != this.regexlen) throw ex("parser.parse.1", this.offset); if (this.references != null) { for (int i = 0; i < this.references.size(); i ++) { ReferencePosition position = (ReferencePosition)this.references.elementAt(i); if (this.parennumber <= position.refNumber) throw ex("parser.parse.2", position.position); } this.references.removeAllElements(); } return ret; } /* public RegularExpression createRegex(String regex, int options) throws ParseException { Token tok = this.parse(regex, options); return new RegularExpression(regex, tok, this.parennumber, this.hasBackReferences, options); } */ protected final void setContext(int con) { this.context = con; } final int read() { return this.nexttoken; } final void next() { if (this.offset >= this.regexlen) { this.chardata = -1; this.nexttoken = T_EOF; return; } int ret; int ch = this.regex.charAt(this.offset++); this.chardata = ch; if (this.context == S_INBRACKETS) { // In a character class, this.chardata has one character, that is to say, // a pair of surrogates is composed and stored to this.chardata. switch (ch) { case '\\': ret = T_BACKSOLIDUS; if (this.offset >= this.regexlen) throw ex("parser.next.1", this.offset-1); this.chardata = this.regex.charAt(this.offset++); break; case '-': if (this.isSet(RegularExpression.XMLSCHEMA_MODE) && this.offset < this.regexlen && this.regex.charAt(this.offset) == '[') { this.offset++; ret = T_XMLSCHEMA_CC_SUBTRACTION; } else ret = T_CHAR; break; case '[': if (!this.isSet(RegularExpression.XMLSCHEMA_MODE) && this.offset < this.regexlen && this.regex.charAt(this.offset) == ':') { this.offset++; ret = T_POSIX_CHARCLASS_START; break; } // Through down default: if (REUtil.isHighSurrogate(ch) && this.offset < this.regexlen) { int low = this.regex.charAt(this.offset); if (REUtil.isLowSurrogate(low)) { this.chardata = REUtil.composeFromSurrogates(ch, low); this.offset ++; } } ret = T_CHAR; } this.nexttoken = ret; return; } switch (ch) { case '|': ret = T_OR; break; case '*': ret = T_STAR; break; case '+': ret = T_PLUS; break; case '?': ret = T_QUESTION; break; case ')': ret = T_RPAREN; break; case '.': ret = T_DOT; break; case '[': ret = T_LBRACKET; break; case '^': ret = T_CARET; break; case '$': ret = T_DOLLAR; break; case '(': ret = T_LPAREN; if (this.offset >= this.regexlen) break; if (this.regex.charAt(this.offset) != '?') break; if (++this.offset >= this.regexlen) throw ex("parser.next.2", this.offset-1); ch = this.regex.charAt(this.offset++); switch (ch) { case ':': ret = T_LPAREN2; break; case '=': ret = T_LOOKAHEAD; break; case '!': ret = T_NEGATIVELOOKAHEAD; break; case '[': ret = T_SET_OPERATIONS; break; case '>': ret = T_INDEPENDENT; break; case '<': if (this.offset >= this.regexlen) throw ex("parser.next.2", this.offset-3); ch = this.regex.charAt(this.offset++); if (ch == '=') { ret = T_LOOKBEHIND; } else if (ch == '!') { ret = T_NEGATIVELOOKBEHIND; } else throw ex("parser.next.3", this.offset-3); break; case '#': while (this.offset < this.regexlen) { ch = this.regex.charAt(this.offset++); if (ch == ')') break; } if (ch != ')') throw ex("parser.next.4", this.offset-1); ret = T_COMMENT; break; default: if (ch == '-' || 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z') {// Options this.offset --; ret = T_MODIFIERS; break; } else if (ch == '(') { // conditional ret = T_CONDITION; // this.offsets points the next of '('. break; } throw ex("parser.next.2", this.offset-2); } break; case '\\': ret = T_BACKSOLIDUS; if (this.offset >= this.regexlen) throw ex("parser.next.1", this.offset-1); this.chardata = this.regex.charAt(this.offset++); break; default: ret = T_CHAR; } this.nexttoken = ret; } /** * regex ::= term (`|` term)* * term ::= factor+ * factor ::= ('^' | '$' | '\A' | '\Z' | '\z' | '\b' | '\B' | '\<' | '\>' * | atom (('*' | '+' | '?' | minmax ) '?'? )?) * | '(?=' regex ')' | '(?!' regex ')' | '(?<=' regex ')' | '(?<!' regex ')' * atom ::= char | '.' | range | '(' regex ')' | '(?:' regex ')' | '\' [0-9] * | '\w' | '\W' | '\d' | '\D' | '\s' | '\S' | category-block */ Token parseRegex() throws ParseException { Token tok = this.parseTerm(); Token parent = null; while (this.read() == T_OR) { this.next(); // '|' if (parent == null) { parent = Token.createUnion(); parent.addChild(tok); tok = parent; } tok.addChild(this.parseTerm()); } return tok; } /** * term ::= factor+ */ Token parseTerm() throws ParseException { int ch = this.read(); if (ch == T_OR || ch == T_RPAREN || ch == T_EOF) { return Token.createEmpty(); } else { Token tok = this.parseFactor(); Token concat = null; while ((ch = this.read()) != T_OR && ch != T_RPAREN && ch != T_EOF) { if (concat == null) { concat = Token.createConcat(); concat.addChild(tok); tok = concat; } concat.addChild(this.parseFactor()); //tok = Token.createConcat(tok, this.parseFactor()); } return tok; } } // ---------------------------------------------------------------- Token processCaret() throws ParseException { this.next(); return Token.token_linebeginning; } Token processDollar() throws ParseException { this.next(); return Token.token_lineend; } Token processLookahead() throws ParseException { this.next(); Token tok = Token.createLook(Token.LOOKAHEAD, this.parseRegex()); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // ')' return tok; } Token processNegativelookahead() throws ParseException { this.next(); Token tok = Token.createLook(Token.NEGATIVELOOKAHEAD, this.parseRegex()); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // ')' return tok; } Token processLookbehind() throws ParseException { this.next(); Token tok = Token.createLook(Token.LOOKBEHIND, this.parseRegex()); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // ')' return tok; } Token processNegativelookbehind() throws ParseException { this.next(); Token tok = Token.createLook(Token.NEGATIVELOOKBEHIND, this.parseRegex()); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // ')' return tok; } Token processBacksolidus_A() throws ParseException { this.next(); return Token.token_stringbeginning; } Token processBacksolidus_Z() throws ParseException { this.next(); return Token.token_stringend2; } Token processBacksolidus_z() throws ParseException { this.next(); return Token.token_stringend; } Token processBacksolidus_b() throws ParseException { this.next(); return Token.token_wordedge; } Token processBacksolidus_B() throws ParseException { this.next(); return Token.token_not_wordedge; } Token processBacksolidus_lt() throws ParseException { this.next(); return Token.token_wordbeginning; } Token processBacksolidus_gt() throws ParseException { this.next(); return Token.token_wordend; } Token processStar(Token tok) throws ParseException { this.next(); if (this.read() == T_QUESTION) { this.next(); return Token.createNGClosure(tok); } else return Token.createClosure(tok); } Token processPlus(Token tok) throws ParseException { // X+ -> XX* this.next(); if (this.read() == T_QUESTION) { this.next(); return Token.createConcat(tok, Token.createNGClosure(tok)); } else return Token.createConcat(tok, Token.createClosure(tok)); } Token processQuestion(Token tok) throws ParseException { // X? -> X| this.next(); Token par = Token.createUnion(); if (this.read() == T_QUESTION) { this.next(); par.addChild(Token.createEmpty()); par.addChild(tok); } else { par.addChild(tok); par.addChild(Token.createEmpty()); } return par; } boolean checkQuestion(int off) { return off < this.regexlen && this.regex.charAt(off) == '?'; } Token processParen() throws ParseException { this.next(); int p = this.parennumber++; Token tok = Token.createParen(this.parseRegex(), p); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // Skips ')' return tok; } Token processParen2() throws ParseException { this.next(); Token tok = Token.createParen(this.parseRegex(), 0); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // Skips ')' return tok; } Token processCondition() throws ParseException { // this.offset points the next of '(' if (this.offset+1 >= this.regexlen) throw ex("parser.factor.4", this.offset); // Parses a condition. int refno = -1; Token condition = null; int ch = this.regex.charAt(this.offset); if ('1' <= ch && ch <= '9') { refno = ch-'0'; this.hasBackReferences = true; if (this.references == null) this.references = new Vector(); this.references.addElement(new ReferencePosition(refno, this.offset)); this.offset ++; if (this.regex.charAt(this.offset) != ')') throw ex("parser.factor.1", this.offset); this.offset ++; } else { if (ch == '?') this.offset --; // Points '('. this.next(); condition = this.parseFactor(); switch (condition.type) { case Token.LOOKAHEAD: case Token.NEGATIVELOOKAHEAD: case Token.LOOKBEHIND: case Token.NEGATIVELOOKBEHIND: break; case Token.ANCHOR: if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); break; default: throw ex("parser.factor.5", this.offset); } } // Parses yes/no-patterns. this.next(); Token yesPattern = this.parseRegex(); Token noPattern = null; if (yesPattern.type == Token.UNION) { if (yesPattern.size() != 2) throw ex("parser.factor.6", this.offset); noPattern = yesPattern.getChild(1); yesPattern = yesPattern.getChild(0); } if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); return Token.createCondition(refno, condition, yesPattern, noPattern); } Token processModifiers() throws ParseException { // this.offset points the next of '?'. // modifiers ::= [imsw]* ('-' [imsw]*)? ':' int add = 0, mask = 0, ch = -1; while (this.offset < this.regexlen) { ch = this.regex.charAt(this.offset); int v = REUtil.getOptionValue(ch); if (v == 0) break; // '-' or ':'? add |= v; this.offset ++; } if (this.offset >= this.regexlen) throw ex("parser.factor.2", this.offset-1); if (ch == '-') { this.offset ++; while (this.offset < this.regexlen) { ch = this.regex.charAt(this.offset); int v = REUtil.getOptionValue(ch); if (v == 0) break; // ':'? mask |= v; this.offset ++; } if (this.offset >= this.regexlen) throw ex("parser.factor.2", this.offset-1); } Token tok; if (ch == ':') { this.offset ++; this.next(); tok = Token.createModifierGroup(this.parseRegex(), add, mask); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); } else if (ch == ')') { // such as (?-i) this.offset ++; this.next(); tok = Token.createModifierGroup(this.parseRegex(), add, mask); } else throw ex("parser.factor.3", this.offset); return tok; } Token processIndependent() throws ParseException { this.next(); Token tok = Token.createLook(Token.INDEPENDENT, this.parseRegex()); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // Skips ')' return tok; } Token processBacksolidus_c() throws ParseException { int ch2; // Must be in 0x0040-0x005f if (this.offset >= this.regexlen || ((ch2 = this.regex.charAt(this.offset++)) & 0xffe0) != 0x0040) throw ex("parser.atom.1", this.offset-1); this.next(); return Token.createChar(ch2-0x40); } Token processBacksolidus_C() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_i() throws ParseException { Token tok = Token.createChar('i'); this.next(); return tok; } Token processBacksolidus_I() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_g() throws ParseException { this.next(); return Token.getGraphemePattern(); } Token processBacksolidus_X() throws ParseException { this.next(); return Token.getCombiningCharacterSequence(); } Token processBackreference() throws ParseException { int refnum = this.chardata-'0'; Token tok = Token.createBackReference(refnum); this.hasBackReferences = true; if (this.references == null) this.references = new Vector(); this.references.addElement(new ReferencePosition(refnum, this.offset-2)); this.next(); return tok; } // ---------------------------------------------------------------- /** * factor ::= ('^' | '$' | '\A' | '\Z' | '\z' | '\b' | '\B' | '\<' | '\>' * | atom (('*' | '+' | '?' | minmax ) '?'? )?) * | '(?=' regex ')' | '(?!' regex ')' | '(?<=' regex ')' | '(?<!' regex ')' * | '(?#' [^)]* ')' * minmax ::= '{' min (',' max?)? '}' * min ::= [0-9]+ * max ::= [0-9]+ */ Token parseFactor() throws ParseException { int ch = this.read(); Token tok; switch (ch) { case T_CARET: return this.processCaret(); case T_DOLLAR: return this.processDollar(); case T_LOOKAHEAD: return this.processLookahead(); case T_NEGATIVELOOKAHEAD: return this.processNegativelookahead(); case T_LOOKBEHIND: return this.processLookbehind(); case T_NEGATIVELOOKBEHIND: return this.processNegativelookbehind(); case T_COMMENT: this.next(); return Token.createEmpty(); case T_BACKSOLIDUS: switch (this.chardata) { case 'A': return this.processBacksolidus_A(); case 'Z': return this.processBacksolidus_Z(); case 'z': return this.processBacksolidus_z(); case 'b': return this.processBacksolidus_b(); case 'B': return this.processBacksolidus_B(); case '<': return this.processBacksolidus_lt(); case '>': return this.processBacksolidus_gt(); } // through down } tok = this.parseAtom(); ch = this.read(); switch (ch) { case T_STAR: return this.processStar(tok); case T_PLUS: return this.processPlus(tok); case T_QUESTION: return this.processQuestion(tok); case T_CHAR: if (this.chardata == '{' && this.offset < this.regexlen) { int off = this.offset; // this.offset -> next of '{' int min = 0, max = -1; if ((ch = this.regex.charAt(off++)) >= '0' && ch <= '9') { min = ch -'0'; while (off < this.regexlen && (ch = this.regex.charAt(off++)) >= '0' && ch <= '9') { min = min*10 +ch-'0'; if (min < 0) throw ex("parser.quantifier.5", this.offset); } } else { throw ex("parser.quantifier.1", this.offset); } max = min; if (ch == ',') { if (off >= this.regexlen) { throw ex("parser.quantifier.3", this.offset); } else if ((ch = this.regex.charAt(off++)) >= '0' && ch <= '9') { max = ch -'0'; // {min,max} while (off < this.regexlen && (ch = this.regex.charAt(off++)) >= '0' && ch <= '9') { max = max*10 +ch-'0'; if (max < 0) throw ex("parser.quantifier.5", this.offset); } if (min > max) throw ex("parser.quantifier.4", this.offset); } else { // assume {min,} max = -1; } } if (ch != '}') throw ex("parser.quantifier.2", this.offset); if (this.checkQuestion(off)) { // off -> next of '}' tok = Token.createNGClosure(tok); this.offset = off+1; } else { tok = Token.createClosure(tok); this.offset = off; } tok.setMin(min); tok.setMax(max); //System.err.println("CLOSURE: "+min+", "+max); this.next(); } } return tok; } /** * atom ::= char | '.' | char-class | '(' regex ')' | '(?:' regex ')' | '\' [0-9] * | '\w' | '\W' | '\d' | '\D' | '\s' | '\S' | category-block * | '(?>' regex ')' * char ::= '\\' | '\' [efnrt] | bmp-code | character-1 */ Token parseAtom() throws ParseException { int ch = this.read(); Token tok = null; switch (ch) { case T_LPAREN: return this.processParen(); case T_LPAREN2: return this.processParen2(); // '(?:' case T_CONDITION: return this.processCondition(); // '(?(' case T_MODIFIERS: return this.processModifiers(); // (?modifiers ... ) case T_INDEPENDENT: return this.processIndependent(); case T_DOT: this.next(); // Skips '.' tok = Token.token_dot; break; /** * char-class ::= '[' ( '^'? range ','?)+ ']' * range ::= '\d' | '\w' | '\s' | category-block | range-char * | range-char '-' range-char * range-char ::= '\[' | '\]' | '\\' | '\' [,-efnrtv] | bmp-code | character-2 * bmp-char ::= '\' 'u' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] */ case T_LBRACKET: return this.parseCharacterClass(true); case T_SET_OPERATIONS: return this.parseSetOperations(); case T_BACKSOLIDUS: switch (this.chardata) { case 'd': case 'D': case 'w': case 'W': case 's': case 'S': tok = this.getTokenForShorthand(this.chardata); this.next(); return tok; case 'e': case 'f': case 'n': case 'r': case 't': case 'u': case 'v': case 'x': { int ch2 = this.decodeEscaped(); if (ch2 < 0x10000) { tok = Token.createChar(ch2); } else { tok = Token.createString(REUtil.decomposeToSurrogates(ch2)); } } break; case 'c': return this.processBacksolidus_c(); case 'C': return this.processBacksolidus_C(); case 'i': return this.processBacksolidus_i(); case 'I': return this.processBacksolidus_I(); case 'g': return this.processBacksolidus_g(); case 'X': return this.processBacksolidus_X(); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return this.processBackreference(); case 'P': case 'p': int pstart = this.offset; tok = processBacksolidus_pP(this.chardata); if (tok == null) throw this.ex("parser.atom.5", pstart); break; default: tok = Token.createChar(this.chardata); } this.next(); break; case T_CHAR: if (this.chardata == ']' || this.chardata == '{' || this.chardata == '}') throw this.ex("parser.atom.4", this.offset-1); tok = Token.createChar(this.chardata); int high = this.chardata; this.next(); if (REUtil.isHighSurrogate(high) && this.read() == T_CHAR && REUtil.isLowSurrogate(this.chardata)) { char[] sur = new char[2]; sur[0] = (char)high; sur[1] = (char)this.chardata; tok = Token.createParen(Token.createString(new String(sur)), 0); this.next(); } break; default: throw this.ex("parser.atom.4", this.offset-1); } return tok; } protected RangeToken processBacksolidus_pP(int c) throws ParseException { this.next(); if (this.read() != T_CHAR || this.chardata != '{') throw this.ex("parser.atom.2", this.offset-1); // handle category escape boolean positive = c == 'p'; int namestart = this.offset; int nameend = this.regex.indexOf('}', namestart); if (nameend < 0) throw this.ex("parser.atom.3", this.offset); String pname = this.regex.substring(namestart, nameend); this.offset = nameend+1; return Token.getRange(pname, positive, this.isSet(RegularExpression.XMLSCHEMA_MODE)); } int processCIinCharacterClass(RangeToken tok, int c) { return this.decodeEscaped(); } /** * char-class ::= '[' ( '^'? range ','?)+ ']' * range ::= '\d' | '\w' | '\s' | category-block | range-char * | range-char '-' range-char * range-char ::= '\[' | '\]' | '\\' | '\' [,-efnrtv] | bmp-code | character-2 * bmp-code ::= '\' 'u' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] */ protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException { this.setContext(S_INBRACKETS); this.next(); // '[' boolean nrange = false; RangeToken base = null; RangeToken tok; if (this.read() == T_CHAR && this.chardata == '^') { nrange = true; this.next(); // '^' if (useNrange) { tok = Token.createNRange(); } else { base = Token.createRange(); base.addRange(0, Token.UTF16_MAX); tok = Token.createRange(); } } else { tok = Token.createRange(); } int type; boolean firstloop = true; while ((type = this.read()) != T_EOF) { if (type == T_CHAR && this.chardata == ']' && !firstloop) break; firstloop = false; int c = this.chardata; boolean end = false; if (type == T_BACKSOLIDUS) { switch (c) { case 'd': case 'D': case 'w': case 'W': case 's': case 'S': tok.mergeRanges(this.getTokenForShorthand(c)); end = true; break; case 'i': case 'I': case 'c': case 'C': c = this.processCIinCharacterClass(tok, c); if (c < 0) end = true; break; case 'p': case 'P': int pstart = this.offset; RangeToken tok2 = this.processBacksolidus_pP(c); if (tok2 == null) throw this.ex("parser.atom.5", pstart); tok.mergeRanges(tok2); end = true; break; default: c = this.decodeEscaped(); } // \ + c } // backsolidus // POSIX Character class such as [:alnum:] else if (type == T_POSIX_CHARCLASS_START) { int nameend = this.regex.indexOf(':', this.offset); if (nameend < 0) throw this.ex("parser.cc.1", this.offset); boolean positive = true; if (this.regex.charAt(this.offset) == '^') { this.offset ++; positive = false; } String name = this.regex.substring(this.offset, nameend); RangeToken range = Token.getRange(name, positive, this.isSet(RegularExpression.XMLSCHEMA_MODE)); if (range == null) throw this.ex("parser.cc.3", this.offset); tok.mergeRanges(range); end = true; if (nameend+1 >= this.regexlen || this.regex.charAt(nameend+1) != ']') throw this.ex("parser.cc.1", nameend); this.offset = nameend+2; } this.next(); if (!end) { // if not shorthands... if (this.read() != T_CHAR || this.chardata != '-') { // Here is no '-'. tok.addRange(c, c); } else { this.next(); // Skips '-' if ((type = this.read()) == T_EOF) throw this.ex("parser.cc.2", this.offset); if (type == T_CHAR && this.chardata == ']') { tok.addRange(c, c); tok.addRange('-', '-'); } else { int rangeend = this.chardata; if (type == T_BACKSOLIDUS) rangeend = this.decodeEscaped(); this.next(); tok.addRange(c, rangeend); } } } if (this.isSet(RegularExpression.SPECIAL_COMMA) && this.read() == T_CHAR && this.chardata == ',') this.next(); } if (this.read() == T_EOF) throw this.ex("parser.cc.2", this.offset); if (!useNrange && nrange) { base.subtractRanges(tok); tok = base; } tok.sortRanges(); tok.compactRanges(); //tok.dumpRanges(); /* if (this.isSet(RegularExpression.IGNORE_CASE)) tok = RangeToken.createCaseInsensitiveToken(tok); */ this.setContext(S_NORMAL); this.next(); // Skips ']' return tok; } /** * '(?[' ... ']' (('-' | '+' | '&') '[' ... ']')? ')' */ protected RangeToken parseSetOperations() throws ParseException { RangeToken tok = this.parseCharacterClass(false); int type; while ((type = this.read()) != T_RPAREN) { int ch = this.chardata; if (type == T_CHAR && (ch == '-' || ch == '&') || type == T_PLUS) { this.next(); if (this.read() != T_LBRACKET) throw ex("parser.ope.1", this.offset-1); RangeToken t2 = this.parseCharacterClass(false); if (type == T_PLUS) tok.mergeRanges(t2); else if (ch == '-') tok.subtractRanges(t2); else if (ch == '&') tok.intersectRanges(t2); else throw new RuntimeException("ASSERT"); } else { throw ex("parser.ope.2", this.offset-1); } } this.next(); return tok; } Token getTokenForShorthand(int ch) { Token tok; switch (ch) { case 'd': tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY) ? Token.getRange("Nd", true) : Token.token_0to9; break; case 'D': tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY) ? Token.getRange("Nd", false) : Token.token_not_0to9; break; case 'w': tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY) ? Token.getRange("IsWord", true) : Token.token_wordchars; break; case 'W': tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY) ? Token.getRange("IsWord", false) : Token.token_not_wordchars; break; case 's': tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY) ? Token.getRange("IsSpace", true) : Token.token_spaces; break; case 'S': tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY) ? Token.getRange("IsSpace", false) : Token.token_not_spaces; break; default: throw new RuntimeException("Internal Error: shorthands: \\u"+Integer.toString(ch, 16)); } return tok; } /** */ int decodeEscaped() throws ParseException { if (this.read() != T_BACKSOLIDUS) throw ex("parser.next.1", this.offset-1); int c = this.chardata; switch (c) { case 'e': c = 0x1b; break; // ESCAPE U+001B case 'f': c = '\f'; break; // FORM FEED U+000C case 'n': c = '\n'; break; // LINE FEED U+000A case 'r': c = '\r'; break; // CRRIAGE RETURN U+000D case 't': c = '\t'; break; // HORIZONTAL TABULATION U+0009 //case 'v': c = 0x0b; break; // VERTICAL TABULATION U+000B case 'x': this.next(); if (this.read() != T_CHAR) throw ex("parser.descape.1", this.offset-1); if (this.chardata == '{') { int v1 = 0; int uv = 0; do { this.next(); if (this.read() != T_CHAR) throw ex("parser.descape.1", this.offset-1); if ((v1 = hexChar(this.chardata)) < 0) break; if (uv > uv*16) throw ex("parser.descape.2", this.offset-1); uv = uv*16+v1; } while (true); if (this.chardata != '}') throw ex("parser.descape.3", this.offset-1); if (uv > Token.UTF16_MAX) throw ex("parser.descape.4", this.offset-1); c = uv; } else { int v1 = 0; if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); int uv = v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; c = uv; } break; case 'u': int v1 = 0; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); int uv = v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; c = uv; break; case 'v': this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; this.next(); if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0) throw ex("parser.descape.1", this.offset-1); uv = uv*16+v1; if (uv > Token.UTF16_MAX) throw ex("parser.descappe.4", this.offset-1); c = uv; break; case 'A': case 'Z': case 'z': throw ex("parser.descape.5", this.offset-2); default: } return c; } static private final int hexChar(int ch) { if (ch < '0') return -1; if (ch > 'f') return -1; if (ch <= '9') return ch-'0'; if (ch < 'A') return -1; if (ch <= 'F') return ch-'A'+10; if (ch < 'a') return -1; return ch-'a'+10; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/Token.java0000644000175000017500000016155011361341574023736 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Vector; import java.util.Hashtable; /** * This class represents a node in parse tree. */ class Token implements java.io.Serializable { static final boolean COUNTTOKENS = true; static int tokens = 0; static final int CHAR = 0; // Literal char static final int DOT = 11; // . static final int CONCAT = 1; // XY static final int UNION = 2; // X|Y|Z static final int CLOSURE = 3; // X* static final int RANGE = 4; // [a-zA-Z] etc. static final int NRANGE = 5; // [^a-zA-Z] etc. static final int PAREN = 6; // (X) or (?:X) static final int EMPTY = 7; // static final int ANCHOR = 8; // ^ $ \b \B \< \> \A \Z \z static final int NONGREEDYCLOSURE = 9; // *? +? static final int STRING = 10; // strings static final int BACKREFERENCE = 12; // back references static final int LOOKAHEAD = 20; // (?=...) static final int NEGATIVELOOKAHEAD = 21; // (?!...) static final int LOOKBEHIND = 22; // (?<=...) static final int NEGATIVELOOKBEHIND = 23; // (?...) static final int MODIFIERGROUP = 25; // (?ims-ims:...) static final int CONDITION = 26; // (?(...)yes|no) static final int UTF16_MAX = 0x10ffff; int type; static Token token_dot; static Token token_0to9; static Token token_wordchars; static Token token_not_0to9; static Token token_not_wordchars; static Token token_spaces; static Token token_not_spaces; static Token token_empty; static Token token_linebeginning; static Token token_linebeginning2; static Token token_lineend; static Token token_stringbeginning; static Token token_stringend; static Token token_stringend2; static Token token_wordedge; static Token token_not_wordedge; static Token token_wordbeginning; static Token token_wordend; static { Token.token_empty = new Token(Token.EMPTY); Token.token_linebeginning = Token.createAnchor('^'); Token.token_linebeginning2 = Token.createAnchor('@'); Token.token_lineend = Token.createAnchor('$'); Token.token_stringbeginning = Token.createAnchor('A'); Token.token_stringend = Token.createAnchor('z'); Token.token_stringend2 = Token.createAnchor('Z'); Token.token_wordedge = Token.createAnchor('b'); Token.token_not_wordedge = Token.createAnchor('B'); Token.token_wordbeginning = Token.createAnchor('<'); Token.token_wordend = Token.createAnchor('>'); Token.token_dot = new Token(Token.DOT); Token.token_0to9 = Token.createRange(); Token.token_0to9.addRange('0', '9'); Token.token_wordchars = Token.createRange(); Token.token_wordchars.addRange('0', '9'); Token.token_wordchars.addRange('A', 'Z'); Token.token_wordchars.addRange('_', '_'); Token.token_wordchars.addRange('a', 'z'); Token.token_spaces = Token.createRange(); Token.token_spaces.addRange('\t', '\t'); Token.token_spaces.addRange('\n', '\n'); Token.token_spaces.addRange('\f', '\f'); Token.token_spaces.addRange('\r', '\r'); Token.token_spaces.addRange(' ', ' '); Token.token_not_0to9 = Token.complementRanges(Token.token_0to9); Token.token_not_wordchars = Token.complementRanges(Token.token_wordchars); Token.token_not_spaces = Token.complementRanges(Token.token_spaces); } static Token.ParenToken createLook(int type, Token child) { if (COUNTTOKENS) Token.tokens ++; return new Token.ParenToken(type, child, 0); } static Token.ParenToken createParen(Token child, int pnumber) { if (COUNTTOKENS) Token.tokens ++; return new Token.ParenToken(Token.PAREN, child, pnumber); } static Token.ClosureToken createClosure(Token tok) { if (COUNTTOKENS) Token.tokens ++; return new Token.ClosureToken(Token.CLOSURE, tok); } static Token.ClosureToken createNGClosure(Token tok) { if (COUNTTOKENS) Token.tokens ++; return new Token.ClosureToken(Token.NONGREEDYCLOSURE, tok); } static Token.ConcatToken createConcat(Token tok1, Token tok2) { if (COUNTTOKENS) Token.tokens ++; return new Token.ConcatToken(tok1, tok2); } static Token.UnionToken createConcat() { if (COUNTTOKENS) Token.tokens ++; return new Token.UnionToken(Token.CONCAT); // *** It is not a bug. } static Token.UnionToken createUnion() { if (COUNTTOKENS) Token.tokens ++; return new Token.UnionToken(Token.UNION); } static Token createEmpty() { return Token.token_empty; } static RangeToken createRange() { if (COUNTTOKENS) Token.tokens ++; return new RangeToken(Token.RANGE); } static RangeToken createNRange() { if (COUNTTOKENS) Token.tokens ++; return new RangeToken(Token.NRANGE); } static Token.CharToken createChar(int ch) { if (COUNTTOKENS) Token.tokens ++; return new Token.CharToken(Token.CHAR, ch); } static private Token.CharToken createAnchor(int ch) { if (COUNTTOKENS) Token.tokens ++; return new Token.CharToken(Token.ANCHOR, ch); } static Token.StringToken createBackReference(int refno) { if (COUNTTOKENS) Token.tokens ++; return new Token.StringToken(Token.BACKREFERENCE, null, refno); } static Token.StringToken createString(String str) { if (COUNTTOKENS) Token.tokens ++; return new Token.StringToken(Token.STRING, str, 0); } static Token.ModifierToken createModifierGroup(Token child, int add, int mask) { if (COUNTTOKENS) Token.tokens ++; return new Token.ModifierToken(child, add, mask); } static Token.ConditionToken createCondition(int refno, Token condition, Token yespat, Token nopat) { if (COUNTTOKENS) Token.tokens ++; return new Token.ConditionToken(refno, condition, yespat, nopat); } protected Token(int type) { this.type = type; } /** * A number of children. */ int size() { return 0; } Token getChild(int index) { return null; } void addChild(Token tok) { throw new RuntimeException("Not supported."); } // for RANGE or NRANGE protected void addRange(int start, int end) { throw new RuntimeException("Not supported."); } protected void sortRanges() { throw new RuntimeException("Not supported."); } protected void compactRanges() { throw new RuntimeException("Not supported."); } protected void mergeRanges(Token tok) { throw new RuntimeException("Not supported."); } protected void subtractRanges(Token tok) { throw new RuntimeException("Not supported."); } protected void intersectRanges(Token tok) { throw new RuntimeException("Not supported."); } static Token complementRanges(Token tok) { return RangeToken.complementRanges(tok); } void setMin(int min) { // for CLOSURE } void setMax(int max) { // for CLOSURE } int getMin() { // for CLOSURE return -1; } int getMax() { // for CLOSURE return -1; } int getReferenceNumber() { // for STRING return 0; } String getString() { // for STRING return null; } int getParenNumber() { return 0; } int getChar() { return -1; } public String toString() { return this.toString(0); } public String toString(int options) { return this.type == Token.DOT ? "." : ""; } /** * How many characters are needed? */ final int getMinLength() { switch (this.type) { case CONCAT: int sum = 0; for (int i = 0; i < this.size(); i ++) sum += this.getChild(i).getMinLength(); return sum; case CONDITION: case UNION: if (this.size() == 0) return 0; int ret = this.getChild(0).getMinLength(); for (int i = 1; i < this.size(); i ++) { int min = this.getChild(i).getMinLength(); if (min < ret) ret = min; } return ret; case CLOSURE: case NONGREEDYCLOSURE: if (this.getMin() >= 0) return this.getMin() * this.getChild(0).getMinLength(); return 0; case EMPTY: case ANCHOR: return 0; case DOT: case CHAR: case RANGE: case NRANGE: return 1; case INDEPENDENT: case PAREN: case MODIFIERGROUP: return this.getChild(0).getMinLength(); case BACKREFERENCE: return 0; // ******* case STRING: return this.getString().length(); case LOOKAHEAD: case NEGATIVELOOKAHEAD: case LOOKBEHIND: case NEGATIVELOOKBEHIND: return 0; // ***** Really? default: throw new RuntimeException("Token#getMinLength(): Invalid Type: "+this.type); } } final int getMaxLength() { switch (this.type) { case CONCAT: int sum = 0; for (int i = 0; i < this.size(); i ++) { int d = this.getChild(i).getMaxLength(); if (d < 0) return -1; sum += d; } return sum; case CONDITION: case UNION: if (this.size() == 0) return 0; int ret = this.getChild(0).getMaxLength(); for (int i = 1; ret >= 0 && i < this.size(); i ++) { int max = this.getChild(i).getMaxLength(); if (max < 0) { // infinity ret = -1; break; } if (max > ret) ret = max; } return ret; case CLOSURE: case NONGREEDYCLOSURE: if (this.getMax() >= 0) // When this.child.getMaxLength() < 0, // this returns minus value return this.getMax() * this.getChild(0).getMaxLength(); return -1; case EMPTY: case ANCHOR: return 0; case CHAR: return 1; case DOT: case RANGE: case NRANGE: return 2; case INDEPENDENT: case PAREN: case MODIFIERGROUP: return this.getChild(0).getMaxLength(); case BACKREFERENCE: return -1; // ****** case STRING: return this.getString().length(); case LOOKAHEAD: case NEGATIVELOOKAHEAD: case LOOKBEHIND: case NEGATIVELOOKBEHIND: return 0; // ***** Really? default: throw new RuntimeException("Token#getMaxLength(): Invalid Type: "+this.type); } } static final int FC_CONTINUE = 0; static final int FC_TERMINAL = 1; static final int FC_ANY = 2; private static final boolean isSet(int options, int flag) { return (options & flag) == flag; } final int analyzeFirstCharacter(RangeToken result, int options) { switch (this.type) { case CONCAT: int ret = FC_CONTINUE; for (int i = 0; i < this.size(); i ++) if ((ret = this.getChild(i).analyzeFirstCharacter(result, options)) != FC_CONTINUE) break; return ret; case UNION: if (this.size() == 0) return FC_CONTINUE; /* * a|b|c -> FC_TERMINAL * a|.|c -> FC_ANY * a|b| -> FC_CONTINUE */ int ret2 = FC_CONTINUE; boolean hasEmpty = false; for (int i = 0; i < this.size(); i ++) { ret2 = this.getChild(i).analyzeFirstCharacter(result, options); if (ret2 == FC_ANY) break; else if (ret2 == FC_CONTINUE) hasEmpty = true; } return hasEmpty ? FC_CONTINUE : ret2; case CONDITION: int ret3 = this.getChild(0).analyzeFirstCharacter(result, options); if (this.size() == 1) return FC_CONTINUE; if (ret3 == FC_ANY) return ret3; int ret4 = this.getChild(1).analyzeFirstCharacter(result, options); if (ret4 == FC_ANY) return ret4; return ret3 == FC_CONTINUE || ret4 == FC_CONTINUE ? FC_CONTINUE : FC_TERMINAL; case CLOSURE: case NONGREEDYCLOSURE: this.getChild(0).analyzeFirstCharacter(result, options); return FC_CONTINUE; case EMPTY: case ANCHOR: return FC_CONTINUE; case CHAR: int ch = this.getChar(); result.addRange(ch, ch); if (ch < 0x10000 && isSet(options, RegularExpression.IGNORE_CASE)) { ch = Character.toUpperCase((char)ch); result.addRange(ch, ch); ch = Character.toLowerCase((char)ch); result.addRange(ch, ch); } return FC_TERMINAL; case DOT: // **** if (isSet(options, RegularExpression.SINGLE_LINE)) { return FC_CONTINUE; // **** We can not optimize. } else { return FC_CONTINUE; /* result.addRange(0, RegularExpression.LINE_FEED-1); result.addRange(RegularExpression.LINE_FEED+1, RegularExpression.CARRIAGE_RETURN-1); result.addRange(RegularExpression.CARRIAGE_RETURN+1, RegularExpression.LINE_SEPARATOR-1); result.addRange(RegularExpression.PARAGRAPH_SEPARATOR+1, UTF16_MAX); return 1; */ } case RANGE: if (isSet(options, RegularExpression.IGNORE_CASE)) { result.mergeRanges(((RangeToken)this).getCaseInsensitiveToken()); } else { result.mergeRanges(this); } return FC_TERMINAL; case NRANGE: // **** if (isSet(options, RegularExpression.IGNORE_CASE)) { result.mergeRanges(Token.complementRanges(((RangeToken)this).getCaseInsensitiveToken())); } else { result.mergeRanges(Token.complementRanges(this)); } return FC_TERMINAL; case INDEPENDENT: case PAREN: return this.getChild(0).analyzeFirstCharacter(result, options); case MODIFIERGROUP: options |= ((ModifierToken)this).getOptions(); options &= ~((ModifierToken)this).getOptionsMask(); return this.getChild(0).analyzeFirstCharacter(result, options); case BACKREFERENCE: result.addRange(0, UTF16_MAX); // **** We can not optimize. return FC_ANY; case STRING: int cha = this.getString().charAt(0); int ch2; if (REUtil.isHighSurrogate(cha) && this.getString().length() >= 2 && REUtil.isLowSurrogate((ch2 = this.getString().charAt(1)))) cha = REUtil.composeFromSurrogates(cha, ch2); result.addRange(cha, cha); if (cha < 0x10000 && isSet(options, RegularExpression.IGNORE_CASE)) { cha = Character.toUpperCase((char)cha); result.addRange(cha, cha); cha = Character.toLowerCase((char)cha); result.addRange(cha, cha); } return FC_TERMINAL; case LOOKAHEAD: case NEGATIVELOOKAHEAD: case LOOKBEHIND: case NEGATIVELOOKBEHIND: return FC_CONTINUE; default: throw new RuntimeException("Token#analyzeHeadCharacter(): Invalid Type: "+this.type); } } private final boolean isShorterThan(Token tok) { if (tok == null) return false; /* int mylength; if (this.type == STRING) mylength = this.getString().length(); else if (this.type == CHAR) mylength = this.getChar() >= 0x10000 ? 2 : 1; else throw new RuntimeException("Internal Error: Illegal type: "+this.type); int otherlength; if (tok.type == STRING) otherlength = tok.getString().length(); else if (tok.type == CHAR) otherlength = tok.getChar() >= 0x10000 ? 2 : 1; else throw new RuntimeException("Internal Error: Illegal type: "+tok.type); */ int mylength; if (this.type == STRING) mylength = this.getString().length(); else throw new RuntimeException("Internal Error: Illegal type: "+this.type); int otherlength; if (tok.type == STRING) otherlength = tok.getString().length(); else throw new RuntimeException("Internal Error: Illegal type: "+tok.type); return mylength < otherlength; } static class FixedStringContainer { Token token = null; int options = 0; FixedStringContainer() { } } final void findFixedString(FixedStringContainer container, int options) { switch (this.type) { case CONCAT: Token prevToken = null; int prevOptions = 0; for (int i = 0; i < this.size(); i ++) { this.getChild(i).findFixedString(container, options); if (prevToken == null || prevToken.isShorterThan(container.token)) { prevToken = container.token; prevOptions = container.options; } } container.token = prevToken; container.options = prevOptions; return; case UNION: case CLOSURE: case NONGREEDYCLOSURE: case EMPTY: case ANCHOR: case RANGE: case DOT: case NRANGE: case BACKREFERENCE: case LOOKAHEAD: case NEGATIVELOOKAHEAD: case LOOKBEHIND: case NEGATIVELOOKBEHIND: case CONDITION: container.token = null; return; case CHAR: // Ignore CHAR tokens. container.token = null; // ** return; // ** case STRING: container.token = this; container.options = options; return; case INDEPENDENT: case PAREN: this.getChild(0).findFixedString(container, options); return; case MODIFIERGROUP: options |= ((ModifierToken)this).getOptions(); options &= ~((ModifierToken)this).getOptionsMask(); this.getChild(0).findFixedString(container, options); return; default: throw new RuntimeException("Token#findFixedString(): Invalid Type: "+this.type); } } boolean match(int ch) { throw new RuntimeException("NFAArrow#match(): Internal error: "+this.type); } // ------------------------------------------------------ private final static Hashtable categories = new Hashtable(); private final static Hashtable categories2 = new Hashtable(); private static final String[] categoryNames = { "Cn", "Lu", "Ll", "Lt", "Lm", "Lo", "Mn", "Me", "Mc", "Nd", "Nl", "No", "Zs", "Zl", "Zp", "Cc", "Cf", null, "Co", "Cs", "Pd", "Ps", "Pe", "Pc", "Po", "Sm", "Sc", "Sk", "So", // 28 "Pi", "Pf", // 29, 30 "L", "M", "N", "Z", "C", "P", "S", // 31-37 }; // Schema Rec. {Datatypes} - Punctuation static final int CHAR_INIT_QUOTE = 29; // Pi - initial quote static final int CHAR_FINAL_QUOTE = 30; // Pf - final quote static final int CHAR_LETTER = 31; static final int CHAR_MARK = 32; static final int CHAR_NUMBER = 33; static final int CHAR_SEPARATOR = 34; static final int CHAR_OTHER = 35; static final int CHAR_PUNCTUATION = 36; static final int CHAR_SYMBOL = 37; //blockNames in UNICODE 3.1 that supported by XML Schema REC private static final String[] blockNames = { /*0000..007F;*/ "Basic Latin", /*0080..00FF;*/ "Latin-1 Supplement", /*0100..017F;*/ "Latin Extended-A", /*0180..024F;*/ "Latin Extended-B", /*0250..02AF;*/ "IPA Extensions", /*02B0..02FF;*/ "Spacing Modifier Letters", /*0300..036F;*/ "Combining Diacritical Marks", /*0370..03FF;*/ "Greek", /*0400..04FF;*/ "Cyrillic", /*0530..058F;*/ "Armenian", /*0590..05FF;*/ "Hebrew", /*0600..06FF;*/ "Arabic", /*0700..074F;*/ "Syriac", /*0780..07BF;*/ "Thaana", /*0900..097F;*/ "Devanagari", /*0980..09FF;*/ "Bengali", /*0A00..0A7F;*/ "Gurmukhi", /*0A80..0AFF;*/ "Gujarati", /*0B00..0B7F;*/ "Oriya", /*0B80..0BFF;*/ "Tamil", /*0C00..0C7F;*/ "Telugu", /*0C80..0CFF;*/ "Kannada", /*0D00..0D7F;*/ "Malayalam", /*0D80..0DFF;*/ "Sinhala", /*0E00..0E7F;*/ "Thai", /*0E80..0EFF;*/ "Lao", /*0F00..0FFF;*/ "Tibetan", /*1000..109F;*/ "Myanmar", /*10A0..10FF;*/ "Georgian", /*1100..11FF;*/ "Hangul Jamo", /*1200..137F;*/ "Ethiopic", /*13A0..13FF;*/ "Cherokee", /*1400..167F;*/ "Unified Canadian Aboriginal Syllabics", /*1680..169F;*/ "Ogham", /*16A0..16FF;*/ "Runic", /*1780..17FF;*/ "Khmer", /*1800..18AF;*/ "Mongolian", /*1E00..1EFF;*/ "Latin Extended Additional", /*1F00..1FFF;*/ "Greek Extended", /*2000..206F;*/ "General Punctuation", /*2070..209F;*/ "Superscripts and Subscripts", /*20A0..20CF;*/ "Currency Symbols", /*20D0..20FF;*/ "Combining Marks for Symbols", /*2100..214F;*/ "Letterlike Symbols", /*2150..218F;*/ "Number Forms", /*2190..21FF;*/ "Arrows", /*2200..22FF;*/ "Mathematical Operators", /*2300..23FF;*/ "Miscellaneous Technical", /*2400..243F;*/ "Control Pictures", /*2440..245F;*/ "Optical Character Recognition", /*2460..24FF;*/ "Enclosed Alphanumerics", /*2500..257F;*/ "Box Drawing", /*2580..259F;*/ "Block Elements", /*25A0..25FF;*/ "Geometric Shapes", /*2600..26FF;*/ "Miscellaneous Symbols", /*2700..27BF;*/ "Dingbats", /*2800..28FF;*/ "Braille Patterns", /*2E80..2EFF;*/ "CJK Radicals Supplement", /*2F00..2FDF;*/ "Kangxi Radicals", /*2FF0..2FFF;*/ "Ideographic Description Characters", /*3000..303F;*/ "CJK Symbols and Punctuation", /*3040..309F;*/ "Hiragana", /*30A0..30FF;*/ "Katakana", /*3100..312F;*/ "Bopomofo", /*3130..318F;*/ "Hangul Compatibility Jamo", /*3190..319F;*/ "Kanbun", /*31A0..31BF;*/ "Bopomofo Extended", /*3200..32FF;*/ "Enclosed CJK Letters and Months", /*3300..33FF;*/ "CJK Compatibility", /*3400..4DB5;*/ "CJK Unified Ideographs Extension A", /*4E00..9FFF;*/ "CJK Unified Ideographs", /*A000..A48F;*/ "Yi Syllables", /*A490..A4CF;*/ "Yi Radicals", /*AC00..D7A3;*/ "Hangul Syllables", /*E000..F8FF;*/ "Private Use", /*F900..FAFF;*/ "CJK Compatibility Ideographs", /*FB00..FB4F;*/ "Alphabetic Presentation Forms", /*FB50..FDFF;*/ "Arabic Presentation Forms-A", /*FE20..FE2F;*/ "Combining Half Marks", /*FE30..FE4F;*/ "CJK Compatibility Forms", /*FE50..FE6F;*/ "Small Form Variants", /*FE70..FEFE;*/ "Arabic Presentation Forms-B", /*FEFF..FEFF;*/ "Specials", /*FF00..FFEF;*/ "Halfwidth and Fullwidth Forms", //missing Specials add manually /*10300..1032F;*/ "Old Italic", // 84 /*10330..1034F;*/ "Gothic", /*10400..1044F;*/ "Deseret", /*1D000..1D0FF;*/ "Byzantine Musical Symbols", /*1D100..1D1FF;*/ "Musical Symbols", /*1D400..1D7FF;*/ "Mathematical Alphanumeric Symbols", /*20000..2A6D6;*/ "CJK Unified Ideographs Extension B", /*2F800..2FA1F;*/ "CJK Compatibility Ideographs Supplement", /*E0000..E007F;*/ "Tags", //missing 2 private use add manually }; //ADD THOSE MANUALLY //F0000..FFFFD; "Private Use", //100000..10FFFD; "Private Use" //FFF0..FFFD; "Specials", static final String blockRanges = "\u0000\u007F\u0080\u00FF\u0100\u017F\u0180\u024F\u0250\u02AF\u02B0\u02FF\u0300\u036F" +"\u0370\u03FF\u0400\u04FF\u0530\u058F\u0590\u05FF\u0600\u06FF\u0700\u074F\u0780\u07BF" +"\u0900\u097F\u0980\u09FF\u0A00\u0A7F\u0A80\u0AFF\u0B00\u0B7F\u0B80\u0BFF\u0C00\u0C7F\u0C80\u0CFF" +"\u0D00\u0D7F\u0D80\u0DFF\u0E00\u0E7F\u0E80\u0EFF\u0F00\u0FFF\u1000\u109F\u10A0\u10FF\u1100\u11FF" +"\u1200\u137F\u13A0\u13FF\u1400\u167F\u1680\u169F\u16A0\u16FF\u1780\u17FF\u1800\u18AF\u1E00\u1EFF" +"\u1F00\u1FFF\u2000\u206F\u2070\u209F\u20A0\u20CF\u20D0\u20FF\u2100\u214F\u2150\u218F\u2190\u21FF\u2200\u22FF" +"\u2300\u23FF\u2400\u243F\u2440\u245F\u2460\u24FF\u2500\u257F\u2580\u259F\u25A0\u25FF\u2600\u26FF\u2700\u27BF" +"\u2800\u28FF\u2E80\u2EFF\u2F00\u2FDF\u2FF0\u2FFF\u3000\u303F\u3040\u309F\u30A0\u30FF\u3100\u312F\u3130\u318F" +"\u3190\u319F\u31A0\u31BF\u3200\u32FF\u3300\u33FF\u3400\u4DB5\u4E00\u9FFF\uA000\uA48F\uA490\uA4CF" +"\uAC00\uD7A3\uE000\uF8FF\uF900\uFAFF\uFB00\uFB4F\uFB50\uFDFF" +"\uFE20\uFE2F\uFE30\uFE4F\uFE50\uFE6F\uFE70\uFEFE\uFEFF\uFEFF\uFF00\uFFEF"; static final int[] nonBMPBlockRanges = { 0x10300, 0x1032F, // 84 0x10330, 0x1034F, 0x10400, 0x1044F, 0x1D000, 0x1D0FF, 0x1D100, 0x1D1FF, 0x1D400, 0x1D7FF, 0x20000, 0x2A6D6, 0x2F800, 0x2FA1F, 0xE0000, 0xE007F }; private static final int NONBMP_BLOCK_START = 84; static protected RangeToken getRange(String name, boolean positive) { if (Token.categories.size() == 0) { synchronized (Token.categories) { Token[] ranges = new Token[Token.categoryNames.length]; for (int i = 0; i < ranges.length; i ++) { ranges[i] = Token.createRange(); } int type; for (int i = 0; i < 0x10000; i ++) { type = Character.getType((char)i); if (type == Character.START_PUNCTUATION || type == Character.END_PUNCTUATION) { //build table of Pi values if (i == 0x00AB || i == 0x2018 || i == 0x201B || i == 0x201C || i == 0x201F || i == 0x2039) { type = CHAR_INIT_QUOTE; } //build table of Pf values if (i == 0x00BB || i == 0x2019 || i == 0x201D || i == 0x203A ) { type = CHAR_FINAL_QUOTE; } } ranges[type].addRange(i, i); switch (type) { case Character.UPPERCASE_LETTER: case Character.LOWERCASE_LETTER: case Character.TITLECASE_LETTER: case Character.MODIFIER_LETTER: case Character.OTHER_LETTER: type = CHAR_LETTER; break; case Character.NON_SPACING_MARK: case Character.COMBINING_SPACING_MARK: case Character.ENCLOSING_MARK: type = CHAR_MARK; break; case Character.DECIMAL_DIGIT_NUMBER: case Character.LETTER_NUMBER: case Character.OTHER_NUMBER: type = CHAR_NUMBER; break; case Character.SPACE_SEPARATOR: case Character.LINE_SEPARATOR: case Character.PARAGRAPH_SEPARATOR: type = CHAR_SEPARATOR; break; case Character.CONTROL: case Character.FORMAT: case Character.SURROGATE: case Character.PRIVATE_USE: case Character.UNASSIGNED: type = CHAR_OTHER; break; case Character.CONNECTOR_PUNCTUATION: case Character.DASH_PUNCTUATION: case Character.START_PUNCTUATION: case Character.END_PUNCTUATION: case CHAR_INIT_QUOTE: case CHAR_FINAL_QUOTE: case Character.OTHER_PUNCTUATION: type = CHAR_PUNCTUATION; break; case Character.MATH_SYMBOL: case Character.CURRENCY_SYMBOL: case Character.MODIFIER_SYMBOL: case Character.OTHER_SYMBOL: type = CHAR_SYMBOL; break; default: throw new RuntimeException("org.apache.xerces.utils.regex.Token#getRange(): Unknown Unicode category: "+type); } ranges[type].addRange(i, i); } // for all characters ranges[Character.UNASSIGNED].addRange(0x10000, Token.UTF16_MAX); for (int i = 0; i < ranges.length; i ++) { if (Token.categoryNames[i] != null) { if (i == Character.UNASSIGNED) { // Unassigned ranges[i].addRange(0x10000, Token.UTF16_MAX); } Token.categories.put(Token.categoryNames[i], ranges[i]); Token.categories2.put(Token.categoryNames[i], Token.complementRanges(ranges[i])); } } //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); for (int i = 0; i < Token.blockNames.length; i ++) { Token r1 = Token.createRange(); int location; if (i < NONBMP_BLOCK_START) { location = i*2; int rstart = Token.blockRanges.charAt(location); int rend = Token.blockRanges.charAt(location+1); //DEBUGING //System.out.println(n+" " +Integer.toHexString(rstart) // +"-"+ Integer.toHexString(rend)); r1.addRange(rstart, rend); } else { location = (i - NONBMP_BLOCK_START) * 2; r1.addRange(Token.nonBMPBlockRanges[location], Token.nonBMPBlockRanges[location + 1]); } String n = Token.blockNames[i]; if (n.equals("Specials")) r1.addRange(0xfff0, 0xfffd); if (n.equals("Private Use")) { r1.addRange(0xF0000,0xFFFFD); r1.addRange(0x100000,0x10FFFD); } Token.categories.put(n, r1); Token.categories2.put(n, Token.complementRanges(r1)); buffer.setLength(0); buffer.append("Is"); if (n.indexOf(' ') >= 0) { for (int ci = 0; ci < n.length(); ci ++) if (n.charAt(ci) != ' ') buffer.append((char)n.charAt(ci)); } else { buffer.append(n); } Token.setAlias(buffer.toString(), n, true); } // TR#18 1.2 Token.setAlias("ASSIGNED", "Cn", false); Token.setAlias("UNASSIGNED", "Cn", true); Token all = Token.createRange(); all.addRange(0, Token.UTF16_MAX); Token.categories.put("ALL", all); Token.categories2.put("ALL", Token.complementRanges(all)); Token.registerNonXS("ASSIGNED"); Token.registerNonXS("UNASSIGNED"); Token.registerNonXS("ALL"); Token isalpha = Token.createRange(); isalpha.mergeRanges(ranges[Character.UPPERCASE_LETTER]); // Lu isalpha.mergeRanges(ranges[Character.LOWERCASE_LETTER]); // Ll isalpha.mergeRanges(ranges[Character.OTHER_LETTER]); // Lo Token.categories.put("IsAlpha", isalpha); Token.categories2.put("IsAlpha", Token.complementRanges(isalpha)); Token.registerNonXS("IsAlpha"); Token isalnum = Token.createRange(); isalnum.mergeRanges(isalpha); // Lu Ll Lo isalnum.mergeRanges(ranges[Character.DECIMAL_DIGIT_NUMBER]); // Nd Token.categories.put("IsAlnum", isalnum); Token.categories2.put("IsAlnum", Token.complementRanges(isalnum)); Token.registerNonXS("IsAlnum"); Token isspace = Token.createRange(); isspace.mergeRanges(Token.token_spaces); isspace.mergeRanges(ranges[CHAR_SEPARATOR]); // Z Token.categories.put("IsSpace", isspace); Token.categories2.put("IsSpace", Token.complementRanges(isspace)); Token.registerNonXS("IsSpace"); Token isword = Token.createRange(); isword.mergeRanges(isalnum); // Lu Ll Lo Nd isword.addRange('_', '_'); Token.categories.put("IsWord", isword); Token.categories2.put("IsWord", Token.complementRanges(isword)); Token.registerNonXS("IsWord"); Token isascii = Token.createRange(); isascii.addRange(0, 127); Token.categories.put("IsASCII", isascii); Token.categories2.put("IsASCII", Token.complementRanges(isascii)); Token.registerNonXS("IsASCII"); Token isnotgraph = Token.createRange(); isnotgraph.mergeRanges(ranges[CHAR_OTHER]); isnotgraph.addRange(' ', ' '); Token.categories.put("IsGraph", Token.complementRanges(isnotgraph)); Token.categories2.put("IsGraph", isnotgraph); Token.registerNonXS("IsGraph"); Token isxdigit = Token.createRange(); isxdigit.addRange('0', '9'); isxdigit.addRange('A', 'F'); isxdigit.addRange('a', 'f'); Token.categories.put("IsXDigit", Token.complementRanges(isxdigit)); Token.categories2.put("IsXDigit", isxdigit); Token.registerNonXS("IsXDigit"); Token.setAlias("IsDigit", "Nd", true); Token.setAlias("IsUpper", "Lu", true); Token.setAlias("IsLower", "Ll", true); Token.setAlias("IsCntrl", "C", true); Token.setAlias("IsPrint", "C", false); Token.setAlias("IsPunct", "P", true); Token.registerNonXS("IsDigit"); Token.registerNonXS("IsUpper"); Token.registerNonXS("IsLower"); Token.registerNonXS("IsCntrl"); Token.registerNonXS("IsPrint"); Token.registerNonXS("IsPunct"); Token.setAlias("alpha", "IsAlpha", true); Token.setAlias("alnum", "IsAlnum", true); Token.setAlias("ascii", "IsASCII", true); Token.setAlias("cntrl", "IsCntrl", true); Token.setAlias("digit", "IsDigit", true); Token.setAlias("graph", "IsGraph", true); Token.setAlias("lower", "IsLower", true); Token.setAlias("print", "IsPrint", true); Token.setAlias("punct", "IsPunct", true); Token.setAlias("space", "IsSpace", true); Token.setAlias("upper", "IsUpper", true); Token.setAlias("word", "IsWord", true); // Perl extension Token.setAlias("xdigit", "IsXDigit", true); Token.registerNonXS("alpha"); Token.registerNonXS("alnum"); Token.registerNonXS("ascii"); Token.registerNonXS("cntrl"); Token.registerNonXS("digit"); Token.registerNonXS("graph"); Token.registerNonXS("lower"); Token.registerNonXS("print"); Token.registerNonXS("punct"); Token.registerNonXS("space"); Token.registerNonXS("upper"); Token.registerNonXS("word"); Token.registerNonXS("xdigit"); } // synchronized } // if null RangeToken tok = positive ? (RangeToken)Token.categories.get(name) : (RangeToken)Token.categories2.get(name); //if (tok == null) System.out.println(name); return tok; } static protected RangeToken getRange(String name, boolean positive, boolean xs) { RangeToken range = Token.getRange(name, positive); if (xs && range != null && Token.isRegisterNonXS(name)) range = null; return range; } static Hashtable nonxs = null; /** * This method is called by only getRange(). * So this method need not MT-safe. */ static protected void registerNonXS(String name) { if (Token.nonxs == null) Token.nonxs = new Hashtable(); Token.nonxs.put(name, name); } static protected boolean isRegisterNonXS(String name) { if (Token.nonxs == null) return false; //DEBUG //System.err.println("isRegisterNonXS: "+name); return Token.nonxs.containsKey(name); } private static void setAlias(String newName, String name, boolean positive) { Token t1 = (Token)Token.categories.get(name); Token t2 = (Token)Token.categories2.get(name); if (positive) { Token.categories.put(newName, t1); Token.categories2.put(newName, t2); } else { Token.categories2.put(newName, t1); Token.categories.put(newName, t2); } } // ------------------------------------------------------ static final String viramaString = "\u094D"// ;DEVANAGARI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u09CD"//;BENGALI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0A4D"//;GURMUKHI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0ACD"//;GUJARATI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0B4D"//;ORIYA SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0BCD"//;TAMIL SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0C4D"//;TELUGU SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0CCD"//;KANNADA SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0D4D"//;MALAYALAM SIGN VIRAMA;Mn;9;ON;;;;;N;;;;; +"\u0E3A"//;THAI CHARACTER PHINTHU;Mn;9;ON;;;;;N;THAI VOWEL SIGN PHINTHU;;;; +"\u0F84";//;TIBETAN MARK HALANTA;Mn;9;ON;;;;;N;TIBETAN VIRAMA;;;; static private Token token_grapheme = null; static synchronized Token getGraphemePattern() { if (Token.token_grapheme != null) return Token.token_grapheme; Token base_char = Token.createRange(); // [{ASSIGNED}]-[{M},{C}] base_char.mergeRanges(Token.getRange("ASSIGNED", true)); base_char.subtractRanges(Token.getRange("M", true)); base_char.subtractRanges(Token.getRange("C", true)); Token virama = Token.createRange(); for (int i = 0; i < Token.viramaString.length(); i ++) { int ch = viramaString.charAt(i); virama.addRange(i, i); } Token combiner_wo_virama = Token.createRange(); combiner_wo_virama.mergeRanges(Token.getRange("M", true)); combiner_wo_virama.addRange(0x1160, 0x11ff); // hangul_medial and hangul_final combiner_wo_virama.addRange(0xff9e, 0xff9f); // extras Token left = Token.createUnion(); // base_char? left.addChild(base_char); left.addChild(Token.token_empty); Token foo = Token.createUnion(); foo.addChild(Token.createConcat(virama, Token.getRange("L", true))); foo.addChild(combiner_wo_virama); foo = Token.createClosure(foo); foo = Token.createConcat(left, foo); Token.token_grapheme = foo; return Token.token_grapheme; } /** * Combing Character Sequence in Perl 5.6. */ static private Token token_ccs = null; static synchronized Token getCombiningCharacterSequence() { if (Token.token_ccs != null) return Token.token_ccs; Token foo = Token.createClosure(Token.getRange("M", true)); // \pM* foo = Token.createConcat(Token.getRange("M", false), foo); // \PM + \pM* Token.token_ccs = foo; return Token.token_ccs; } // ------------------------------------------------------ // ------------------------------------------------------ /** * This class represents a node in parse tree. */ static class StringToken extends Token implements java.io.Serializable { String string; int refNumber; StringToken(int type, String str, int n) { super(type); this.string = str; this.refNumber = n; } int getReferenceNumber() { // for STRING return this.refNumber; } String getString() { // for STRING return this.string; } public String toString(int options) { if (this.type == BACKREFERENCE) return "\\"+this.refNumber; else return REUtil.quoteMeta(this.string); } } /** * This class represents a node in parse tree. */ static class ConcatToken extends Token implements java.io.Serializable { Token child; Token child2; ConcatToken(Token t1, Token t2) { super(Token.CONCAT); this.child = t1; this.child2 = t2; } int size() { return 2; } Token getChild(int index) { return index == 0 ? this.child : this.child2; } public String toString(int options) { String ret; if (this.child2.type == CLOSURE && this.child2.getChild(0) == this.child) { ret = this.child.toString(options)+"+"; } else if (this.child2.type == NONGREEDYCLOSURE && this.child2.getChild(0) == this.child) { ret = this.child.toString(options)+"+?"; } else ret = this.child.toString(options)+this.child2.toString(options); return ret; } } /** * This class represents a node in parse tree. */ static class CharToken extends Token implements java.io.Serializable { int chardata; CharToken(int type, int ch) { super(type); this.chardata = ch; } int getChar() { return this.chardata; } public String toString(int options) { String ret; switch (this.type) { case CHAR: switch (this.chardata) { case '|': case '*': case '+': case '?': case '(': case ')': case '.': case '[': case '{': case '\\': ret = "\\"+(char)this.chardata; 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 (this.chardata >= 0x10000) { String pre = "0"+Integer.toHexString(this.chardata); ret = "\\v"+pre.substring(pre.length()-6, pre.length()); } else ret = ""+(char)this.chardata; } break; case ANCHOR: if (this == Token.token_linebeginning || this == Token.token_lineend) ret = ""+(char)this.chardata; else ret = "\\"+(char)this.chardata; break; default: ret = null; } return ret; } boolean match(int ch) { if (this.type == CHAR) { return ch == this.chardata; } else throw new RuntimeException("NFAArrow#match(): Internal error: "+this.type); } } /** * This class represents a node in parse tree. */ static class ClosureToken extends Token implements java.io.Serializable { int min; int max; Token child; ClosureToken(int type, Token tok) { super(type); this.child = tok; this.setMin(-1); this.setMax(-1); } int size() { return 1; } Token getChild(int index) { return this.child; } final void setMin(int min) { this.min = min; } final void setMax(int max) { this.max = max; } final int getMin() { return this.min; } final int getMax() { return this.max; } public String toString(int options) { String ret; if (this.type == CLOSURE) { if (this.getMin() < 0 && this.getMax() < 0) { ret = this.child.toString(options)+"*"; } else if (this.getMin() == this.getMax()) { ret = this.child.toString(options)+"{"+this.getMin()+"}"; } else if (this.getMin() >= 0 && this.getMax() >= 0) { ret = this.child.toString(options)+"{"+this.getMin()+","+this.getMax()+"}"; } else if (this.getMin() >= 0 && this.getMax() < 0) { ret = this.child.toString(options)+"{"+this.getMin()+",}"; } else throw new RuntimeException("Token#toString(): CLOSURE " +this.getMin()+", "+this.getMax()); } else { if (this.getMin() < 0 && this.getMax() < 0) { ret = this.child.toString(options)+"*?"; } else if (this.getMin() == this.getMax()) { ret = this.child.toString(options)+"{"+this.getMin()+"}?"; } else if (this.getMin() >= 0 && this.getMax() >= 0) { ret = this.child.toString(options)+"{"+this.getMin()+","+this.getMax()+"}?"; } else if (this.getMin() >= 0 && this.getMax() < 0) { ret = this.child.toString(options)+"{"+this.getMin()+",}?"; } else throw new RuntimeException("Token#toString(): NONGREEDYCLOSURE " +this.getMin()+", "+this.getMax()); } return ret; } } /** * This class represents a node in parse tree. */ static class ParenToken extends Token implements java.io.Serializable { Token child; int parennumber; ParenToken(int type, Token tok, int paren) { super(type); this.child = tok; this.parennumber = paren; } int size() { return 1; } Token getChild(int index) { return this.child; } int getParenNumber() { return this.parennumber; } public String toString(int options) { String ret = null; switch (this.type) { case PAREN: if (this.parennumber == 0) { ret = "(?:"+this.child.toString(options)+")"; } else { ret = "("+this.child.toString(options)+")"; } break; case LOOKAHEAD: ret = "(?="+this.child.toString(options)+")"; break; case NEGATIVELOOKAHEAD: ret = "(?!"+this.child.toString(options)+")"; break; case LOOKBEHIND: ret = "(?<="+this.child.toString(options)+")"; break; case NEGATIVELOOKBEHIND: ret = "(?"+this.child.toString(options)+")"; break; } return ret; } } /** * (?(condition)yes-pattern|no-pattern) */ static class ConditionToken extends Token implements java.io.Serializable { int refNumber; Token condition; Token yes; Token no; ConditionToken(int refno, Token cond, Token yespat, Token nopat) { super(Token.CONDITION); this.refNumber = refno; this.condition = cond; this.yes = yespat; this.no = nopat; } int size() { return this.no == null ? 1 : 2; } Token getChild(int index) { if (index == 0) return this.yes; if (index == 1) return this.no; throw new RuntimeException("Internal Error: "+index); } public String toString(int options) { String ret; if (refNumber > 0) { ret = "(?("+refNumber+")"; } else if (this.condition.type == Token.ANCHOR) { ret = "(?("+this.condition+")"; } else { ret = "(?"+this.condition; } if (this.no == null) { ret += this.yes+")"; } else { ret += this.yes+"|"+this.no+")"; } return ret; } } /** * (ims-ims: .... ) */ static class ModifierToken extends Token implements java.io.Serializable { Token child; int add; int mask; ModifierToken(Token tok, int add, int mask) { super(Token.MODIFIERGROUP); this.child = tok; this.add = add; this.mask = mask; } int size() { return 1; } Token getChild(int index) { return this.child; } int getOptions() { return this.add; } int getOptionsMask() { return this.mask; } public String toString(int options) { return "(?" +(this.add == 0 ? "" : REUtil.createOptionString(this.add)) +(this.mask == 0 ? "" : REUtil.createOptionString(this.mask)) +":" +this.child.toString(options) +")"; } } /** * This class represents a node in parse tree. * for UNION or CONCAT. */ static class UnionToken extends Token implements java.io.Serializable { Vector children; UnionToken(int type) { super(type); } void addChild(Token tok) { if (tok == null) return; if (this.children == null) this.children = new Vector(); if (this.type == UNION) { this.children.addElement(tok); return; } // This is CONCAT, and new child is CONCAT. if (tok.type == CONCAT) { for (int i = 0; i < tok.size(); i ++) this.addChild(tok.getChild(i)); // Recursion return; } int size = this.children.size(); if (size == 0) { this.children.addElement(tok); return; } Token previous = (Token)this.children.elementAt(size-1); if (!((previous.type == CHAR || previous.type == STRING) && (tok.type == CHAR || tok.type == STRING))) { this.children.addElement(tok); return; } //System.err.println("Merge '"+previous+"' and '"+tok+"'."); StringBuffer buffer; int nextMaxLength = (tok.type == CHAR ? 2 : tok.getString().length()); if (previous.type == CHAR) { // Replace previous token by STRING buffer = new StringBuffer(2 + nextMaxLength); int ch = previous.getChar(); if (ch >= 0x10000) buffer.append(REUtil.decomposeToSurrogates(ch)); else buffer.append((char)ch); previous = Token.createString(null); this.children.setElementAt(previous, size-1); } else { // STRING buffer = new StringBuffer(previous.getString().length() + nextMaxLength); buffer.append(previous.getString()); } if (tok.type == CHAR) { int ch = tok.getChar(); if (ch >= 0x10000) buffer.append(REUtil.decomposeToSurrogates(ch)); else buffer.append((char)ch); } else { buffer.append(tok.getString()); } ((StringToken)previous).string = new String(buffer); } int size() { return this.children == null ? 0 : this.children.size(); } Token getChild(int index) { return (Token)this.children.elementAt(index); } public String toString(int options) { String ret; if (this.type == CONCAT) { if (this.children.size() == 2) { Token ch = this.getChild(0); Token ch2 = this.getChild(1); if (ch2.type == CLOSURE && ch2.getChild(0) == ch) { ret = ch.toString(options)+"+"; } else if (ch2.type == NONGREEDYCLOSURE && ch2.getChild(0) == ch) { ret = ch.toString(options)+"+?"; } else ret = ch.toString(options)+ch2.toString(options); } else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < this.children.size(); i ++) { sb.append(((Token)this.children.elementAt(i)).toString(options)); } ret = new String(sb); } return ret; } if (this.children.size() == 2 && this.getChild(1).type == EMPTY) { ret = this.getChild(0).toString(options)+"?"; } else if (this.children.size() == 2 && this.getChild(0).type == EMPTY) { ret = this.getChild(1).toString(options)+"??"; } else { StringBuffer sb = new StringBuffer(); sb.append(((Token)this.children.elementAt(0)).toString(options)); for (int i = 1; i < this.children.size(); i ++) { sb.append((char)'|'); sb.append(((Token)this.children.elementAt(i)).toString(options)); } ret = new String(sb); } return ret; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/README.txt0000644000175000017500000000137011361341574023502 0ustar apoapoThis is an isolated directory that was taken from the Apache Xerces-J 2.0 project. BMPPattern.java,v 1.4 2004/02/24 Match.java,v 1.5 2004/02/24 Op.java,v 1.4 2004/02/24 ParseException.java,v 1.4 2004/02/24 ParserForXMLSchema.java,v 1.6 2004/02/24 RangeToken.java,v 1.5 2004/02/24 RegexParser.java,v 1.9 2004/02/24 RegularExpression.java,v 1.8 2004/02/24 REUtil.java,v 1.8 2004/02/24 Token.java,v 1.8 2004/02/24 message.properties, 1.6 2003/03/25 It contains the following modifications: (1) a change in namespace. (2) the addition of a SchemaRegularExpression class for fast detection of NCNAME, etc. (3) Bugfix in file ParserForXMLSchema:237 No xbean code outside this directory or other directories with similar README notices was taken from Apache. xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/Op.java0000644000175000017500000002036711361341574023234 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Vector; /** */ class Op { static final int DOT = 0; static final int CHAR = 1; // Single character static final int RANGE = 3; // [a-zA-Z] static final int NRANGE = 4; // [^a-zA-Z] static final int ANCHOR = 5; // ^ $ ... static final int STRING = 6; // literal String static final int CLOSURE = 7; // X* static final int NONGREEDYCLOSURE = 8; // X*? static final int QUESTION = 9; // X? static final int NONGREEDYQUESTION = 10; // X?? static final int UNION = 11; // X|Y static final int CAPTURE = 15; // ( and ) static final int BACKREFERENCE = 16; // \1 \2 ... static final int LOOKAHEAD = 20; // (?=...) static final int NEGATIVELOOKAHEAD = 21; // (?!...) static final int LOOKBEHIND = 22; // (?<=...) static final int NEGATIVELOOKBEHIND = 23; // (?...) static final int MODIFIER = 25; // (?ims-ims:...) static final int CONDITION = 26; // (?(..)yes|no) static int nofinstances = 0; static final boolean COUNT = false; static Op createDot() { if (Op.COUNT) Op.nofinstances ++; return new Op(Op.DOT); } static CharOp createChar(int data) { if (Op.COUNT) Op.nofinstances ++; return new CharOp(Op.CHAR, data); } static CharOp createAnchor(int data) { if (Op.COUNT) Op.nofinstances ++; return new CharOp(Op.ANCHOR, data); } static CharOp createCapture(int number, Op next) { if (Op.COUNT) Op.nofinstances ++; CharOp op = new CharOp(Op.CAPTURE, number); op.next = next; return op; } static UnionOp createUnion(int size) { if (Op.COUNT) Op.nofinstances ++; //System.err.println("Creates UnionOp"); return new UnionOp(Op.UNION, size); } static ChildOp createClosure(int id) { if (Op.COUNT) Op.nofinstances ++; return new ModifierOp(Op.CLOSURE, id, -1); } static ChildOp createNonGreedyClosure() { if (Op.COUNT) Op.nofinstances ++; return new ChildOp(Op.NONGREEDYCLOSURE); } static ChildOp createQuestion(boolean nongreedy) { if (Op.COUNT) Op.nofinstances ++; return new ChildOp(nongreedy ? Op.NONGREEDYQUESTION : Op.QUESTION); } static RangeOp createRange(Token tok) { if (Op.COUNT) Op.nofinstances ++; return new RangeOp(Op.RANGE, tok); } static ChildOp createLook(int type, Op next, Op branch) { if (Op.COUNT) Op.nofinstances ++; ChildOp op = new ChildOp(type); op.setChild(branch); op.next = next; return op; } static CharOp createBackReference(int refno) { if (Op.COUNT) Op.nofinstances ++; return new CharOp(Op.BACKREFERENCE, refno); } static StringOp createString(String literal) { if (Op.COUNT) Op.nofinstances ++; return new StringOp(Op.STRING, literal); } static ChildOp createIndependent(Op next, Op branch) { if (Op.COUNT) Op.nofinstances ++; ChildOp op = new ChildOp(Op.INDEPENDENT); op.setChild(branch); op.next = next; return op; } static ModifierOp createModifier(Op next, Op branch, int add, int mask) { if (Op.COUNT) Op.nofinstances ++; ModifierOp op = new ModifierOp(Op.MODIFIER, add, mask); op.setChild(branch); op.next = next; return op; } static ConditionOp createCondition(Op next, int ref, Op conditionflow, Op yesflow, Op noflow) { if (Op.COUNT) Op.nofinstances ++; ConditionOp op = new ConditionOp(Op.CONDITION, ref, conditionflow, yesflow, noflow); op.next = next; return op; } int type; Op next = null; protected Op(int type) { this.type = type; } int size() { // for UNION return 0; } Op elementAt(int index) { // for UNIoN throw new RuntimeException("Internal Error: type="+this.type); } Op getChild() { // for CLOSURE, QUESTION throw new RuntimeException("Internal Error: type="+this.type); } // ModifierOp int getData() { // CharOp for CHAR, BACKREFERENCE, CAPTURE, ANCHOR, throw new RuntimeException("Internal Error: type="+this.type); } int getData2() { // ModifierOp throw new RuntimeException("Internal Error: type="+this.type); } RangeToken getToken() { // RANGE, NRANGE throw new RuntimeException("Internal Error: type="+this.type); } String getString() { // STRING throw new RuntimeException("Internal Error: type="+this.type); } // ================================================================ static class CharOp extends Op { int charData; CharOp(int type, int data) { super(type); this.charData = data; } int getData() { return this.charData; } } // ================================================================ static class UnionOp extends Op { Vector branches; UnionOp(int type, int size) { super(type); this.branches = new Vector(size); } void addElement(Op op) { this.branches.addElement(op); } int size() { return this.branches.size(); } Op elementAt(int index) { return (Op)this.branches.elementAt(index); } } // ================================================================ static class ChildOp extends Op { Op child; ChildOp(int type) { super(type); } void setChild(Op child) { this.child = child; } Op getChild() { return this.child; } } // ================================================================ static class ModifierOp extends ChildOp { int v1; int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ static class RangeOp extends Op { Token tok; RangeOp(int type, Token tok) { super(type); this.tok = tok; } RangeToken getToken() { return (RangeToken)this.tok; } } // ================================================================ static class StringOp extends Op { String string; StringOp(int type, String literal) { super(type); this.string = literal; } String getString() { return this.string; } } // ================================================================ static class ConditionOp extends Op { int refNumber; Op condition; Op yes; Op no; ConditionOp(int type, int refno, Op conditionflow, Op yesflow, Op noflow) { super(type); this.refNumber = refno; this.condition = conditionflow; this.yes = yesflow; this.no = noflow; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/regex/REUtil.java0000644000175000017500000002733111361341574024020 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.text.CharacterIterator; public final class REUtil { private REUtil() { } static final int composeFromSurrogates(int high, int low) { return 0x10000 + ((high-0xd800)<<10) + low-0xdc00; } static final boolean isLowSurrogate(int ch) { return (ch & 0xfc00) == 0xdc00; } static final boolean isHighSurrogate(int ch) { return (ch & 0xfc00) == 0xd800; } static final String decomposeToSurrogates(int ch) { char[] chs = new char[2]; ch -= 0x10000; chs[0] = (char)((ch>>10)+0xd800); chs[1] = (char)((ch&0x3ff)+0xdc00); return new String(chs); } static final String substring(CharacterIterator iterator, int begin, int end) { char[] src = new char[end-begin]; for (int i = 0; i < src.length; i ++) src[i] = iterator.setIndex(i+begin); return new String(src); } // ================================================================ static final int getOptionValue(int ch) { int ret = 0; switch (ch) { case 'i': ret = RegularExpression.IGNORE_CASE; break; case 'm': ret = RegularExpression.MULTIPLE_LINES; break; case 's': ret = RegularExpression.SINGLE_LINE; break; case 'x': ret = RegularExpression.EXTENDED_COMMENT; break; case 'u': ret = RegularExpression.USE_UNICODE_CATEGORY; break; case 'w': ret = RegularExpression.UNICODE_WORD_BOUNDARY; break; case 'F': ret = RegularExpression.PROHIBIT_FIXED_STRING_OPTIMIZATION; break; case 'H': ret = RegularExpression.PROHIBIT_HEAD_CHARACTER_OPTIMIZATION; break; case 'X': ret = RegularExpression.XMLSCHEMA_MODE; break; case ',': ret = RegularExpression.SPECIAL_COMMA; break; default: } return ret; } static final int parseOptions(String opts) throws ParseException { if (opts == null) return 0; int options = 0; for (int i = 0; i < opts.length(); i ++) { int v = getOptionValue(opts.charAt(i)); if (v == 0) throw new ParseException("Unknown Option: "+opts.substring(i), -1); options |= v; } return options; } static final String createOptionString(int options) { StringBuffer sb = new StringBuffer(9); if ((options & RegularExpression.PROHIBIT_FIXED_STRING_OPTIMIZATION) != 0) sb.append((char)'F'); if ((options & RegularExpression.PROHIBIT_HEAD_CHARACTER_OPTIMIZATION) != 0) sb.append((char)'H'); if ((options & RegularExpression.XMLSCHEMA_MODE) != 0) sb.append((char)'X'); if ((options & RegularExpression.IGNORE_CASE) != 0) sb.append((char)'i'); if ((options & RegularExpression.MULTIPLE_LINES) != 0) sb.append((char)'m'); if ((options & RegularExpression.SINGLE_LINE) != 0) sb.append((char)'s'); if ((options & RegularExpression.USE_UNICODE_CATEGORY) != 0) sb.append((char)'u'); if ((options & RegularExpression.UNICODE_WORD_BOUNDARY) != 0) sb.append((char)'w'); if ((options & RegularExpression.EXTENDED_COMMENT) != 0) sb.append((char)'x'); if ((options & RegularExpression.SPECIAL_COMMA) != 0) sb.append((char)','); return sb.toString().intern(); } // ================================================================ static String stripExtendedComment(String regex) { int len = regex.length(); StringBuffer buffer = new StringBuffer(len); int offset = 0; while (offset < len) { int ch = regex.charAt(offset++); // Skips a white space. if (ch == '\t' || ch == '\n' || ch == '\f' || ch == '\r' || ch == ' ') continue; if (ch == '#') { // Skips chracters between '#' and a line end. while (offset < len) { ch = regex.charAt(offset++); if (ch == '\r' || ch == '\n') break; } continue; } int next; // Strips an escaped white space. if (ch == '\\' && offset < len) { if ((next = regex.charAt(offset)) == '#' || next == '\t' || next == '\n' || next == '\f' || next == '\r' || next == ' ') { buffer.append((char)next); offset ++; } else { // Other escaped character. buffer.append((char)'\\'); buffer.append((char)next); offset ++; } } else // As is. buffer.append((char)ch); } return buffer.toString(); } // ================================================================ /** * Sample entry. *

Usage: org.apache.xerces.utils.regex.REUtil <regex> <string>
*/ public static void main(String[] argv) { String pattern = null; try { String options = ""; String target = null; if( argv.length == 0 ) { System.out.println( "Error:Usage: java REUtil -i|-m|-s|-u|-w|-X regularExpression String" ); System.exit( 0 ); } for (int i = 0; i < argv.length; i ++) { if (argv[i].length() == 0 || argv[i].charAt(0) != '-') { if (pattern == null) pattern = argv[i]; else if (target == null) target = argv[i]; else System.err.println("Unnecessary: "+argv[i]); } else if (argv[i].equals("-i")) { options += "i"; } else if (argv[i].equals("-m")) { options += "m"; } else if (argv[i].equals("-s")) { options += "s"; } else if (argv[i].equals("-u")) { options += "u"; } else if (argv[i].equals("-w")) { options += "w"; } else if (argv[i].equals("-X")) { options += "X"; } else { System.err.println("Unknown option: "+argv[i]); } } RegularExpression reg = new RegularExpression(pattern, options); System.out.println("RegularExpression: "+reg); Match match = new Match(); reg.matches(target, match); for (int i = 0; i < match.getNumberOfGroups(); i ++) { if (i == 0 ) System.out.print("Matched range for the whole pattern: "); else System.out.print("["+i+"]: "); if (match.getBeginning(i) < 0) System.out.println("-1"); else { System.out.print(match.getBeginning(i)+", "+match.getEnd(i)+", "); System.out.println("\""+match.getCapturedText(i)+"\""); } } } catch (ParseException pe) { if (pattern == null) { pe.printStackTrace(); } else { System.err.println("org.apache.xerces.utils.regex.ParseException: "+pe.getMessage()); String indent = " "; System.err.println(indent+pattern); int loc = pe.getLocation(); if (loc >= 0) { System.err.print(indent); for (int i = 0; i < loc; i ++) System.err.print("-"); System.err.println("^"); } } } catch (Exception e) { e.printStackTrace(); } } static final int CACHESIZE = 20; static final RegularExpression[] regexCache = new RegularExpression[CACHESIZE]; /** * Creates a RegularExpression instance. * This method caches created instances. * * @see RegularExpression#RegularExpression(java.lang.String, java.lang.String) */ public static RegularExpression createRegex(String pattern, String options) throws ParseException { RegularExpression re = null; int intOptions = REUtil.parseOptions(options); synchronized (REUtil.regexCache) { int i; for (i = 0; i < REUtil.CACHESIZE; i ++) { RegularExpression cached = REUtil.regexCache[i]; if (cached == null) { i = -1; break; } if (cached.equals(pattern, intOptions)) { re = cached; break; } } if (re != null) { if (i != 0) { System.arraycopy(REUtil.regexCache, 0, REUtil.regexCache, 1, i); REUtil.regexCache[0] = re; } } else { re = new RegularExpression(pattern, options); System.arraycopy(REUtil.regexCache, 0, REUtil.regexCache, 1, REUtil.CACHESIZE-1); REUtil.regexCache[0] = re; } } return re; } /** * * @see RegularExpression#matches(java.lang.String) */ public static boolean matches(String regex, String target) throws ParseException { return REUtil.createRegex(regex, null).matches(target); } /** * * @see RegularExpression#matches(java.lang.String) */ public static boolean matches(String regex, String options, String target) throws ParseException { return REUtil.createRegex(regex, options).matches(target); } // ================================================================ /** * */ public static String quoteMeta(String literal) { int len = literal.length(); StringBuffer 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); if (i > 0) buffer.append(literal.substring(0, i)); } buffer.append((char)'\\'); buffer.append((char)ch); } else if (buffer != null) buffer.append((char)ch); } return buffer != null ? buffer.toString() : literal; } // ================================================================ static void dumpString(String v) { for (int i = 0; i < v.length(); i ++) { System.out.print(Integer.toHexString(v.charAt(i))); System.out.print(" "); } System.out.println(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/0000755000175000017500000000000013041512717022125 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java0000644000175000017500000015307011403530372027445 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java0000644000175000017500000001663711361341574026517 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java0000644000175000017500000010265511361341574025415 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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)); } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java0000644000175000017500000044160511361341574027077 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/ClassLoaderResourceLoader.java0000644000175000017500000000214411361341574030030 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.ResourceLoader; import java.io.InputStream; public class ClassLoaderResourceLoader implements ResourceLoader { ClassLoader _classLoader; public ClassLoaderResourceLoader(ClassLoader classLoader) { _classLoader = classLoader; } public InputStream getResourceAsStream(String resourceName) { return _classLoader.getResourceAsStream(resourceName); } public void close() {} } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java0000644000175000017500000011646111361341574025443 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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()); } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java0000644000175000017500000013067511361341574027435 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.File; import java.io.InputStream; import java.math.BigInteger; import java.util.Collections; 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) * and makes all the primitives extend anyAtomicType. * * @author Radu Preotiuc * */ public class XQuerySchemaTypeSystem extends SchemaTypeLoaderBase implements SchemaTypeSystem { // The global builtin type system 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 public static final int BTC_FIRST_XQUERY = 52; public static final int BTC_ANY_ATOMIC = 52; public static final int BTC_DAY_TIME_DURATION = 53; public static final int BTC_YEAR_MONTH_DURATION = 54; public static final int BTC_LAST_XQUERY = 54; // some constants that need to be initialized early private static final SchemaType[] EMPTY_SCHEMATYPE_ARRAY = new SchemaType[0]; private static final SchemaType.Ref[] EMPTY_SCHEMATYPEREF_ARRAY = new SchemaType.Ref[0]; private static final SchemaGlobalElement[] EMPTY_SCHEMAELEMENT_ARRAY = new SchemaGlobalElement[0]; private static final SchemaGlobalAttribute[] EMPTY_SCHEMAATTRIBUTE_ARRAY = new SchemaGlobalAttribute[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]; private static XQuerySchemaTypeSystem _global = new XQuerySchemaTypeSystem(); // UR types public static final SchemaTypeImpl ST_ANY_TYPE = _global.getBuiltinType(SchemaType.BTC_ANY_TYPE); public static final SchemaTypeImpl ST_ANY_SIMPLE = _global.getBuiltinType(SchemaType.BTC_ANY_SIMPLE); public static final SchemaTypeImpl ST_ANY_ATOMIC = _global.getBuiltinType(BTC_ANY_ATOMIC); // primitives public static final SchemaTypeImpl ST_BOOLEAN = _global.getBuiltinType(SchemaType.BTC_BOOLEAN); public static final SchemaTypeImpl ST_BASE_64_BINARY = _global.getBuiltinType(SchemaType.BTC_BASE_64_BINARY); public static final SchemaTypeImpl ST_HEX_BINARY = _global.getBuiltinType(SchemaType.BTC_HEX_BINARY); public static final SchemaTypeImpl ST_ANY_URI = _global.getBuiltinType(SchemaType.BTC_ANY_URI); public static final SchemaTypeImpl ST_QNAME = _global.getBuiltinType(SchemaType.BTC_QNAME); public static final SchemaTypeImpl ST_NOTATION = _global.getBuiltinType(SchemaType.BTC_NOTATION); public static final SchemaTypeImpl ST_FLOAT = _global.getBuiltinType(SchemaType.BTC_FLOAT); public static final SchemaTypeImpl ST_DOUBLE = _global.getBuiltinType(SchemaType.BTC_DOUBLE); public static final SchemaTypeImpl ST_DECIMAL = _global.getBuiltinType(SchemaType.BTC_DECIMAL); public static final SchemaTypeImpl ST_STRING = _global.getBuiltinType(SchemaType.BTC_STRING); public static final SchemaTypeImpl ST_DURATION = _global.getBuiltinType(SchemaType.BTC_DURATION); public static final SchemaTypeImpl ST_DATE_TIME = _global.getBuiltinType(SchemaType.BTC_DATE_TIME); public static final SchemaTypeImpl ST_TIME = _global.getBuiltinType(SchemaType.BTC_TIME); public static final SchemaTypeImpl ST_DATE = _global.getBuiltinType(SchemaType.BTC_DATE); public static final SchemaTypeImpl ST_G_YEAR_MONTH = _global.getBuiltinType(SchemaType.BTC_G_YEAR_MONTH); public static final SchemaTypeImpl ST_G_YEAR = _global.getBuiltinType(SchemaType.BTC_G_YEAR); public static final SchemaTypeImpl ST_G_MONTH_DAY = _global.getBuiltinType(SchemaType.BTC_G_MONTH_DAY); public static final SchemaTypeImpl ST_G_DAY = _global.getBuiltinType(SchemaType.BTC_G_DAY); public static final SchemaTypeImpl ST_G_MONTH = _global.getBuiltinType(SchemaType.BTC_G_MONTH); // derived numerics public static final SchemaTypeImpl ST_INTEGER = _global.getBuiltinType(SchemaType.BTC_INTEGER); public static final SchemaTypeImpl ST_LONG = _global.getBuiltinType(SchemaType.BTC_LONG); public static final SchemaTypeImpl ST_INT = _global.getBuiltinType(SchemaType.BTC_INT); public static final SchemaTypeImpl ST_SHORT = _global.getBuiltinType(SchemaType.BTC_SHORT); public static final SchemaTypeImpl ST_BYTE = _global.getBuiltinType(SchemaType.BTC_BYTE); public static final SchemaTypeImpl ST_NON_POSITIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_NON_POSITIVE_INTEGER); public static final SchemaTypeImpl ST_NEGATIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_NEGATIVE_INTEGER); public static final SchemaTypeImpl ST_NON_NEGATIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_NON_NEGATIVE_INTEGER); public static final SchemaTypeImpl ST_POSITIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_POSITIVE_INTEGER); public static final SchemaTypeImpl ST_UNSIGNED_LONG = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_LONG); public static final SchemaTypeImpl ST_UNSIGNED_INT = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_INT); public static final SchemaTypeImpl ST_UNSIGNED_SHORT = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_SHORT); public static final SchemaTypeImpl ST_UNSIGNED_BYTE = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_BYTE); // derived strings public static final SchemaTypeImpl ST_NORMALIZED_STRING = _global.getBuiltinType(SchemaType.BTC_NORMALIZED_STRING); public static final SchemaTypeImpl ST_TOKEN = _global.getBuiltinType(SchemaType.BTC_TOKEN); public static final SchemaTypeImpl ST_NAME = _global.getBuiltinType(SchemaType.BTC_NAME); public static final SchemaTypeImpl ST_NCNAME = _global.getBuiltinType(SchemaType.BTC_NCNAME); public static final SchemaTypeImpl ST_LANGUAGE = _global.getBuiltinType(SchemaType.BTC_LANGUAGE); public static final SchemaTypeImpl ST_ID = _global.getBuiltinType(SchemaType.BTC_ID); public static final SchemaTypeImpl ST_IDREF = _global.getBuiltinType(SchemaType.BTC_IDREF); public static final SchemaTypeImpl ST_IDREFS = _global.getBuiltinType(SchemaType.BTC_IDREFS); public static final SchemaTypeImpl ST_ENTITY = _global.getBuiltinType(SchemaType.BTC_ENTITY); public static final SchemaTypeImpl ST_ENTITIES = _global.getBuiltinType(SchemaType.BTC_ENTITIES); public static final SchemaTypeImpl ST_NMTOKEN = _global.getBuiltinType(SchemaType.BTC_NMTOKEN); public static final SchemaTypeImpl ST_NMTOKENS = _global.getBuiltinType(SchemaType.BTC_NMTOKENS); // derived durations public static final SchemaTypeImpl ST_DAY_TIME_DURATION = _global.getBuiltinType(BTC_DAY_TIME_DURATION); public static final SchemaTypeImpl ST_YEAR_MONTH_DURATION = _global.getBuiltinType(BTC_YEAR_MONTH_DURATION); // the no-type public static final SchemaTypeImpl ST_NO_TYPE = _global.getBuiltinType(SchemaType.BTC_NOT_BUILTIN); private final static XmlValueRef XMLSTR_PRESERVE = buildString("preserve"); private final static XmlValueRef XMLSTR_REPLACE = buildString("preserve"); 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 }; 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 XmlValueRef[] FACETS_WS_REPLACE = new XmlValueRef[] { 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; private final static boolean[] FIXED_FACETS_WS = new boolean[] { 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 }; 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; /* * LAST Static initializer */ static { 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++) { _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 SchemaTypeImpl getBuiltinType(int btc) { return _typeArray[arrayIndexForBtc(btc)]; } private XQuerySchemaTypeSystem() { _container.setTypeSystem(this); // UR types setupType(SchemaType.BTC_ANY_TYPE, "anyType", "org.apache.xmlbeans.XmlObject"); setupType(SchemaType.BTC_ANY_SIMPLE, "anySimpleType", "org.apache.xmlbeans.XmlAnySimpleType"); setupType(BTC_ANY_ATOMIC, "anyAtomicType", null); // primitives setupType(SchemaType.BTC_BOOLEAN, "boolean", "org.apache.xmlbeans.XmlBoolean"); setupType(SchemaType.BTC_BASE_64_BINARY, "base64Binary", "org.apache.xmlbeans.XmlBase64Binary"); setupType(SchemaType.BTC_HEX_BINARY, "hexBinary", "org.apache.xmlbeans.XmlHexBinary"); setupType(SchemaType.BTC_ANY_URI, "anyURI", "org.apache.xmlbeans.XmlAnyURI"); setupType(SchemaType.BTC_QNAME, "QName", "org.apache.xmlbeans.XmlQName"); setupType(SchemaType.BTC_NOTATION, "NOTATION", "org.apache.xmlbeans.XmlNOTATION"); setupType(SchemaType.BTC_FLOAT, "float", "org.apache.xmlbeans.XmlFloat"); setupType(SchemaType.BTC_DOUBLE, "double", "org.apache.xmlbeans.XmlDouble"); setupType(SchemaType.BTC_DECIMAL, "decimal", "org.apache.xmlbeans.XmlDecimal"); setupType(SchemaType.BTC_STRING, "string", "org.apache.xmlbeans.XmlString"); setupType(SchemaType.BTC_DURATION, "duration", "org.apache.xmlbeans.XmlDuration"); setupType(SchemaType.BTC_DATE_TIME, "dateTime", "org.apache.xmlbeans.XmlDateTime"); setupType(SchemaType.BTC_TIME, "time", "org.apache.xmlbeans.XmlTime"); setupType(SchemaType.BTC_DATE, "date", "org.apache.xmlbeans.XmlDate"); setupType(SchemaType.BTC_G_YEAR_MONTH, "gYearMonth", "org.apache.xmlbeans.XmlGYearMonth"); setupType(SchemaType.BTC_G_YEAR, "gYear", "org.apache.xmlbeans.XmlGYear"); setupType(SchemaType.BTC_G_MONTH_DAY, "gMonthDay", "org.apache.xmlbeans.XmlGMonthDay"); setupType(SchemaType.BTC_G_DAY, "gDay", "org.apache.xmlbeans.XmlGDay"); setupType(SchemaType.BTC_G_MONTH, "gMonth", "org.apache.xmlbeans.XmlGMonth"); // derived numerics setupType(SchemaType.BTC_INTEGER, "integer", "org.apache.xmlbeans.XmlInteger"); setupType(SchemaType.BTC_LONG, "long", "org.apache.xmlbeans.XmlLong"); setupType(SchemaType.BTC_INT, "int", "org.apache.xmlbeans.XmlInt"); setupType(SchemaType.BTC_SHORT, "short", "org.apache.xmlbeans.XmlShort"); setupType(SchemaType.BTC_BYTE, "byte", "org.apache.xmlbeans.XmlByte"); setupType(SchemaType.BTC_NON_POSITIVE_INTEGER, "nonPositiveInteger", "org.apache.xmlbeans.XmlNonPositiveInteger"); setupType(SchemaType.BTC_NEGATIVE_INTEGER, "negativeInteger", "org.apache.xmlbeans.XmlNegativeInteger"); setupType(SchemaType.BTC_NON_NEGATIVE_INTEGER, "nonNegativeInteger", "org.apache.xmlbeans.XmlNonNegativeInteger"); setupType(SchemaType.BTC_POSITIVE_INTEGER, "positiveInteger", "org.apache.xmlbeans.XmlPositiveInteger"); setupType(SchemaType.BTC_UNSIGNED_LONG, "unsignedLong", "org.apache.xmlbeans.XmlUnsignedLong"); setupType(SchemaType.BTC_UNSIGNED_INT, "unsignedInt", "org.apache.xmlbeans.XmlUnsignedInt"); setupType(SchemaType.BTC_UNSIGNED_SHORT, "unsignedShort", "org.apache.xmlbeans.XmlUnsignedShort"); setupType(SchemaType.BTC_UNSIGNED_BYTE, "unsignedByte", "org.apache.xmlbeans.XmlUnsignedByte"); // derived strings setupType(SchemaType.BTC_NORMALIZED_STRING, "normalizedString", "org.apache.xmlbeans.XmlNormalizedString"); setupType(SchemaType.BTC_TOKEN, "token", "org.apache.xmlbeans.XmlToken"); setupType(SchemaType.BTC_NAME, "Name", "org.apache.xmlbeans.XmlName"); setupType(SchemaType.BTC_NCNAME, "NCName", "org.apache.xmlbeans.XmlNCName"); setupType(SchemaType.BTC_LANGUAGE, "language", "org.apache.xmlbeans.XmlLanguage"); setupType(SchemaType.BTC_ID, "ID", "org.apache.xmlbeans.XmlID"); setupType(SchemaType.BTC_IDREF, "IDREF", "org.apache.xmlbeans.XmlIDREF"); setupType(SchemaType.BTC_IDREFS, "IDREFS", "org.apache.xmlbeans.XmlIDREFS"); setupType(SchemaType.BTC_ENTITY, "ENTITY", "org.apache.xmlbeans.XmlENTITY"); setupType(SchemaType.BTC_ENTITIES, "ENTITIES", "org.apache.xmlbeans.XmlENTITIES"); setupType(SchemaType.BTC_NMTOKEN, "NMTOKEN", "org.apache.xmlbeans.XmlNMTOKEN"); setupType(SchemaType.BTC_NMTOKENS, "NMTOKENS", "org.apache.xmlbeans.XmlNMTOKENS"); // derived durations setupType(BTC_DAY_TIME_DURATION, "dayTimeDuration", null); setupType(BTC_YEAR_MONTH_DURATION, "yearMonthDuration", null); // the no-type setupType(SchemaType.BTC_NOT_BUILTIN, null, null); _container.setImmutable(); } /** * Returns the name of this loader. */ public String getName() { return "xquery.typesystem.builtin"; } 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 findDocumentType(QName name) { return null; } public SchemaType findAttributeType(QName name) { return null; } public SchemaGlobalElement findElement(QName name) { return null; } public SchemaGlobalAttribute findAttribute(QName name) { return null; } public SchemaType.Ref findTypeRef(QName name) { SchemaType type = findType(name); return (type == null ? null : type.getRef()); } public SchemaType.Ref findDocumentTypeRef(QName name) { return null; } public SchemaType.Ref findAttributeTypeRef(QName name) { return null; } public SchemaGlobalElement.Ref findElementRef(QName name) { return null; } public SchemaGlobalAttribute.Ref findAttributeRef(QName name) { return null; } public SchemaModelGroup.Ref findModelGroupRef(QName name) { return null; } public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) { return null; } public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { return null; } public SchemaType typeForClassname(String classname) { return (SchemaType)_typesByClassname.get(classname); } 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() { SchemaType[] result = new SchemaType[_typeArray.length - 1]; System.arraycopy(_typeArray, 1, result, 0, result.length); return result; } /** * Returns the document types defined in this loader. */ public SchemaType[] documentTypes() { return EMPTY_SCHEMATYPE_ARRAY; } /** * Returns the attribute types defined in this loader. */ public SchemaType[] attributeTypes() { return EMPTY_SCHEMATYPE_ARRAY; } /** * Returns the global elements defined in this loader. */ public SchemaGlobalElement[] globalElements() { return EMPTY_SCHEMAELEMENT_ARRAY; } /** * Returns the global attributes defined in this loader. */ public SchemaGlobalAttribute[] globalAttributes() { return EMPTY_SCHEMAATTRIBUTE_ARRAY; } /** * Returns the model groups defined in this loader. */ public SchemaModelGroup[] modelGroups() { return EMPTY_SCHEMAMODELGROUP_ARRAY; } /** * Returns the attribute groups defined in this loader. */ public SchemaAttributeGroup[] attributeGroups() { return EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY; } /* * Returns the top-level 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); } /** * Returns the classloader used by this loader for resolving types. */ public ClassLoader getClassLoader() { return BuiltinSchemaTypeSystem.class.getClassLoader(); } /** * Saves this type to a directory. */ 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) { throw new UnsupportedOperationException("The builtin schema type system cannot be saved."); } 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) { case SchemaType.WS_PRESERVE: return XMLSTR_PRESERVE; case SchemaType.WS_REPLACE: return XMLSTR_REPLACE; case SchemaType.WS_COLLAPSE: return XMLSTR_COLLAPSE; } return null; } private static XmlValueRef buildNnInteger(BigInteger bigInt) { if (bigInt == null) return null; if (bigInt.signum() < 0) return null; try { XmlIntegerImpl i = new XmlIntegerImpl(); i.setBigIntegerValue(bigInt); i.setImmutable(); return new XmlValueRef(i); } catch (XmlValueOutOfRangeException e) { return null; } } private static XmlValueRef buildInteger(BigInteger bigInt) { if (bigInt == null) return null; try { XmlIntegerImpl i = new XmlIntegerImpl(); i.setBigIntegerValue(bigInt); i.setImmutable(); return new XmlValueRef(i); } catch (XmlValueOutOfRangeException e) { return null; } } private 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; } } 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) result.setFullJavaName(classname); _typeArray[arrayIndexForBtc(btc)] = result; _typeMap.put(name, result); _handlesToObjects.put(handle, result); _objectsToHandles.put(result, handle); if (classname != null) _typesByClassname.put(classname, result); } 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 SchemaComponent resolveHandle(String handle) { return (SchemaComponent)_handlesToObjects.get(handle); } /** * Links a type. */ 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) { case SchemaType.BTC_NOT_BUILTIN: variety = SchemaType.NOT_SIMPLE; base = ST_ANY_TYPE; break; case SchemaType.BTC_ANY_TYPE: variety = SchemaType.NOT_SIMPLE; base = null; derivationType = SchemaType.DT_RESTRICTION; break; default: assert(false); case SchemaType.BTC_ANY_SIMPLE: base = ST_ANY_TYPE; break; case BTC_ANY_ATOMIC: base = ST_ANY_SIMPLE; case SchemaType.BTC_BOOLEAN: 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_FLOAT: case SchemaType.BTC_DOUBLE: case SchemaType.BTC_DECIMAL: 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: base = ST_ANY_ATOMIC; break; // derived numerics case SchemaType.BTC_INTEGER: base = ST_DECIMAL; break; case SchemaType.BTC_LONG: base = ST_INTEGER; break; case SchemaType.BTC_INT: base = ST_LONG; break; case SchemaType.BTC_SHORT: base = ST_INT; break; case SchemaType.BTC_BYTE: base = ST_SHORT; break; case SchemaType.BTC_NON_POSITIVE_INTEGER: base = ST_INTEGER; break; case SchemaType.BTC_NEGATIVE_INTEGER: base = ST_NON_POSITIVE_INTEGER; break; case SchemaType.BTC_NON_NEGATIVE_INTEGER: base = ST_INTEGER; break; case SchemaType.BTC_POSITIVE_INTEGER: base = ST_NON_NEGATIVE_INTEGER; break; case SchemaType.BTC_UNSIGNED_LONG: base = ST_NON_NEGATIVE_INTEGER; break; case SchemaType.BTC_UNSIGNED_INT: base = ST_UNSIGNED_LONG; break; case SchemaType.BTC_UNSIGNED_SHORT: base = ST_UNSIGNED_INT; break; case SchemaType.BTC_UNSIGNED_BYTE: base = ST_UNSIGNED_SHORT; break; // derived strings case SchemaType.BTC_NORMALIZED_STRING: base = ST_STRING; break; case SchemaType.BTC_TOKEN: base = ST_NORMALIZED_STRING; break; case SchemaType.BTC_NAME: base = ST_TOKEN; break; case SchemaType.BTC_NCNAME: base = ST_NAME; break; case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_ENTITY: base = ST_NCNAME; break; case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_NMTOKEN: 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) item = ST_IDREF; else if (btc == SchemaType.BTC_ENTITIES) item = ST_ENTITY; else item = ST_NMTOKEN; break; // derived durations case BTC_DAY_TIME_DURATION: case BTC_YEAR_MONTH_DURATION: base = ST_DURATION; break; } result.setDerivationType(derivationType); result.setSimpleTypeVariety(variety); if (variety != SchemaType.NOT_SIMPLE) { result.setSimpleType(true); } 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.setListItemTypeRef(item == null ? null : item.getRef()); if (btc >= SchemaType.BTC_FIRST_PRIMITIVE && btc <= SchemaType.BTC_LAST_PRIMITIVE || btc == BTC_ANY_ATOMIC) result.setPrimitiveTypeRef(result.getRef()); else if (variety == SchemaType.ATOMIC) { if (base == null) throw new IllegalStateException("Base was null for " + btc); if (base.getPrimitiveType() == null) throw new IllegalStateException("Base.gpt was null for " + btc); result.setPrimitiveTypeRef(base.getPrimitiveType().getRef()); } XmlValueRef[] facets; boolean[] fixedf; int wsr = SchemaType.WS_COLLAPSE; int decimalSize = SchemaType.NOT_DECIMAL; // now set up facets switch (btc) { default: assert(false); case SchemaType.BTC_ANY_TYPE: case SchemaType.BTC_ANY_SIMPLE: case SchemaType.BTC_NOT_BUILTIN: case BTC_ANY_ATOMIC: facets = FACETS_NONE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_UNSPECIFIED; break; case SchemaType.BTC_STRING: facets = FACETS_WS_PRESERVE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_PRESERVE; break; case SchemaType.BTC_BOOLEAN: case SchemaType.BTC_BASE_64_BINARY: case SchemaType.BTC_HEX_BINARY: case SchemaType.BTC_ANY_URI: case SchemaType.BTC_QNAME: case SchemaType.BTC_FLOAT: case SchemaType.BTC_DOUBLE: case SchemaType.BTC_NOTATION: 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: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_WS; break; case SchemaType.BTC_DECIMAL: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_WS; decimalSize = SchemaType.SIZE_BIG_DECIMAL; break; // derived numerics case SchemaType.BTC_INTEGER: facets = FACETS_INTEGER; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_LONG: facets = FACETS_LONG; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_LONG; break; case SchemaType.BTC_INT: facets = FACETS_INT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_INT; break; case SchemaType.BTC_SHORT: facets = FACETS_SHORT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_SHORT; break; case SchemaType.BTC_BYTE: facets = FACETS_BYTE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BYTE; break; case SchemaType.BTC_NON_POSITIVE_INTEGER: facets = FACETS_NONPOSITIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_NEGATIVE_INTEGER: facets = FACETS_NEGATIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_NON_NEGATIVE_INTEGER: facets = FACETS_NONNEGATIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_POSITIVE_INTEGER: facets = FACETS_POSITIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_UNSIGNED_LONG: facets = FACETS_UNSIGNED_LONG; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_UNSIGNED_INT: facets = FACETS_UNSIGNED_INT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_LONG; break; case SchemaType.BTC_UNSIGNED_SHORT: facets = FACETS_UNSIGNED_SHORT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_INT; break; case SchemaType.BTC_UNSIGNED_BYTE: facets = FACETS_UNSIGNED_BYTE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_SHORT; break; // derived strings case SchemaType.BTC_NORMALIZED_STRING: facets = FACETS_WS_REPLACE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_REPLACE; break; case SchemaType.BTC_TOKEN: case SchemaType.BTC_NAME: case SchemaType.BTC_NCNAME: case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_IDREFS: case SchemaType.BTC_ENTITY: case SchemaType.BTC_NMTOKEN: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_COLLAPSE; break; case SchemaType.BTC_ENTITIES: case SchemaType.BTC_NMTOKENS: facets = FACETS_BUILTIN_LIST; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_UNSPECIFIED; break; case BTC_DAY_TIME_DURATION: case BTC_YEAR_MONTH_DURATION: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_WS; wsr = SchemaType.WS_COLLAPSE; break; } // fundamental facets int ordered = SchemaType.UNORDERED; boolean isNumeric = false; boolean isFinite = false; boolean isBounded = false; switch (btc) { default: assert(false); case SchemaType.BTC_ANY_TYPE: case SchemaType.BTC_NOT_BUILTIN: case SchemaType.BTC_ANY_SIMPLE: case BTC_ANY_ATOMIC: case SchemaType.BTC_STRING: 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_NORMALIZED_STRING: case SchemaType.BTC_TOKEN: case SchemaType.BTC_NAME: case SchemaType.BTC_NCNAME: case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_IDREFS: case SchemaType.BTC_ENTITY: case SchemaType.BTC_NMTOKEN: case SchemaType.BTC_ENTITIES: case SchemaType.BTC_NMTOKENS: break; case SchemaType.BTC_BOOLEAN: isFinite = true; break; case SchemaType.BTC_FLOAT: case SchemaType.BTC_DOUBLE: case SchemaType.BTC_DECIMAL: case SchemaType.BTC_INTEGER: isNumeric = true; ordered = SchemaType.TOTAL_ORDER; break; 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 BTC_DAY_TIME_DURATION: case BTC_YEAR_MONTH_DURATION: ordered = SchemaType.PARTIAL_ORDER; break; case SchemaType.BTC_LONG: case SchemaType.BTC_INT: case SchemaType.BTC_SHORT: case SchemaType.BTC_BYTE: case SchemaType.BTC_NON_POSITIVE_INTEGER: case SchemaType.BTC_NEGATIVE_INTEGER: case SchemaType.BTC_NON_NEGATIVE_INTEGER: case SchemaType.BTC_POSITIVE_INTEGER: case SchemaType.BTC_UNSIGNED_LONG: case SchemaType.BTC_UNSIGNED_INT: case SchemaType.BTC_UNSIGNED_SHORT: case SchemaType.BTC_UNSIGNED_BYTE: isNumeric = true; ordered = SchemaType.TOTAL_ORDER; isFinite = true; isBounded = true; break; } result.setBasicFacets(facets, fixedf); result.setWhiteSpaceRule(wsr); result.setOrdered(ordered); result.setBounded(isBounded); result.setNumeric(isNumeric); result.setFinite(isFinite); result.setDecimalSize(decimalSize); result.setAnonymousTypeRefs(EMPTY_SCHEMATYPEREF_ARRAY); String pattern = null; boolean hasPattern = false; 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. hasPattern = true; break; case SchemaType.BTC_NMTOKEN: pattern = "\\c+"; hasPattern = true; break; case SchemaType.BTC_NAME: pattern = "\\i\\c*"; hasPattern = true; break; case SchemaType.BTC_NCNAME: pattern = "[\\i-[:]][\\c-[:]]*"; hasPattern = true; break; case BTC_DAY_TIME_DURATION: pattern = "[^YM]*[DT].*"; hasPattern = true; break; case BTC_YEAR_MONTH_DURATION: pattern = "[^DT]*"; hasPattern = true; break; // These types inherit their patterns case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_ENTITY: hasPattern = true; break; } 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}); } result.setPatternFacet(hasPattern); // ANY_TYPE has to be able to act like a complex type if (btc == SchemaType.BTC_ANY_TYPE) { SchemaParticleImpl contentModel = new SchemaParticleImpl(); contentModel.setParticleType(SchemaParticle.WILDCARD); contentModel.setWildcardSet(QNameSet.ALL); contentModel.setWildcardProcess(SchemaParticle.LAX); contentModel.setMinOccurs(BigInteger.ZERO); contentModel.setMaxOccurs(null); contentModel.setTransitionRules(QNameSet.ALL, true); contentModel.setTransitionNotes(QNameSet.ALL, true); SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); attrModel.setWildcardProcess(SchemaAttributeModel.LAX); attrModel.setWildcardSet(QNameSet.ALL); result.setComplexTypeVariety(SchemaType.MIXED_CONTENT); 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) { // 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 result.setComplexTypeVariety(SchemaType.EMPTY_CONTENT); result.setContentModel(contentModel, attrModel, Collections.EMPTY_MAP, Collections.EMPTY_MAP, false); result.setAnonymousTypeRefs(EMPTY_SCHEMATYPEREF_ARRAY); result.setWildcardSummary(QNameSet.EMPTY, false, QNameSet.EMPTY, false); } result.setOrderSensitive(false); } public static SchemaType getNoType() { return ST_NO_TYPE; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/PathResourceLoader.java0000644000175000017500000000434511361341574026535 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.ResourceLoader; import java.io.InputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class PathResourceLoader implements ResourceLoader { private ResourceLoader[] _path; public PathResourceLoader(ResourceLoader[] loaderpath) throws IOException { _path = new ResourceLoader[loaderpath.length]; System.arraycopy(loaderpath, 0, _path, 0, _path.length); } public PathResourceLoader(File[] filepath) { List pathlist = new ArrayList(); for (int i = 0; i < filepath.length; i++) { try { ResourceLoader path = new FileResourceLoader(filepath[i]); pathlist.add(path); } catch (IOException e) { continue; // can't read a file on classpath? skip it. } } _path = (ResourceLoader[])pathlist.toArray(new ResourceLoader[pathlist.size()]); } public InputStream getResourceAsStream(String resourceName) { for (int i = 0; i < _path.length; i++) { InputStream result = _path[i].getResourceAsStream(resourceName); if (result != null) return result; } return null; } public void close() { for (int i = 0; i < _path.length; i++) { try { _path[i].close(); } catch (Exception e) { // oh well. } } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java0000644000175000017500000023700211714330736025664 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaStringEnumEntryImpl.java0000644000175000017500000000232611361341574030057 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaStringEnumEntry; public class SchemaStringEnumEntryImpl implements SchemaStringEnumEntry { private String _string; private int _int; private String _enumName; public SchemaStringEnumEntryImpl(String str, int i, String enumName) { _string = str; _int = i; _enumName = enumName; } public String getString() { return _string; } public int getIntValue() { return _int; } public String getEnumName() { return _enumName; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java0000644000175000017500000015413711361341574024724 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java0000644000175000017500000033643111476266350027214 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java0000644000175000017500000000632511361341574027725 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.xml.namespace.QName; import org.apache.xmlbeans.SchemaAnnotation; import org.apache.xmlbeans.SchemaComponent; import org.apache.xmlbeans.SchemaAttributeGroup; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.SchemaTypeSystem; public class SchemaAttributeGroupImpl implements SchemaAttributeGroup { private SchemaContainer _container; private QName _name; private XmlObject _parseObject; private Object _userData; private String _parseTNS; private String _formDefault; private boolean _chameleon; private boolean _redefinition; private SchemaAnnotation _annotation; private String _filename; public SchemaAttributeGroupImpl(SchemaContainer container) { _container = container; } public SchemaAttributeGroupImpl(SchemaContainer container, QName name) { _container = container; _name = name; } public void init(QName name, String targetNamespace, boolean chameleon, String formDefault, boolean redefinition, XmlObject x, SchemaAnnotation a, Object userData) { assert _name == null || name.equals( _name ); _name = name; _parseTNS = targetNamespace; _chameleon = chameleon; _formDefault = formDefault; _redefinition = redefinition; _parseObject = x; _annotation = a; _userData = userData; } public SchemaTypeSystem getTypeSystem() { return _container.getTypeSystem(); } SchemaContainer getContainer() { return _container; } public int getComponentType() { return SchemaComponent.ATTRIBUTE_GROUP; } public void setFilename(String filename) { _filename = filename; } public String getSourceName() { return _filename; } public QName getName() { return _name; } public XmlObject getParseObject() { return _parseObject; } public String getTargetNamespace() { return _parseTNS; } public String getChameleonNamespace() { return _chameleon ? _parseTNS : null; } public String getFormDefault() { return _formDefault; } public SchemaAnnotation getAnnotation() { return _annotation; } private SchemaAttributeGroup.Ref _selfref = new SchemaAttributeGroup.Ref(this); public SchemaAttributeGroup.Ref getRef() { return _selfref; } public SchemaComponent.Ref getComponentRef() { return getRef(); } public boolean isRedefinition() { return _redefinition; } public Object getUserData() { return _userData; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java0000644000175000017500000005450111361341574027014 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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()); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java0000644000175000017500000000660211361341574027020 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaAnnotation; import org.apache.xmlbeans.SchemaComponent; import org.apache.xmlbeans.SchemaModelGroup; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.SchemaTypeSystem; import javax.xml.namespace.QName; public class SchemaModelGroupImpl implements SchemaModelGroup { private SchemaContainer _container; private QName _name; private XmlObject _parseObject; private Object _userData; private String _parseTNS; private boolean _chameleon; private String _elemFormDefault; private String _attFormDefault; private boolean _redefinition; private SchemaAnnotation _annotation; private String _filename; public SchemaModelGroupImpl(SchemaContainer container) { _container = container; } public SchemaModelGroupImpl(SchemaContainer container, QName name) { _container = container; _name = name; } public void init(QName name, String targetNamespace, boolean chameleon, String elemFormDefault, String attFormDefault, boolean redefinition, XmlObject x, SchemaAnnotation a, Object userData) { assert _name == null || name.equals( _name ); _name = name; _parseTNS = targetNamespace; _chameleon = chameleon; _elemFormDefault = elemFormDefault; _attFormDefault = attFormDefault; _redefinition = redefinition; _parseObject = x; _annotation = a; _userData = userData; } public SchemaTypeSystem getTypeSystem() { return _container.getTypeSystem(); } SchemaContainer getContainer() { return _container; } public int getComponentType() { return SchemaComponent.MODEL_GROUP; } public void setFilename(String filename) { _filename = filename; } public String getSourceName() { return _filename; } public QName getName() { return _name; } public XmlObject getParseObject() { return _parseObject; } public String getTargetNamespace() { return _parseTNS; } public String getChameleonNamespace() { return _chameleon ? _parseTNS : null; } public String getElemFormDefault() { return _elemFormDefault; } public String getAttFormDefault() { return _attFormDefault; } public boolean isRedefinition() { return _redefinition; } public SchemaAnnotation getAnnotation() { return _annotation; } private SchemaModelGroup.Ref _selfref = new SchemaModelGroup.Ref(this); public SchemaModelGroup.Ref getRef() { return _selfref; } public SchemaComponent.Ref getComponentRef() { return getRef(); } public Object getUserData() { return _userData; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java0000644000175000017500000003516711361341574027254 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.values.TypeStoreVisitor; import org.apache.xmlbeans.impl.values.TypeStore; import javax.xml.namespace.QName; import org.apache.xmlbeans.SchemaParticle; import org.apache.xmlbeans.SchemaLocalElement; import org.apache.xmlbeans.SchemaField; import java.util.Arrays; /** * This state machine validates element order based on a deterministic * content model. */ public class SchemaTypeVisitorImpl implements TypeStoreVisitor { /** * Construct it by passing the root of the content model. */ public SchemaTypeVisitorImpl(SchemaParticle part) { init(part); } public SchemaTypeVisitorImpl() { } public void init(SchemaParticle part) { if (_stack == null) { _stack = expand(null); } if (_rollback == null) { _rollback = expand(null); } _stackSize = 0; _rollbackSize = 0; if (part != null) { push(part); _rollbackIndex = 1; } } public VisitorState[] expand(VisitorState[] orig) { int newsize = (orig == null ? 4 : orig.length * 2); VisitorState[] result = new VisitorState[newsize]; if (orig != null) System.arraycopy(orig, 0, result, 0, orig.length); for (int i = (orig == null ? 0 : orig.length); i < newsize; i++) { result[i] = new VisitorState(); } return result; } final static boolean PROBE_VALIDITY = true; final static boolean CHECK_VALIDITY = false; private VisitorState[] _stack; private VisitorState[] _rollback; int _stackSize; int _rollbackSize; private boolean _isValid; private SchemaParticle _matchedParticle; private VisitorState _top; private int _rollbackIndex; private static class VisitorState { public void copy(VisitorState orig) { _curPart = orig._curPart; _curCount = orig._curCount; _curMin = orig._curMin; _curMax = orig._curMax; _processedChildCount = orig._processedChildCount; _childCount = orig._childCount; if (orig._seen != null) { _seen = new boolean[orig._seen.length]; System.arraycopy(orig._seen, 0, _seen, 0, orig._seen.length); } } public void init(SchemaParticle part) { _curPart = part; _curMin = part.getIntMinOccurs(); _curMax = part.getIntMaxOccurs(); _curCount = 0; _processedChildCount = 0; _childCount = part.countOfParticleChild(); _seen = part.getParticleType() == SchemaParticle.ALL ? new boolean[_childCount] : null; } SchemaParticle _curPart; int _curCount; int _curMax; int _curMin; int _processedChildCount; int _childCount; boolean[] _seen; } VisitorState topRef() { return _stack[_stackSize - 1]; } void saveCopy(VisitorState ref) { if (_rollback.length == _rollbackSize) _rollback = expand(_rollback); _rollback[_rollbackSize].copy(ref); _rollbackSize += 1; } void addParticle(SchemaParticle part) { if (_stack.length == _stackSize) _stack = expand(_stack); _stack[_stackSize].init(part); _stackSize += 1; } /** * Precondition: * stack: (R1 R2 R3 R4) * top: null or discardable due to pop in progress * rollback: (R8 R7 R6 R5) (empty at the start of "visit") * * Postcondition: * stack: (R1 R2 R3) * top: D4 = mutable copy of R4 * rollback (R8 R7 R6 R5 R4) */ boolean prepare() { if (_rollbackIndex == 0) { _top = null; return false; } _top = topRef(); saveCopy(_top); _rollbackIndex = _stackSize - 1; return true; } /** * Precondition: * stack: (R1 R2 R3 R4 D5 D6) * top: D7 * rollback: (R8 R7 R6 R5) * * Postcondition: * stack: (R1 R2 R3 R4 D5 D6 D7) * top: D8 = new state based on part * rollback (R8 R7 R6 R5) */ void push(SchemaParticle part) { addParticle(part); _top = topRef(); } /** * Precondition: * stack: (R1 R2 R3 R4 D5 D6) * top: D7 is discardable * rollback: (R8 R7 R6 R5) * * Postcondition: * stack: (R1 R2 R3 R4 D5) * top: D6 (see prepare in case it's an R state) * rollback (R8 R7 R6 R5) */ boolean pop() { _stackSize -= 1; if (_stackSize <= _rollbackIndex) return prepare(); _top = topRef(); return true; } /** * Precondition: * stack: (R1 R2 R3 R4 D5 D6) * top: D7 * rollback: (R8 R7 R6 R5) * * Postcondition: * stack: (R1 R2 R3 R4 D5 D6 D7) -> and rename to D's to R's * top: null * rollback () */ void commit() { _top = null; _rollbackIndex = _stackSize; _rollbackSize = 0; } /** * Precondition: * stack: (R1 R2 R3 R4 D5 D6) * top: D7 is discardable * rollback: (R8 R7 R6 R5) * * Postcondition: * stack: (R1 R2 R3 R4 R5 R6 R7 R8) * top: null * rollback () */ void rollback() { while (_rollbackSize > 0) { _rollbackSize -= 1; VisitorState temp = _stack[_rollbackIndex]; _stack[_rollbackIndex] = _rollback[_rollbackSize]; _rollback[_rollbackSize] = temp; _rollbackIndex += 1; } _stackSize = _rollbackIndex; _top = null; } /** * When no valid next state can be found, then "notValid" * is returned. It rolls back any changes to the state * machine stack, sets to false the valid bit, and clears * the matched element state before returning false. */ boolean notValid() { _isValid = false; _matchedParticle = null; rollback(); return false; } /** * When a valid state transition has been done, then "ok" * is returned. It commits the changed state machine state, * stores the matched element state, and returns true. */ boolean ok(SchemaParticle part, boolean testValidity) { if ( ! testValidity ) { _matchedParticle = part; commit(); } else { rollback(); } return true; } /*== VISITOR IMPLEMENTATION ==*/ /** * Traverses a deterministic content model, checking for * validity at any given point. * * Call visit(null) once at the end if you're checking for * complete validity of the sequence of elements. * * This is a wrapper for the actual visit implementation. */ public boolean visit(QName eltName) { return visit(eltName, CHECK_VALIDITY); } /** * The actual implementation that * traverses a deterministic content model, checking for * validity at any given point. * * When testValidity is false then this method will change states * if the current state is valid * * When testValidity is true then this method will not change states * and will return if a particular state is valid or invalid */ public boolean visit(QName eltName, boolean testValidity) { if (!prepare()) return notValid(); // init with some values out of processedChildCount and stackSize range int lastAtProcessedChildCount = -2; int lastAtStackSize = -2; traversing: for (;;) { // optimization for cases where state doesn't change between _top._curMin and _top._curMax // check for state change see JIRA bug XMLBEANS-37 if (_top._curCount>_top._curMin && lastAtProcessedChildCount==_top._processedChildCount && lastAtStackSize==_stackSize) { _top._curCount = _top._curMax; } // save state lastAtProcessedChildCount = _top._processedChildCount; lastAtStackSize = _stackSize; while (_top._curCount >= _top._curMax) { if (!pop()) break traversing; } minmax: switch (_top._curPart.getParticleType()) { default: assert(false); case SchemaParticle.WILDCARD: if (!_top._curPart.canStartWithElement(eltName)) { if (_top._curCount < _top._curMin) return notValid(); break minmax; } _top._curCount++; return ok(_top._curPart, testValidity); case SchemaParticle.ELEMENT: if (!_top._curPart.canStartWithElement(eltName)) { if (_top._curCount < _top._curMin) return notValid(); break minmax; } _top._curCount++; return ok(_top._curPart, testValidity); case SchemaParticle.SEQUENCE: for (int i = _top._processedChildCount; i < _top._childCount; i++) { SchemaParticle candidate = _top._curPart.getParticleChild(i); if (candidate.canStartWithElement(eltName)) { _top._processedChildCount = i + 1; push(candidate); continue traversing; } if (!candidate.isSkippable()) { if (_top._processedChildCount != 0 || _top._curCount < _top._curMin) return notValid(); break minmax; } } _top._curCount++; _top._processedChildCount = 0; continue traversing; case SchemaParticle.CHOICE: for (int i = 0; i < _top._childCount; i++) { SchemaParticle candidate = _top._curPart.getParticleChild(i); if (candidate.canStartWithElement(eltName)) { _top._curCount++; push(candidate); continue traversing; } } if (_top._curCount < _top._curMin && !_top._curPart.isSkippable()) return notValid(); break minmax; case SchemaParticle.ALL: int skipped = _top._processedChildCount; allscan: for (int i = 0; i < _top._childCount; i++) { if (_top._seen[i]) continue allscan; SchemaParticle candidate = _top._curPart.getParticleChild(i); if (candidate.canStartWithElement(eltName)) { _top._processedChildCount++; _top._seen[i] = true; push(candidate); continue traversing; } else if (candidate.isSkippable()) { skipped += 1; } } if (skipped < _top._childCount) { if (_top._curCount < _top._curMin) return notValid(); break minmax; } _top._curCount++; _top._processedChildCount = 0; Arrays.fill(_top._seen, false); continue traversing; } // somebody called "break minmax", so pop out of loop if (!pop()) break traversing; } // we've completed the outermost loop if (eltName == null) return ok(null, testValidity); // this means we have extra elements at the end return notValid(); } public boolean testValid(QName eltName) { return visit(eltName,PROBE_VALIDITY); } /** * Constructs elementflags */ public int get_elementflags() { if (currentParticle() == null || currentParticle().getParticleType() != SchemaParticle.ELEMENT) return 0; SchemaLocalElement elt = (SchemaLocalElement)currentParticle(); return (elt.isNillable() ? TypeStore.NILLABLE : 0) | (elt.isDefault() ? TypeStore.HASDEFAULT : 0) | (elt.isFixed() ? TypeStore.FIXED : 0); } /** * Returns default text */ public String get_default_text() { if (currentParticle() == null || currentParticle().getParticleType() != SchemaParticle.ELEMENT) return null; return ((SchemaLocalElement)currentParticle()).getDefaultText(); } /** * Returns the schema field for this field. */ public SchemaField get_schema_field() { if (currentParticle() instanceof SchemaField) return (SchemaField)currentParticle(); return null; } /** * Returns the current schema element */ public SchemaParticle currentParticle() { return _matchedParticle; } /** * Returns true if the entire content up to now is valid. */ public boolean isAllValid() { return _isValid; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalAttributeImpl.java0000644000175000017500000001060511361341574027657 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 javax.xml.namespace.QName; import org.apache.xmlbeans.SchemaAnnotation; import org.apache.xmlbeans.SchemaBookmark; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.SchemaLocalAttribute; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlAnySimpleType; import org.apache.xmlbeans.XmlQName; import org.apache.xmlbeans.soap.SOAPArrayType; import org.apache.xmlbeans.soap.SchemaWSDLArrayType; import org.apache.xmlbeans.impl.values.NamespaceContext; import java.math.BigInteger; public class SchemaLocalAttributeImpl implements SchemaLocalAttribute, SchemaWSDLArrayType { public SchemaLocalAttributeImpl() { } public void init(QName name, SchemaType.Ref typeref, int use, String deftext, XmlObject parseObject, XmlValueRef defvalue, boolean isFixed, SOAPArrayType wsdlArray, SchemaAnnotation ann, Object userData) { if (_xmlName != null || _typeref != null) throw new IllegalStateException("Already initialized"); _use = use; _typeref = typeref; _defaultText = deftext; _parseObject = parseObject; _defaultValue = defvalue; _isDefault = (deftext != null); _isFixed = isFixed; _xmlName = name; _wsdlArrayType = wsdlArray; _annotation = ann; _userData = userData; } private String _defaultText; /* package */ XmlValueRef _defaultValue; private boolean _isFixed; private boolean _isDefault; private QName _xmlName; private SchemaType.Ref _typeref; private SOAPArrayType _wsdlArrayType; private int _use; private SchemaAnnotation _annotation; protected XmlObject _parseObject; // for QName resolution private Object _userData; public boolean isTypeResolved() { return (_typeref != null); } public void resolveTypeRef(SchemaType.Ref typeref) { if (_typeref != null) throw new IllegalStateException(); _typeref = typeref; } public int getUse() { return _use; } public QName getName() { return _xmlName; } public String getDefaultText() { return _defaultText; } public boolean isDefault() { return _isDefault; } public boolean isFixed() { return _isFixed; } public boolean isAttribute() { return true; } public SchemaAnnotation getAnnotation() { return _annotation; } public SchemaType getType() { return _typeref.get(); } public SchemaType.Ref getTypeRef() { return _typeref; } public BigInteger getMinOccurs() { return _use == REQUIRED ? BigInteger.ONE : BigInteger.ZERO; } public BigInteger getMaxOccurs() { return _use == PROHIBITED ? BigInteger.ZERO : BigInteger.ONE; } public boolean isNillable() { return false; } public SOAPArrayType getWSDLArrayType() { return _wsdlArrayType; } public XmlAnySimpleType getDefaultValue() { if (_defaultValue != null) return _defaultValue.get(); if (_defaultText != null && XmlAnySimpleType.type.isAssignableFrom(getType())) { if (_parseObject != null) { try { NamespaceContext.push(new NamespaceContext(_parseObject)); return getType().newValue(_defaultText); } finally { NamespaceContext.pop(); } } return getType().newValue(_defaultText); } return null; } public void setDefaultValue(XmlValueRef defaultRef) { _defaultValue = defaultRef; } public Object getUserData() { return _userData; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalAttributeImpl.java0000644000175000017500000000441011361341574030022 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaGlobalAttribute; import org.apache.xmlbeans.SchemaComponent; import org.apache.xmlbeans.SchemaTypeSystem; import org.apache.xmlbeans.XmlObject; public class SchemaGlobalAttributeImpl extends SchemaLocalAttributeImpl implements SchemaGlobalAttribute { SchemaContainer _container; String _filename; private String _parseTNS; private boolean _chameleon; public SchemaGlobalAttributeImpl(SchemaContainer container) { _container = container; } public SchemaTypeSystem getTypeSystem() { return _container.getTypeSystem(); } SchemaContainer getContainer() { return _container; } public int getComponentType() { return SchemaComponent.ATTRIBUTE; } public String getSourceName() { return _filename; } public void setFilename(String filename) { _filename = filename; } public void setParseContext(XmlObject parseObject, String targetNamespace, boolean chameleon) { _parseObject = parseObject; _parseTNS = targetNamespace; _chameleon = chameleon; } public XmlObject getParseObject() { return _parseObject; } public String getTargetNamespace() { return _parseTNS; } public String getChameleonNamespace() { return _chameleon ? _parseTNS : null; } private SchemaGlobalAttribute.Ref _selfref = new SchemaGlobalAttribute.Ref(this); public SchemaGlobalAttribute.Ref getRef() { return _selfref; } public SchemaComponent.Ref getComponentRef() { return getRef(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java0000644000175000017500000000546611361341574027676 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaAttributeModel; import org.apache.xmlbeans.SchemaGlobalAttribute; import org.apache.xmlbeans.QNameSet; import org.apache.xmlbeans.QNameSetBuilder; import org.apache.xmlbeans.SchemaLocalAttribute; import javax.xml.namespace.QName; import java.util.Map; import java.util.LinkedHashMap; public class SchemaAttributeModelImpl implements SchemaAttributeModel { private Map attrMap; private QNameSet wcSet; private int wcProcess; public SchemaAttributeModelImpl() { attrMap = new LinkedHashMap(); wcSet = null; wcProcess = NONE; } public SchemaAttributeModelImpl(SchemaAttributeModel sam) { attrMap = new LinkedHashMap(); if (sam == null) { wcSet = null; wcProcess = NONE; } else { SchemaLocalAttribute[] attrs = sam.getAttributes(); for (int i = 0; i < attrs.length; i++) { attrMap.put(attrs[i].getName(), attrs[i]); } if (sam.getWildcardProcess() != SchemaAttributeModel.NONE) { wcSet = sam.getWildcardSet(); wcProcess = sam.getWildcardProcess(); } } } private static final SchemaLocalAttribute[] EMPTY_SLA_ARRAY = new SchemaLocalAttribute[0]; public SchemaLocalAttribute[] getAttributes() { return (SchemaLocalAttribute[])attrMap.values().toArray(EMPTY_SLA_ARRAY); } public SchemaLocalAttribute getAttribute(QName name) { return (SchemaLocalAttribute)attrMap.get(name); } public void addAttribute(SchemaLocalAttribute attruse) { attrMap.put(attruse.getName(), attruse); } public void removeProhibitedAttribute(QName name) { attrMap.remove(name); } public QNameSet getWildcardSet() { return wcSet == null ? QNameSet.EMPTY : wcSet; } public void setWildcardSet(QNameSet set) { wcSet = set; } public int getWildcardProcess() { return wcProcess; } public void setWildcardProcess(int proc) { wcProcess = proc; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaPropertyImpl.java0000644000175000017500000001342211361341574026565 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaComponent; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.SchemaGlobalElement; import org.apache.xmlbeans.SchemaGlobalAttribute; import org.apache.xmlbeans.SchemaProperty; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.SchemaField; import org.apache.xmlbeans.QNameSet; import org.apache.xmlbeans.XmlAnySimpleType; import org.apache.xmlbeans.XmlQName; import org.apache.xmlbeans.impl.values.NamespaceContext; import java.math.BigInteger; import java.util.Set; import javax.xml.namespace.QName; public class SchemaPropertyImpl implements SchemaProperty { private QName _name; private SchemaType.Ref _typeref; private boolean _isAttribute; private SchemaType.Ref _containerTypeRef; private String _javaPropertyName; private BigInteger _minOccurs; private BigInteger _maxOccurs; private int _hasNillable; private int _hasDefault; private int _hasFixed; private String _defaultText; private boolean _isImmutable; private SchemaType.Ref _javaBasedOnTypeRef; private boolean _extendsSingleton; private boolean _extendsArray; private boolean _extendsOption; private int _javaTypeCode; private QNameSet _javaSetterDelimiter; private XmlValueRef _defaultValue; private Set _acceptedNames; private void mutate() { if (_isImmutable) throw new IllegalStateException(); } public void setImmutable() { mutate(); _isImmutable = true; } public SchemaType getContainerType() { return _containerTypeRef.get(); } public void setContainerTypeRef(SchemaType.Ref typeref) { mutate(); _containerTypeRef = typeref; } public QName getName() { return _name; } public void setName(QName name) { mutate(); _name = name; } public String getJavaPropertyName() { return _javaPropertyName; } public void setJavaPropertyName(String name) { mutate(); _javaPropertyName = name; } public boolean isAttribute() { return _isAttribute; } public void setAttribute(boolean isAttribute) { mutate(); _isAttribute = isAttribute; } public boolean isReadOnly() { return false; } public SchemaType getType() { return _typeref.get(); } public void setTypeRef(SchemaType.Ref typeref) { mutate(); _typeref = typeref; } public SchemaType javaBasedOnType() { return _javaBasedOnTypeRef == null ? null : _javaBasedOnTypeRef.get(); } public boolean extendsJavaSingleton() { return _extendsSingleton; } public boolean extendsJavaArray() { return _extendsArray; } public boolean extendsJavaOption() { return _extendsOption; } public void setExtendsJava(SchemaType.Ref javaBasedOnTypeRef, boolean singleton, boolean option, boolean array) { mutate(); _javaBasedOnTypeRef = javaBasedOnTypeRef; _extendsSingleton = singleton; _extendsOption = option; _extendsArray = array; } public QNameSet getJavaSetterDelimiter() { if (_isAttribute) return QNameSet.EMPTY; if (_javaSetterDelimiter == null) ((SchemaTypeImpl) getContainerType()).assignJavaElementSetterModel(); assert _javaSetterDelimiter != null; return _javaSetterDelimiter; } void setJavaSetterDelimiter(QNameSet set) { _javaSetterDelimiter = set; } public QName[] acceptedNames() { if (_acceptedNames == null) return new QName[] { _name }; return (QName[])_acceptedNames.toArray(new QName[_acceptedNames.size()]); } public void setAcceptedNames(Set set) { mutate(); _acceptedNames = set; } public void setAcceptedNames(QNameSet set) { mutate(); _acceptedNames = set.includedQNamesInExcludedURIs(); } public BigInteger getMinOccurs() { return _minOccurs; } public void setMinOccurs(BigInteger min) { mutate(); _minOccurs = min; } public BigInteger getMaxOccurs() { return _maxOccurs; } public void setMaxOccurs(BigInteger max) { mutate(); _maxOccurs = max; } public int hasNillable() { return _hasNillable; } public void setNillable(int when) { mutate(); _hasNillable = when; } public int hasDefault() { return _hasDefault; } public void setDefault(int when) { mutate(); _hasDefault = when; } public int hasFixed() { return _hasFixed; } public void setFixed(int when) { mutate(); _hasFixed = when; } public String getDefaultText() { return _defaultText; } public void setDefaultText(String val) { mutate(); _defaultText = val; } public XmlAnySimpleType getDefaultValue() { if (_defaultValue != null) return _defaultValue.get(); return null; } public void setDefaultValue(XmlValueRef defaultRef) { mutate(); _defaultValue = defaultRef; } public int getJavaTypeCode() { return _javaTypeCode; } public void setJavaTypeCode(int code) { mutate(); _javaTypeCode = code; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java0000644000175000017500000027323311563242117025204 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } } } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaContainer.java0000644000175000017500000001541711361341574026047 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java0000644000175000017500000012411111361341574027572 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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.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 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; public class BuiltinSchemaTypeSystem extends SchemaTypeLoaderBase implements SchemaTypeSystem { // The global builtin type system public static SchemaTypeSystem get() { return _global; } // some constants that need to be initialized early private static final SchemaType[] EMPTY_SCHEMATYPE_ARRAY = new SchemaType[0]; private static final SchemaType.Ref[] EMPTY_SCHEMATYPEREF_ARRAY = new SchemaType.Ref[0]; private static final SchemaGlobalElement[] EMPTY_SCHEMAELEMENT_ARRAY = new SchemaGlobalElement[0]; private static final SchemaGlobalAttribute[] EMPTY_SCHEMAATTRIBUTE_ARRAY = new SchemaGlobalAttribute[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]; private static BuiltinSchemaTypeSystem _global = new BuiltinSchemaTypeSystem(); // UR types public static final SchemaTypeImpl ST_ANY_TYPE = _global.getBuiltinType(SchemaType.BTC_ANY_TYPE); public static final SchemaTypeImpl ST_ANY_SIMPLE = _global.getBuiltinType(SchemaType.BTC_ANY_SIMPLE); // primitives public static final SchemaTypeImpl ST_BOOLEAN = _global.getBuiltinType(SchemaType.BTC_BOOLEAN); public static final SchemaTypeImpl ST_BASE_64_BINARY = _global.getBuiltinType(SchemaType.BTC_BASE_64_BINARY); public static final SchemaTypeImpl ST_HEX_BINARY = _global.getBuiltinType(SchemaType.BTC_HEX_BINARY); public static final SchemaTypeImpl ST_ANY_URI = _global.getBuiltinType(SchemaType.BTC_ANY_URI); public static final SchemaTypeImpl ST_QNAME = _global.getBuiltinType(SchemaType.BTC_QNAME); public static final SchemaTypeImpl ST_NOTATION = _global.getBuiltinType(SchemaType.BTC_NOTATION); public static final SchemaTypeImpl ST_FLOAT = _global.getBuiltinType(SchemaType.BTC_FLOAT); public static final SchemaTypeImpl ST_DOUBLE = _global.getBuiltinType(SchemaType.BTC_DOUBLE); public static final SchemaTypeImpl ST_DECIMAL = _global.getBuiltinType(SchemaType.BTC_DECIMAL); public static final SchemaTypeImpl ST_STRING = _global.getBuiltinType(SchemaType.BTC_STRING); public static final SchemaTypeImpl ST_DURATION = _global.getBuiltinType(SchemaType.BTC_DURATION); public static final SchemaTypeImpl ST_DATE_TIME = _global.getBuiltinType(SchemaType.BTC_DATE_TIME); public static final SchemaTypeImpl ST_TIME = _global.getBuiltinType(SchemaType.BTC_TIME); public static final SchemaTypeImpl ST_DATE = _global.getBuiltinType(SchemaType.BTC_DATE); public static final SchemaTypeImpl ST_G_YEAR_MONTH = _global.getBuiltinType(SchemaType.BTC_G_YEAR_MONTH); public static final SchemaTypeImpl ST_G_YEAR = _global.getBuiltinType(SchemaType.BTC_G_YEAR); public static final SchemaTypeImpl ST_G_MONTH_DAY = _global.getBuiltinType(SchemaType.BTC_G_MONTH_DAY); public static final SchemaTypeImpl ST_G_DAY = _global.getBuiltinType(SchemaType.BTC_G_DAY); public static final SchemaTypeImpl ST_G_MONTH = _global.getBuiltinType(SchemaType.BTC_G_MONTH); // derived numerics public static final SchemaTypeImpl ST_INTEGER = _global.getBuiltinType(SchemaType.BTC_INTEGER); public static final SchemaTypeImpl ST_LONG = _global.getBuiltinType(SchemaType.BTC_LONG); public static final SchemaTypeImpl ST_INT = _global.getBuiltinType(SchemaType.BTC_INT); public static final SchemaTypeImpl ST_SHORT = _global.getBuiltinType(SchemaType.BTC_SHORT); public static final SchemaTypeImpl ST_BYTE = _global.getBuiltinType(SchemaType.BTC_BYTE); public static final SchemaTypeImpl ST_NON_POSITIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_NON_POSITIVE_INTEGER); public static final SchemaTypeImpl ST_NEGATIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_NEGATIVE_INTEGER); public static final SchemaTypeImpl ST_NON_NEGATIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_NON_NEGATIVE_INTEGER); public static final SchemaTypeImpl ST_POSITIVE_INTEGER = _global.getBuiltinType(SchemaType.BTC_POSITIVE_INTEGER); public static final SchemaTypeImpl ST_UNSIGNED_LONG = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_LONG); public static final SchemaTypeImpl ST_UNSIGNED_INT = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_INT); public static final SchemaTypeImpl ST_UNSIGNED_SHORT = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_SHORT); public static final SchemaTypeImpl ST_UNSIGNED_BYTE = _global.getBuiltinType(SchemaType.BTC_UNSIGNED_BYTE); // derived strings public static final SchemaTypeImpl ST_NORMALIZED_STRING = _global.getBuiltinType(SchemaType.BTC_NORMALIZED_STRING); public static final SchemaTypeImpl ST_TOKEN = _global.getBuiltinType(SchemaType.BTC_TOKEN); public static final SchemaTypeImpl ST_NAME = _global.getBuiltinType(SchemaType.BTC_NAME); public static final SchemaTypeImpl ST_NCNAME = _global.getBuiltinType(SchemaType.BTC_NCNAME); public static final SchemaTypeImpl ST_LANGUAGE = _global.getBuiltinType(SchemaType.BTC_LANGUAGE); public static final SchemaTypeImpl ST_ID = _global.getBuiltinType(SchemaType.BTC_ID); public static final SchemaTypeImpl ST_IDREF = _global.getBuiltinType(SchemaType.BTC_IDREF); public static final SchemaTypeImpl ST_IDREFS = _global.getBuiltinType(SchemaType.BTC_IDREFS); public static final SchemaTypeImpl ST_ENTITY = _global.getBuiltinType(SchemaType.BTC_ENTITY); public static final SchemaTypeImpl ST_ENTITIES = _global.getBuiltinType(SchemaType.BTC_ENTITIES); public static final SchemaTypeImpl ST_NMTOKEN = _global.getBuiltinType(SchemaType.BTC_NMTOKEN); public static final SchemaTypeImpl ST_NMTOKENS = _global.getBuiltinType(SchemaType.BTC_NMTOKENS); // the no-type public static final SchemaTypeImpl ST_NO_TYPE = _global.getBuiltinType(SchemaType.BTC_NOT_BUILTIN); private final static XmlValueRef XMLSTR_PRESERVE = buildString("preserve"); private final static XmlValueRef XMLSTR_REPLACE = buildString("preserve"); 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 }; 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 XmlValueRef[] FACETS_WS_REPLACE = new XmlValueRef[] { 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; 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 }; private final static boolean[] FIXED_FACETS_WS = new boolean[] { 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 }; 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; /* * LAST Static initializer */ static { for (int i = SchemaType.BTC_NOT_BUILTIN; i <= SchemaType.BTC_LAST_BUILTIN; i++) { _global.fillInType(i); } } private Map _typeMap = new HashMap(); private SchemaTypeImpl[] _typeArray = new SchemaTypeImpl[SchemaType.BTC_LAST_BUILTIN + 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 SchemaTypeImpl getBuiltinType(int btc) { return _typeArray[btc]; } private BuiltinSchemaTypeSystem() { _container.setTypeSystem(this); // UR types setupBuiltin(SchemaType.BTC_ANY_TYPE, "anyType", "org.apache.xmlbeans.XmlObject"); setupBuiltin(SchemaType.BTC_ANY_SIMPLE, "anySimpleType", "org.apache.xmlbeans.XmlAnySimpleType"); // primitives setupBuiltin(SchemaType.BTC_BOOLEAN, "boolean", "org.apache.xmlbeans.XmlBoolean"); setupBuiltin(SchemaType.BTC_BASE_64_BINARY, "base64Binary", "org.apache.xmlbeans.XmlBase64Binary"); setupBuiltin(SchemaType.BTC_HEX_BINARY, "hexBinary", "org.apache.xmlbeans.XmlHexBinary"); setupBuiltin(SchemaType.BTC_ANY_URI, "anyURI", "org.apache.xmlbeans.XmlAnyURI"); setupBuiltin(SchemaType.BTC_QNAME, "QName", "org.apache.xmlbeans.XmlQName"); setupBuiltin(SchemaType.BTC_NOTATION, "NOTATION", "org.apache.xmlbeans.XmlNOTATION"); setupBuiltin(SchemaType.BTC_FLOAT, "float", "org.apache.xmlbeans.XmlFloat"); setupBuiltin(SchemaType.BTC_DOUBLE, "double", "org.apache.xmlbeans.XmlDouble"); setupBuiltin(SchemaType.BTC_DECIMAL, "decimal", "org.apache.xmlbeans.XmlDecimal"); setupBuiltin(SchemaType.BTC_STRING, "string", "org.apache.xmlbeans.XmlString"); setupBuiltin(SchemaType.BTC_DURATION, "duration", "org.apache.xmlbeans.XmlDuration"); setupBuiltin(SchemaType.BTC_DATE_TIME, "dateTime", "org.apache.xmlbeans.XmlDateTime"); setupBuiltin(SchemaType.BTC_TIME, "time", "org.apache.xmlbeans.XmlTime"); setupBuiltin(SchemaType.BTC_DATE, "date", "org.apache.xmlbeans.XmlDate"); setupBuiltin(SchemaType.BTC_G_YEAR_MONTH, "gYearMonth", "org.apache.xmlbeans.XmlGYearMonth"); setupBuiltin(SchemaType.BTC_G_YEAR, "gYear", "org.apache.xmlbeans.XmlGYear"); setupBuiltin(SchemaType.BTC_G_MONTH_DAY, "gMonthDay", "org.apache.xmlbeans.XmlGMonthDay"); setupBuiltin(SchemaType.BTC_G_DAY, "gDay", "org.apache.xmlbeans.XmlGDay"); setupBuiltin(SchemaType.BTC_G_MONTH, "gMonth", "org.apache.xmlbeans.XmlGMonth"); // derived numerics setupBuiltin(SchemaType.BTC_INTEGER, "integer", "org.apache.xmlbeans.XmlInteger"); setupBuiltin(SchemaType.BTC_LONG, "long", "org.apache.xmlbeans.XmlLong"); setupBuiltin(SchemaType.BTC_INT, "int", "org.apache.xmlbeans.XmlInt"); setupBuiltin(SchemaType.BTC_SHORT, "short", "org.apache.xmlbeans.XmlShort"); setupBuiltin(SchemaType.BTC_BYTE, "byte", "org.apache.xmlbeans.XmlByte"); setupBuiltin(SchemaType.BTC_NON_POSITIVE_INTEGER, "nonPositiveInteger", "org.apache.xmlbeans.XmlNonPositiveInteger"); setupBuiltin(SchemaType.BTC_NEGATIVE_INTEGER, "negativeInteger", "org.apache.xmlbeans.XmlNegativeInteger"); setupBuiltin(SchemaType.BTC_NON_NEGATIVE_INTEGER, "nonNegativeInteger", "org.apache.xmlbeans.XmlNonNegativeInteger"); setupBuiltin(SchemaType.BTC_POSITIVE_INTEGER, "positiveInteger", "org.apache.xmlbeans.XmlPositiveInteger"); setupBuiltin(SchemaType.BTC_UNSIGNED_LONG, "unsignedLong", "org.apache.xmlbeans.XmlUnsignedLong"); setupBuiltin(SchemaType.BTC_UNSIGNED_INT, "unsignedInt", "org.apache.xmlbeans.XmlUnsignedInt"); setupBuiltin(SchemaType.BTC_UNSIGNED_SHORT, "unsignedShort", "org.apache.xmlbeans.XmlUnsignedShort"); setupBuiltin(SchemaType.BTC_UNSIGNED_BYTE, "unsignedByte", "org.apache.xmlbeans.XmlUnsignedByte"); // derived strings setupBuiltin(SchemaType.BTC_NORMALIZED_STRING, "normalizedString", "org.apache.xmlbeans.XmlNormalizedString"); setupBuiltin(SchemaType.BTC_TOKEN, "token", "org.apache.xmlbeans.XmlToken"); setupBuiltin(SchemaType.BTC_NAME, "Name", "org.apache.xmlbeans.XmlName"); setupBuiltin(SchemaType.BTC_NCNAME, "NCName", "org.apache.xmlbeans.XmlNCName"); setupBuiltin(SchemaType.BTC_LANGUAGE, "language", "org.apache.xmlbeans.XmlLanguage"); setupBuiltin(SchemaType.BTC_ID, "ID", "org.apache.xmlbeans.XmlID"); setupBuiltin(SchemaType.BTC_IDREF, "IDREF", "org.apache.xmlbeans.XmlIDREF"); setupBuiltin(SchemaType.BTC_IDREFS, "IDREFS", "org.apache.xmlbeans.XmlIDREFS"); setupBuiltin(SchemaType.BTC_ENTITY, "ENTITY", "org.apache.xmlbeans.XmlENTITY"); setupBuiltin(SchemaType.BTC_ENTITIES, "ENTITIES", "org.apache.xmlbeans.XmlENTITIES"); setupBuiltin(SchemaType.BTC_NMTOKEN, "NMTOKEN", "org.apache.xmlbeans.XmlNMTOKEN"); setupBuiltin(SchemaType.BTC_NMTOKENS, "NMTOKENS", "org.apache.xmlbeans.XmlNMTOKENS"); // the no-type setupBuiltin(SchemaType.BTC_NOT_BUILTIN, null, null); _container.setImmutable(); } /** * Returns the name of this loader. */ public String getName() { return "schema.typesystem.builtin"; } 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 findDocumentType(QName name) { return null; } public SchemaType findAttributeType(QName name) { return null; } public SchemaGlobalElement findElement(QName name) { return null; } public SchemaGlobalAttribute findAttribute(QName name) { return null; } public SchemaType.Ref findTypeRef(QName name) { SchemaType type = findType(name); return (type == null ? null : type.getRef()); } public SchemaType.Ref findDocumentTypeRef(QName name) { return null; } public SchemaType.Ref findAttributeTypeRef(QName name) { return null; } public SchemaGlobalElement.Ref findElementRef(QName name) { return null; } public SchemaGlobalAttribute.Ref findAttributeRef(QName name) { return null; } public SchemaModelGroup.Ref findModelGroupRef(QName name) { return null; } public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) { return null; } public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { return null; } public SchemaType typeForClassname(String classname) { return (SchemaType)_typesByClassname.get(classname); } 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() { SchemaType[] result = new SchemaType[_typeArray.length - 1]; System.arraycopy(_typeArray, 1, result, 0, result.length); return result; } /** * Returns the document types defined in this loader. */ public SchemaType[] documentTypes() { return EMPTY_SCHEMATYPE_ARRAY; } /** * Returns the attribute types defined in this loader. */ public SchemaType[] attributeTypes() { return EMPTY_SCHEMATYPE_ARRAY; } /** * Returns the global elements defined in this loader. */ public SchemaGlobalElement[] globalElements() { return EMPTY_SCHEMAELEMENT_ARRAY; } /** * Returns the global attributes defined in this loader. */ public SchemaGlobalAttribute[] globalAttributes() { return EMPTY_SCHEMAATTRIBUTE_ARRAY; } /** * Returns the model groups defined in this loader. */ public SchemaModelGroup[] modelGroups() { return EMPTY_SCHEMAMODELGROUP_ARRAY; } /** * Returns the attribute groups defined in this loader. */ public SchemaAttributeGroup[] attributeGroups() { return EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY; } /* * Returns the top-level 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); } /** * Returns the classloader used by this loader for resolving types. */ public ClassLoader getClassLoader() { return BuiltinSchemaTypeSystem.class.getClassLoader(); } /** * Saves this type to a directory. */ 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) { throw new UnsupportedOperationException("The builtin schema type system cannot be saved."); } private 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; } private static XmlValueRef buildNnInteger(BigInteger bigInt) { if (bigInt == null) return null; if (bigInt.signum() < 0) return null; try { XmlIntegerImpl i = new XmlIntegerImpl(); i.set(bigInt); i.setImmutable(); return new XmlValueRef(i); } catch (XmlValueOutOfRangeException e) { return null; } } private static XmlValueRef buildInteger(BigInteger bigInt) { if (bigInt == null) return null; try { XmlIntegerImpl i = new XmlIntegerImpl(); i.set(bigInt); i.setImmutable(); return new XmlValueRef(i); } catch (XmlValueOutOfRangeException e) { return null; } } private 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; } } private void setupBuiltin(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) result.setFullJavaName(classname); _typeArray[btc] = result; _typeMap.put(name, result); _handlesToObjects.put(handle, result); _objectsToHandles.put(result, handle); if (classname != null) _typesByClassname.put(classname, result); } 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 SchemaComponent resolveHandle(String handle) { return (SchemaComponent)_handlesToObjects.get(handle); } /** * Links a type. */ 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) { case SchemaType.BTC_NOT_BUILTIN: variety = SchemaType.NOT_SIMPLE; base = ST_ANY_TYPE; break; case SchemaType.BTC_ANY_TYPE: variety = SchemaType.NOT_SIMPLE; base = null; derivationType = SchemaType.DT_RESTRICTION; break; default: assert(false); case SchemaType.BTC_ANY_SIMPLE: base = ST_ANY_TYPE; break; case SchemaType.BTC_BOOLEAN: 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_FLOAT: case SchemaType.BTC_DOUBLE: case SchemaType.BTC_DECIMAL: 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: base = ST_ANY_SIMPLE; break; // derived numerics case SchemaType.BTC_INTEGER: base = ST_DECIMAL; break; case SchemaType.BTC_LONG: base = ST_INTEGER; break; case SchemaType.BTC_INT: base = ST_LONG; break; case SchemaType.BTC_SHORT: base = ST_INT; break; case SchemaType.BTC_BYTE: base = ST_SHORT; break; case SchemaType.BTC_NON_POSITIVE_INTEGER: base = ST_INTEGER; break; case SchemaType.BTC_NEGATIVE_INTEGER: base = ST_NON_POSITIVE_INTEGER; break; case SchemaType.BTC_NON_NEGATIVE_INTEGER: base = ST_INTEGER; break; case SchemaType.BTC_POSITIVE_INTEGER: base = ST_NON_NEGATIVE_INTEGER; break; case SchemaType.BTC_UNSIGNED_LONG: base = ST_NON_NEGATIVE_INTEGER; break; case SchemaType.BTC_UNSIGNED_INT: base = ST_UNSIGNED_LONG; break; case SchemaType.BTC_UNSIGNED_SHORT: base = ST_UNSIGNED_INT; break; case SchemaType.BTC_UNSIGNED_BYTE: base = ST_UNSIGNED_SHORT; break; // derived strings case SchemaType.BTC_NORMALIZED_STRING: base = ST_STRING; break; case SchemaType.BTC_TOKEN: base = ST_NORMALIZED_STRING; break; case SchemaType.BTC_NAME: base = ST_TOKEN; break; case SchemaType.BTC_NCNAME: base = ST_NAME; break; case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_ENTITY: base = ST_NCNAME; break; case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_NMTOKEN: 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) item = ST_IDREF; else if (btc == SchemaType.BTC_ENTITIES) item = ST_ENTITY; else item = ST_NMTOKEN; break; } result.setDerivationType(derivationType); result.setSimpleTypeVariety(variety); if (variety != SchemaType.NOT_SIMPLE) { result.setSimpleType(true); } 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.setListItemTypeRef(item == null ? null : item.getRef()); if (btc >= SchemaType.BTC_FIRST_PRIMITIVE && btc <= SchemaType.BTC_LAST_PRIMITIVE) result.setPrimitiveTypeRef(result.getRef()); else if (variety == SchemaType.ATOMIC) { if (base == null) throw new IllegalStateException("Base was null for " + btc); if (base.getPrimitiveType() == null) throw new IllegalStateException("Base.gpt was null for " + btc); result.setPrimitiveTypeRef(base.getPrimitiveType().getRef()); } XmlValueRef[] facets; boolean[] fixedf; int wsr = SchemaType.WS_COLLAPSE; int decimalSize = SchemaType.NOT_DECIMAL; // now set up facets switch (btc) { default: assert(false); case SchemaType.BTC_ANY_TYPE: case SchemaType.BTC_ANY_SIMPLE: case SchemaType.BTC_NOT_BUILTIN: facets = FACETS_NONE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_UNSPECIFIED; break; case SchemaType.BTC_STRING: facets = FACETS_WS_PRESERVE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_PRESERVE; break; case SchemaType.BTC_BOOLEAN: case SchemaType.BTC_BASE_64_BINARY: case SchemaType.BTC_HEX_BINARY: case SchemaType.BTC_ANY_URI: case SchemaType.BTC_QNAME: case SchemaType.BTC_FLOAT: case SchemaType.BTC_DOUBLE: case SchemaType.BTC_NOTATION: 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: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_WS; break; case SchemaType.BTC_DECIMAL: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_WS; decimalSize = SchemaType.SIZE_BIG_DECIMAL; break; // derived numerics case SchemaType.BTC_INTEGER: facets = FACETS_INTEGER; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_LONG: facets = FACETS_LONG; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_LONG; break; case SchemaType.BTC_INT: facets = FACETS_INT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_INT; break; case SchemaType.BTC_SHORT: facets = FACETS_SHORT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_SHORT; break; case SchemaType.BTC_BYTE: facets = FACETS_BYTE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BYTE; break; case SchemaType.BTC_NON_POSITIVE_INTEGER: facets = FACETS_NONPOSITIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_NEGATIVE_INTEGER: facets = FACETS_NEGATIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_NON_NEGATIVE_INTEGER: facets = FACETS_NONNEGATIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_POSITIVE_INTEGER: facets = FACETS_POSITIVE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_UNSIGNED_LONG: facets = FACETS_UNSIGNED_LONG; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_BIG_INTEGER; break; case SchemaType.BTC_UNSIGNED_INT: facets = FACETS_UNSIGNED_INT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_LONG; break; case SchemaType.BTC_UNSIGNED_SHORT: facets = FACETS_UNSIGNED_SHORT; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_INT; break; case SchemaType.BTC_UNSIGNED_BYTE: facets = FACETS_UNSIGNED_BYTE; fixedf = FIXED_FACETS_INTEGER; decimalSize = SchemaType.SIZE_SHORT; break; // derived strings case SchemaType.BTC_NORMALIZED_STRING: facets = FACETS_WS_REPLACE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_REPLACE; break; case SchemaType.BTC_TOKEN: case SchemaType.BTC_NAME: case SchemaType.BTC_NCNAME: case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_IDREFS: case SchemaType.BTC_ENTITY: case SchemaType.BTC_NMTOKEN: facets = FACETS_WS_COLLAPSE; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_COLLAPSE; break; case SchemaType.BTC_ENTITIES: case SchemaType.BTC_NMTOKENS: facets = FACETS_BUILTIN_LIST; fixedf = FIXED_FACETS_NONE; wsr = SchemaType.WS_UNSPECIFIED; break; } // fundamental facets int ordered = SchemaType.UNORDERED; boolean isNumeric = false; boolean isFinite = false; boolean isBounded = false; switch (btc) { default: assert(false); case SchemaType.BTC_ANY_TYPE: case SchemaType.BTC_NOT_BUILTIN: case SchemaType.BTC_ANY_SIMPLE: case SchemaType.BTC_STRING: 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_NORMALIZED_STRING: case SchemaType.BTC_TOKEN: case SchemaType.BTC_NAME: case SchemaType.BTC_NCNAME: case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_IDREFS: case SchemaType.BTC_ENTITY: case SchemaType.BTC_NMTOKEN: case SchemaType.BTC_ENTITIES: case SchemaType.BTC_NMTOKENS: break; case SchemaType.BTC_BOOLEAN: isFinite = true; break; case SchemaType.BTC_FLOAT: case SchemaType.BTC_DOUBLE: case SchemaType.BTC_DECIMAL: case SchemaType.BTC_INTEGER: isNumeric = true; ordered = SchemaType.TOTAL_ORDER; break; 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: ordered = SchemaType.PARTIAL_ORDER; break; case SchemaType.BTC_LONG: case SchemaType.BTC_INT: case SchemaType.BTC_SHORT: case SchemaType.BTC_BYTE: case SchemaType.BTC_NON_POSITIVE_INTEGER: case SchemaType.BTC_NEGATIVE_INTEGER: case SchemaType.BTC_NON_NEGATIVE_INTEGER: case SchemaType.BTC_POSITIVE_INTEGER: case SchemaType.BTC_UNSIGNED_LONG: case SchemaType.BTC_UNSIGNED_INT: case SchemaType.BTC_UNSIGNED_SHORT: case SchemaType.BTC_UNSIGNED_BYTE: isNumeric = true; ordered = SchemaType.TOTAL_ORDER; isFinite = true; isBounded = true; break; } result.setBasicFacets(facets, fixedf); result.setWhiteSpaceRule(wsr); result.setOrdered(ordered); result.setBounded(isBounded); result.setNumeric(isNumeric); result.setFinite(isFinite); result.setDecimalSize(decimalSize); result.setAnonymousTypeRefs(EMPTY_SCHEMATYPEREF_ARRAY); String pattern = null; boolean hasPattern = false; 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. hasPattern = true; break; case SchemaType.BTC_NMTOKEN: pattern = "\\c+"; hasPattern = true; break; case SchemaType.BTC_NAME: pattern = "\\i\\c*"; hasPattern = true; break; case SchemaType.BTC_NCNAME: pattern = "[\\i-[:]][\\c-[:]]*"; hasPattern = true; break; // These types inherit their patterns case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_ENTITY: hasPattern = true; break; } 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}); } result.setPatternFacet(hasPattern); // ANY_TYPE has to be able to act like a complex type if (btc == SchemaType.BTC_ANY_TYPE) { SchemaParticleImpl contentModel = new SchemaParticleImpl(); contentModel.setParticleType(SchemaParticle.WILDCARD); contentModel.setWildcardSet(QNameSet.ALL); contentModel.setWildcardProcess(SchemaParticle.LAX); contentModel.setMinOccurs(BigInteger.ZERO); contentModel.setMaxOccurs(null); contentModel.setTransitionRules(QNameSet.ALL, true); contentModel.setTransitionNotes(QNameSet.ALL, true); SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); attrModel.setWildcardProcess(SchemaAttributeModel.LAX); attrModel.setWildcardSet(QNameSet.ALL); result.setComplexTypeVariety(SchemaType.MIXED_CONTENT); 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) { // 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 result.setComplexTypeVariety(SchemaType.EMPTY_CONTENT); result.setContentModel(contentModel, attrModel, Collections.EMPTY_MAP, Collections.EMPTY_MAP, false); result.setAnonymousTypeRefs(EMPTY_SCHEMATYPEREF_ARRAY); result.setWildcardSummary(QNameSet.EMPTY, false, QNameSet.EMPTY, false); } result.setOrderSensitive(false); } public static SchemaType getNoType() { return ST_NO_TYPE; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java0000644000175000017500000001315711361341574030604 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java0000644000175000017500000022151611361341574025771 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/XmlValueRef.java0000644000175000017500000000367711361341574025203 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlObject; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlAnySimpleType; import java.util.ArrayList; import java.util.List; import java.util.Iterator; public class XmlValueRef { XmlAnySimpleType _obj; SchemaType.Ref _typeref; Object _initVal; public XmlValueRef(XmlAnySimpleType xobj) { if (xobj == null) throw new IllegalArgumentException(); _obj = xobj; } XmlValueRef(SchemaType.Ref typeref, Object initVal) { if (typeref == null) throw new IllegalArgumentException(); _typeref = typeref; _initVal = initVal; } synchronized XmlAnySimpleType get() { if (_obj == null) { SchemaType type = _typeref.get(); if (type.getSimpleVariety() != SchemaType.LIST) _obj = type.newValue(_initVal); else { List actualVals = new ArrayList(); for (Iterator i = ((List)_initVal).iterator(); i.hasNext(); ) { XmlValueRef ref = (XmlValueRef)i.next(); actualVals.add(ref.get()); } _obj = type.newValue(actualVals); } } return _obj; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/FileResourceLoader.java0000644000175000017500000000402111361341574026507 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.ResourceLoader; import java.io.InputStream; import java.io.FileInputStream; import java.io.File; import java.io.IOException; import java.util.zip.ZipFile; import java.util.zip.ZipEntry; public class FileResourceLoader implements ResourceLoader { private File _directory; private ZipFile _zipfile; public FileResourceLoader(File file) throws IOException { if (file.isDirectory()) _directory = file; else { _zipfile = new ZipFile(file); } } public InputStream getResourceAsStream(String resourceName) { try { if (_zipfile != null) { ZipEntry entry = _zipfile.getEntry(resourceName); if (entry == null) return null; return _zipfile.getInputStream(entry); } else { return new FileInputStream(new File(_directory, resourceName)); } } catch (IOException e) { return null; } } public void close() { if (_zipfile != null) { try { _zipfile.close(); } catch (IOException e) { // oh well. } _zipfile = null; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java0000644000175000017500000005046111361341574026766 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java0000644000175000017500000000613211361341574027305 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaAnnotation; 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 { private boolean _blockExt; private boolean _blockRest; private boolean _blockSubst; protected boolean _abs; private SchemaAnnotation _annotation; private SOAPArrayType _wsdlArrayType; private SchemaIdentityConstraint.Ref[] _constraints = new SchemaIdentityConstraint.Ref[0]; public SchemaLocalElementImpl() { setParticleType(SchemaParticle.ELEMENT); } public boolean blockExtension() { return _blockExt; } public boolean blockRestriction() { return _blockRest; } public boolean blockSubstitution() { return _blockSubst; } public boolean isAbstract() { return _abs; } public void setAbstract(boolean abs) { _abs = abs; } public void setBlock(boolean extension, boolean restriction, boolean substitution) { mutate(); _blockExt = extension; _blockRest = restriction; _blockSubst = substitution; } public void setAnnotation(SchemaAnnotation ann) { _annotation = ann; } public void setWsdlArrayType(SOAPArrayType arrayType) { _wsdlArrayType = arrayType; } public SchemaAnnotation getAnnotation() { return _annotation; } public SOAPArrayType getWSDLArrayType() { return _wsdlArrayType; } public void setIdentityConstraints(SchemaIdentityConstraint.Ref[] constraints) { mutate(); _constraints = constraints; } public SchemaIdentityConstraint[] getIdentityConstraints() { SchemaIdentityConstraint[] result = new SchemaIdentityConstraint[_constraints.length]; for (int i = 0 ; i < result.length ; i++) result[i] = _constraints[i].get(); return result; } public SchemaIdentityConstraint.Ref[] getIdentityConstraintRefs() { SchemaIdentityConstraint.Ref[] result = new SchemaIdentityConstraint.Ref[_constraints.length]; System.arraycopy(_constraints, 0, result, 0, result.length); return result; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java0000644000175000017500000004124511361341574027744 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java0000644000175000017500000000650011361341574027452 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.SchemaGlobalElement; import org.apache.xmlbeans.SchemaComponent; import org.apache.xmlbeans.SchemaTypeSystem; import org.apache.xmlbeans.XmlObject; import javax.xml.namespace.QName; import java.util.LinkedHashSet; import java.util.Set; public class SchemaGlobalElementImpl extends SchemaLocalElementImpl implements SchemaGlobalElement { private Set _sgMembers = new LinkedHashSet(); private static final QName[] _namearray = new QName[0]; private boolean _finalExt; private boolean _finalRest; private SchemaContainer _container; private String _filename; // private XmlObject _parseObject; now inherited from base private String _parseTNS; private boolean _chameleon; private SchemaGlobalElement.Ref _sg; public SchemaGlobalElementImpl(SchemaContainer container) { _container = container; } public SchemaTypeSystem getTypeSystem() { return _container.getTypeSystem(); } SchemaContainer getContainer() { return _container; } public String getSourceName() { return _filename; } public void setFilename(String filename) { _filename = filename; } void setFinal(boolean finalExt, boolean finalRest) { mutate(); _finalExt = finalExt; _finalRest = finalRest; } public int getComponentType() { return SchemaComponent.ELEMENT; } public SchemaGlobalElement substitutionGroup() { return _sg == null ? null : _sg.get(); } public void setSubstitutionGroup(SchemaGlobalElement.Ref sg) { _sg = sg; } public QName[] substitutionGroupMembers() { return (QName[])_sgMembers.toArray(_namearray); } public void addSubstitutionGroupMember(QName name) { mutate(); _sgMembers.add(name); } public boolean finalExtension() { return _finalExt; } public boolean finalRestriction() { return _finalRest; } public void setParseContext(XmlObject parseObject, String targetNamespace, boolean chameleon) { _parseObject = parseObject; _parseTNS = targetNamespace; _chameleon = chameleon; } public XmlObject getParseObject() { return _parseObject; } public String getTargetNamespace() { return _parseTNS; } public String getChameleonNamespace() { return _chameleon ? _parseTNS : null; } private SchemaGlobalElement.Ref _selfref = new SchemaGlobalElement.Ref(this); public SchemaGlobalElement.Ref getRef() { return _selfref; } public SchemaComponent.Ref getComponentRef() { return getRef(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAnnotationImpl.java0000644000175000017500000001635711361341574027065 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.List; import javax.xml.namespace.QName; import org.apache.xmlbeans.SchemaAnnotation; import org.apache.xmlbeans.SchemaTypeSystem; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.impl.xb.xsdschema.AppinfoDocument; import org.apache.xmlbeans.impl.xb.xsdschema.Annotated; import org.apache.xmlbeans.impl.xb.xsdschema.AnnotationDocument; import org.apache.xmlbeans.impl.xb.xsdschema.DocumentationDocument; import org.apache.xmlbeans.SchemaComponent; public class SchemaAnnotationImpl implements SchemaAnnotation { private SchemaContainer _container; private String[] _appInfoAsXml; private AppinfoDocument.Appinfo[] _appInfo; private String[] _documentationAsXml; private DocumentationDocument.Documentation[] _documentation; private Attribute[] _attributes; private String _filename; public void setFilename(String filename) { _filename = filename; } public String getSourceName() { return _filename; } public XmlObject[] getApplicationInformation() { if (_appInfo == null) { int n = _appInfoAsXml.length; _appInfo = new AppinfoDocument.Appinfo[n]; for (int i = 0; i < n; i++) { String appInfo = _appInfoAsXml[i]; try { _appInfo[i] = AppinfoDocument.Factory. parse(appInfo).getAppinfo(); } catch(XmlException e) { // problem in the classfile _appInfo[i] = AppinfoDocument.Factory. newInstance().getAppinfo(); } } } return _appInfo; } public XmlObject[] getUserInformation() { if (_documentation == null) { int n = _documentationAsXml.length; _documentation = new DocumentationDocument.Documentation[n]; for (int i = 0; i < n; i++) { String doc = _documentationAsXml[i]; try { _documentation[i] = DocumentationDocument.Factory. parse(doc).getDocumentation(); } catch (XmlException e) { // problem in the classfile _documentation[i] = DocumentationDocument.Factory. newInstance().getDocumentation(); } } } return _documentation; } public Attribute[] getAttributes() { return _attributes; } public int getComponentType() { return ANNOTATION; } public SchemaTypeSystem getTypeSystem() { return _container != null ? _container.getTypeSystem() : null; } SchemaContainer getContainer() { return _container; } public QName getName() { return null; } public SchemaComponent.Ref getComponentRef() { return null; } public static SchemaAnnotationImpl getAnnotation(SchemaContainer c, Annotated elem) { AnnotationDocument.Annotation ann = elem.getAnnotation(); return getAnnotation(c, elem, ann); } public static SchemaAnnotationImpl getAnnotation(SchemaContainer c, XmlObject elem, AnnotationDocument.Annotation ann) { // Check option if (StscState.get().noAnn()) return null; SchemaAnnotationImpl result = new SchemaAnnotationImpl(c); // Retrieving attributes, first attributes on the enclosing element ArrayList attrArray = new ArrayList(2); addNoSchemaAttributes(elem, attrArray); if (ann == null) { if (attrArray.size() == 0) return null; // no annotation present // no annotation element present, but attributes on the enclosing // element present, so we have an annotation component result._appInfo = new AppinfoDocument.Appinfo[0]; result._documentation = new DocumentationDocument.Documentation[0]; } else { result._appInfo = ann.getAppinfoArray(); result._documentation = ann.getDocumentationArray(); // Now the attributes on the annotation element addNoSchemaAttributes(ann, attrArray); } result._attributes = (AttributeImpl[]) attrArray.toArray(new AttributeImpl[attrArray.size()]); return result; } private static void addNoSchemaAttributes(XmlObject elem, List attrList) { XmlCursor cursor = elem.newCursor(); boolean hasAttributes = cursor.toFirstAttribute(); while (hasAttributes) { QName name = cursor.getName(); String namespaceURI = name.getNamespaceURI(); if ("".equals(namespaceURI) || "http://www.w3.org/2001/XMLSchema".equals(namespaceURI)) ; // no nothing else { String attValue = cursor.getTextValue(); String valUri; String prefix; if (attValue.indexOf(':') > 0) prefix = attValue.substring(0, attValue.indexOf(':')); else prefix = ""; cursor.push(); cursor.toParent(); valUri = cursor.namespaceForPrefix(prefix); cursor.pop(); attrList.add(new AttributeImpl(name, attValue, valUri)); //add the attribute } hasAttributes = cursor.toNextAttribute(); } cursor.dispose(); } private SchemaAnnotationImpl(SchemaContainer c) { _container = c; } /*package*/ SchemaAnnotationImpl(SchemaContainer c, String[] aapStrings, String[] adocStrings, Attribute[] aat) { _container = c; _appInfoAsXml = aapStrings; _documentationAsXml = adocStrings; _attributes = aat; } /*package*/ static class AttributeImpl implements Attribute { private QName _name; private String _value; private String _valueUri; /*package*/ AttributeImpl(QName name, String value, String valueUri) { _name = name; _value = value; _valueUri = valueUri; } public QName getName() { return _name; } public String getValue() { return _value; } public String getValueUri() { return _valueUri; } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java0000644000175000017500000002622411361341574027522 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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."); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java0000644000175000017500000002573111361341574025442 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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()); } } } } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java0000644000175000017500000025457411501523001027624 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaDependencies.java0000644000175000017500000001173611361341574026513 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/soap/0000755000175000017500000000000013041512717020666 5ustar apoapoxmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/soap/SchemaWSDLArrayType.java0000644000175000017500000000166511361341574025300 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * In the current implementation, schema elements and attributes * can be coerced to this interface in order to retrieve the value * of the wsdl:arrayType attributes on attributes and elements. */ public interface SchemaWSDLArrayType { SOAPArrayType getWSDLArrayType(); } xmlbeans-2.6.0/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java0000644000175000017500000003310111361341574024136 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/xmlpublic/0000755000175000017500000000000011361341573014242 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/javax/0000755000175000017500000000000011361341573015353 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/javax/xml/0000755000175000017500000000000011361341573016153 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/javax/xml/namespace/0000755000175000017500000000000013041512717020104 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/javax/xml/namespace/NamespaceContext.java0000644000175000017500000000161311361341573024214 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.xml.namespace; import java.util.Iterator; public interface NamespaceContext { public String getNamespaceURI(String prefix); public String getPrefix(String namespaceURI); public Iterator getPrefixes(String namespaceURI); } xmlbeans-2.6.0/src/xmlpublic/javax/xml/namespace/QName.java0000644000175000017500000001557711361341573021772 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.xml.namespace; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; /** * QName class represents the value of a qualified name * as specified in XML * Schema Part2: Datatypes specification. *

* The value of a QName contains a namespaceURI, a localPart and a prefix. * The localPart provides the local part of the qualified name. The * namespaceURI is a URI reference identifying the namespace. * * @version 1.1 */ public class QName implements Serializable { private static final long serialVersionUID = -9120448754896609940L; /** comment/shared empty string */ private static final String emptyString = "".intern(); /** Field namespaceURI */ private String namespaceURI; /** Field localPart */ private String localPart; /** Field prefix */ private String prefix; /** * Constructor for the QName. * * @param localPart Local part of the QName */ public QName(String localPart) { this(emptyString, localPart, emptyString); } /** * Constructor for the QName. * * @param namespaceURI Namespace URI for the QName * @param localPart Local part of the QName. */ public QName(String namespaceURI, String localPart) { this(namespaceURI, localPart, emptyString); } /** * Constructor for the QName. * * @param namespaceURI Namespace URI for the QName * @param localPart Local part of the QName. * @param prefix Prefix of the QName. */ public QName(String namespaceURI, String localPart, String prefix) { this.namespaceURI = (namespaceURI == null) ? emptyString : namespaceURI.intern(); if (localPart == null) { throw new IllegalArgumentException("invalid QName local part"); } else { this.localPart = localPart.intern(); } if (prefix == null) { throw new IllegalArgumentException("invalid QName prefix"); } else { this.prefix = prefix.intern(); } } /** * Gets the Namespace URI for this QName * * @return Namespace URI */ public String getNamespaceURI() { return namespaceURI; } /** * Gets the Local part for this QName * * @return Local part */ public String getLocalPart() { return localPart; } /** * Gets the Prefix for this QName * * @return Prefix */ public String getPrefix() { return prefix; } /** * Returns a string representation of this QName * * @return a string representation of the QName */ public String toString() { return ((namespaceURI == emptyString) ? localPart : '{' + namespaceURI + '}' + localPart); } /** * Tests this QName for equality with another object. *

* If the given object is not a QName or is null then this method * returns false. *

* For two QNames to be considered equal requires that both * localPart and namespaceURI must be equal. This method uses * String.equals to check equality of localPart * and namespaceURI. Any class that extends QName is required * to satisfy this equality contract. *

* This method satisfies the general contract of the Object.equals method. * * @param obj the reference object with which to compare * * @return true if the given object is identical to this * QName: false otherwise. */ public final boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof QName)) { return false; } if ((namespaceURI == ((QName) obj).namespaceURI) && (localPart == ((QName) obj).localPart)) { return true; } return false; } /** * Returns a QName holding the value of the specified String. *

* The string must be in the form returned by the QName.toString() * method, i.e. "{namespaceURI}localPart", with the "{namespaceURI}" * part being optional. *

* This method doesn't do a full validation of the resulting QName. * In particular, it doesn't check that the resulting namespace URI * is a legal URI (per RFC 2396 and RFC 2732), nor that the resulting * local part is a legal NCName per the XML Namespaces specification. * * @param s the string to be parsed * @throws java.lang.IllegalArgumentException If the specified String cannot be parsed as a QName * @return QName corresponding to the given String */ public static QName valueOf(String s) { if ((s == null) || s.equals("")) { throw new IllegalArgumentException("invalid QName literal"); } if (s.charAt(0) == '{') { int i = s.indexOf('}'); if (i == -1) { throw new IllegalArgumentException("invalid QName literal"); } if (i == s.length() - 1) { throw new IllegalArgumentException("invalid QName literal"); } else { return new QName(s.substring(1, i), s.substring(i + 1)); } } else { return new QName(s); } } /** * Returns a hash code value for this QName object. The hash code * is based on both the localPart and namespaceURI parts of the * QName. This method satisfies the general contract of the * Object.hashCode method. * * @return a hash code value for this Qname object */ public final int hashCode() { return namespaceURI.hashCode() ^ localPart.hashCode(); } /** * Ensure that deserialization properly interns the results. * @param in the ObjectInputStream to be read */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); namespaceURI = namespaceURI.intern(); localPart = localPart.intern(); prefix = prefix.intern(); } } xmlbeans-2.6.0/src/xmlpublic/org/0000755000175000017500000000000011361341572015030 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/org/apache/0000755000175000017500000000000011361341572016251 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/0000755000175000017500000000000013041512717020060 5ustar apoapoxmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SystemProperties.java0000644000175000017500000000246711361341572024277 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Hashtable; public class SystemProperties { protected static Hashtable propertyH; public static String getProperty(String key) { if (propertyH == null) { try { propertyH = System.getProperties(); } catch(SecurityException ex) { propertyH = new Hashtable(); return null; } } return (String)propertyH.get(key); } public static String getProperty(String key, String defaultValue) { String result = getProperty(key); if (result == null) return defaultValue; return result; } public static void setPropertyH(Hashtable aPropertyH) { propertyH = aPropertyH; } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/ResourceLoader.java0000644000175000017500000000144211361341573023645 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.InputStream; public interface ResourceLoader { InputStream getResourceAsStream(String resourceName); void close(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlIDREF.java0000644000175000017500000002013611361341573022242 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNormalizedString.java0000644000175000017500000002265311361341573024712 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNCName.java0000644000175000017500000002103611361341573022512 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaIdentityConstraint.java0000644000175000017500000000576211361341573025717 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlDecimal.java0000644000175000017500000002135211361341573022750 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/CDataBookmark.java0000644000175000017500000000505311361341573023373 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * 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.
* 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>
 * 
*

* @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#setSaveCDataLengthThreshold(int) * @author Cezar Andrei (cezar dot andrei at gmail dot com) */ 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(); }xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlGMonthDay.java0000644000175000017500000002264411361341573023251 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlValidationError.java0000644000175000017500000002277211361341573024525 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Contributed by Dutta Satadip for adding functionality to retrieve xml validation errors * programatically. */ package org.apache.xmlbeans; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.Location; /** * The XmlValidationError class extends the {@link XmlError }XMLError class. The XML Validator contains * extra attributes that can be used to construct the XML validation error programatically. *

* To extract the validation error cast the errors to XmlValidationError instead of * XmlError for example: *
*

 * xobj.validate(new XmlOptions().setErrorListener(errors))
 * for (Iterator it = errors.iterator(); it.hasNext(); )
 * {
 *      XmlError err = (XmlError)it.next());
 *      if (err instanceof XmlValidationError)
 *      {
 *          XmlValidationError validationError = (XmlValidationError) err;
 *     }
 * }
 *
* * * Whenever an XmlValidationError is retrieved it will always be populated with * the following information: *
    *
  • Message
  • *
  • Severity
  • *
  • Error Type
  • *
* *

* The error type is very important because the other attributes of the * XMLValidationError are populated based on the error type. *

* if errortype == INCORRECT_ELEMENT then *
* offendingQName, badSchemaType will always be present, however expectedSchemaType and * expectedQNames are available only if it is possible to determine them during vaildation. *
* *

* if errortype == ELEMENT_NOT_ALLOWED then *
* badSchemaType will always be present, however expectedSchemaType and * offendingQName are available only if it is possible to determine them during vaildation. *
* *

* if errortype == INCORRECT_ATTRIBUTE then *
* offendingQName, badSchemaType will always be present *
* *

* if errortype == ATTRIBUTE_TYPE_INVALID then *
* no other addtional attributes are populated *
* *

* if errortype == LIST_INVALID then *
* expectedSchemaType will always be present *
* *

* if errortype == UNION_INVALID then *
* expectedSchemaType will always be present *
* * *

* if errortype == NIL_ELEMENT then *
* offendingQName, expectedSchemaType and badSchemaType will always be present *
* *

* if errortype == ELEMENT_TYPE_INVALID then *
* offendingQName will always be present, other attributes may be available *
*/ public class XmlValidationError extends XmlError { public static final int INCORRECT_ELEMENT = 1; public static final int ELEMENT_NOT_ALLOWED = 2; public static final int ELEMENT_TYPE_INVALID = 3; public static final int NIL_ELEMENT = 4; public static final int INCORRECT_ATTRIBUTE = 1000; public static final int ATTRIBUTE_TYPE_INVALID = 1001; public static final int LIST_INVALID = 2000; public static final int UNION_INVALID = 3000; public static final int UNDEFINED = 10000; // QName of field in error. can be null. private QName _fieldQName; private QName _offendingQName; private SchemaType _expectedSchemaType; private List _expectedQNames; private int _errorType; private SchemaType _badSchemaType; /** * The static factory methods should be used instead of * this constructor. */ // KHK: remove this private XmlValidationError(String message, int severity, XmlCursor cursor, QName fieldQName, QName offendingQname, SchemaType expectedSchemaType, List expectedQNames, int errorType, SchemaType badSchemaType) { super(message, (String)null, severity, cursor); setFieldQName(fieldQName); setOffendingQName(offendingQname); setExpectedSchemaType(expectedSchemaType); setExpectedQNames(expectedQNames); setErrorType(errorType); setBadSchemaType(badSchemaType); } /** * The static factory methods should be used instead of * this constructor. */ private XmlValidationError(String code, Object[] args, int severity, XmlCursor cursor, QName fieldQName, QName offendingQname, SchemaType expectedSchemaType, List expectedQNames, int errorType, SchemaType badSchemaType) { super(code, args, severity, cursor); setFieldQName(fieldQName); setOffendingQName(offendingQname); setExpectedSchemaType(expectedSchemaType); setExpectedQNames(expectedQNames); setErrorType(errorType); setBadSchemaType(badSchemaType); } /** * The static factory methods should be used instead of * this constructor. */ // KHK: remove this private XmlValidationError(String message, int severity, Location loc, QName fieldQName, QName offendingQname, SchemaType expectedSchemaType, List expectedQNames, int errorType, SchemaType badSchemaType) { super(message, (String)null, severity, loc); setFieldQName(fieldQName); setOffendingQName(offendingQname); setExpectedSchemaType(expectedSchemaType); setExpectedQNames(expectedQNames); setErrorType(errorType); setBadSchemaType(badSchemaType); } /** * The static factory methods should be used instead of * this constructor. */ private XmlValidationError(String code, Object[] args, int severity, Location loc, QName fieldQName, QName offendingQname, SchemaType expectedSchemaType, List expectedQNames, int errorType, SchemaType badSchemaType) { super(code, args, severity, loc); setFieldQName(fieldQName); setOffendingQName(offendingQname); setExpectedSchemaType(expectedSchemaType); setExpectedQNames(expectedQNames); setErrorType(errorType); setBadSchemaType(badSchemaType); } public static XmlValidationError forCursorWithDetails( String message, String code, Object[] args, int severity, XmlCursor cursor, QName fieldQName, QName offendingQname, SchemaType expectedSchemaType, List expectedQNames, int errorType, SchemaType badSchemaType) { if (code == null) return new XmlValidationError(message, severity, cursor, fieldQName, offendingQname, expectedSchemaType, expectedQNames, errorType, badSchemaType); else return new XmlValidationError(code, args, severity, cursor, fieldQName, offendingQname, expectedSchemaType, expectedQNames, errorType, badSchemaType); } public static XmlValidationError forLocationWithDetails( String message, String code, Object[] args, int severity, Location location, QName fieldQName, QName offendingQname, SchemaType expectedSchemaType, List expectedQNames, int errorType, SchemaType badSchemaType) { if (code == null) return new XmlValidationError(message, severity, location, fieldQName, offendingQname, expectedSchemaType, expectedQNames, errorType, badSchemaType); else return new XmlValidationError(code, args, severity, location, fieldQName, offendingQname, expectedSchemaType, expectedQNames, errorType, badSchemaType); } public String getMessage() { if (_fieldQName != null) { String msg = super.getMessage(); StringBuffer sb = new StringBuffer(msg.length() + 100); sb.append(msg); sb.append(" in element "); sb.append(_fieldQName.getLocalPart()); if (_fieldQName.getNamespaceURI() != null && _fieldQName.getNamespaceURI().length() != 0) sb.append('@').append(_fieldQName.getNamespaceURI()); return sb.toString(); } else return super.getMessage(); } public SchemaType getBadSchemaType() { return _badSchemaType; } public void setBadSchemaType(SchemaType _badSchemaType) { this._badSchemaType = _badSchemaType; } public int getErrorType() { return _errorType; } public void setErrorType(int _errorType) { this._errorType = _errorType; } public List getExpectedQNames() { return _expectedQNames; } public void setExpectedQNames(List _expectedQNames) { this._expectedQNames = _expectedQNames; } public QName getFieldQName() { return _fieldQName; } public void setFieldQName(QName _fieldQName) { this._fieldQName = _fieldQName; } public QName getOffendingQName() { return _offendingQName; } public void setOffendingQName(QName _offendingQName) { this._offendingQName = _offendingQName; } public SchemaType getExpectedSchemaType() { return _expectedSchemaType; } public void setExpectedSchemaType(SchemaType _expectedSchemaType) { this._expectedSchemaType = _expectedSchemaType; } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlInteger.java0000644000175000017500000002222211361341573023004 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlLanguage.java0000644000175000017500000002052611361341572023136 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/UserType.java0000644000175000017500000000136311361341573022511 0ustar apoapopackage org.apache.xmlbeans; import javax.xml.namespace.QName; /** * The UserType class represents a mapping between an XML Schema QName and * a custom Java class type. It is used during code generation to determine * how to convert user-defined simple types to user defined Java classes. */ public interface UserType { /** * The QName of the simple value that will be converted to a Java class. */ QName getName(); /** * The class name the simple value will be converted to. */ String getJavaName(); /** * A class which provides public static methods to convert {@link SimpleValue} * objects to and from the Java type specified by {@link #getJavaName()}. */ String getStaticHandler(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlENTITIES.java0000644000175000017500000002153711361341573022643 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaStringEnumEntry.java0000644000175000017500000000214511361341572025165 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * Describes a code-generated string enumeration * * @see SchemaType#getStringEnumEntries */ public interface SchemaStringEnumEntry { /** * The enumerated string value */ public String getString(); /** * An integer to represent this choice in the enumeration */ public int getIntValue(); /** * A capitalized name to use for the enumeration constant name */ public String getEnumName(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/Filer.java0000644000175000017500000000253511361341573021774 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.OutputStream; import java.io.Writer; import java.io.IOException; /** * */ public interface Filer { /** * 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 IOException */ public OutputStream createBinaryFile(String typename) throws IOException; /** * 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 IOException */ public Writer createSourceFile(String typename) throws IOException; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/PrePostExtension.java0000644000175000017500000000311411361341573024216 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; public interface PrePostExtension { /** Operation code for setting a property. */ int OPERATION_SET = 1; /** Operation code for inserting a property. */ int OPERATION_INSERT = 2; /** Operation code for removing a property. */ int OPERATION_REMOVE = 3; /** * Get the fully qualified static handler class name. */ String getStaticHandler(); /** * Returns true if the static handler class has a preSet() method * with the following signature: *
* public static boolean preSet(int, org.apache.xmlbeans.XmlObject, javax.xml.namespace.QName, boolean, int}; */ boolean hasPreCall(); /** * Returns true if the static handler class has a preSet() method * with the following signature: *
* public static void postSet(int, org.apache.xmlbeans.XmlObject, javax.xml.namespace.QName, boolean, int}; */ boolean hasPostCall(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/InterfaceExtension.java0000644000175000017500000000305211361341573024523 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; public interface InterfaceExtension { /** * Get the fully qualified interface name. */ String getInterface(); /** * Get the fully qualified static handler class name. */ String getStaticHandler(); /** * Returns an array of MethodSignature declared in the interface class. * Possibly null if there is an error in the configuration. */ MethodSignature[] getMethods(); public interface MethodSignature { /** Returns the name of the method. */ String getName(); /** Returns the fully qualified type name of the return value or 'void' for no return value. */ String getReturnType(); /** Returns the fully qualified type name of the parameter types in order. */ String[] getParameterTypes(); /** Returns the fully qualified type name of the exception types. */ String[] getExceptionTypes(); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlFactoryHook.java0000644000175000017500000001132111361341572023634 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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() { } } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlError.java0000644000175000017500000005347111361341572022511 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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"); } } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlName.java0000644000175000017500000002066011361341573022273 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlENTITY.java0000644000175000017500000001775111361341572022435 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/package.html0000644000175000017500000000512011361341573022342 0ustar apoapo Provides classes for XML Beans schema, infoset, xpath, and xquery handling.

The XML Beans API is designed to work with the XML Beans schema compiler. The schema compiler produces XML Bean classes that extend and interact with the basic XML Bean classes and interfaces in this package. It is also possible to use XML Beans without the schema compiler to manipulate and validate XML in a late-bound way (with no types, or with runtime-loaded types only).

This package contains:

  1. All the built-in XML Bean classes such as {@link org.apache.xmlbeans.XmlObject}, {@link org.apache.xmlbeans.XmlAnySimpleType}, and {@link org.apache.xmlbeans.XmlInt} (one for each of the 46 built-in XML Schema types).
  2. Support for full XML infoset, XPath, and XQuery (via {@link org.apache.xmlbeans.XmlCursor}, {@link org.apache.xmlbeans.XmlObject#selectPath} and related methods).
  3. Support for computation using XML Schema data types (via datatype classes such as {@link org.apache.xmlbeans.GDuration}).
  4. Support for working with XML Schema type metadata itself (via {@link org.apache.xmlbeans.SchemaType}, {@link org.apache.xmlbeans.SchemaTypeSystem}, and related classes).

The place to begin when working with the XML Beans API is the following fundamental classes:

  1. {@link org.apache.xmlbeans.XmlObject} is the base class for all XML Beans.
  2. {@link org.apache.xmlbeans.XmlObject.Factory} is used to load and create XML Bean instances. Each XML Bean class has its own nested factory class.
  3. {@link org.apache.xmlbeans.XmlCursor} is an efficient treewalking API for the full XML infoset.
  4. {@link org.apache.xmlbeans.SchemaType} is the type metadata interface for XML Schema types
  5. {@link org.apache.xmlbeans.XmlBeans} provides a collection of utility functions.
xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java0000644000175000017500000001061211361341572024010 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 global Schema Component. That is, a type, element, attribute, * model group, attribute group, or identity constraint. *

* Note that not all types, elements, and attributes are global; local * types, element, and attributes do not appear in the global lookup table. * Also note that other information items such as particles, facets, and * so on are not globally indexed, so are not SchemaComponents. * * @see SchemaType * @see SchemaGlobalElement * @see SchemaGlobalAttribute * @see SchemaAttributeGroup * @see SchemaModelGroup * @see SchemaIdentityConstraint */ public interface SchemaComponent { /** A type definition. See {@link #getComponentType} */ static final int TYPE = 0; /** An element definition. See {@link #getComponentType} */ static final int ELEMENT = 1; /** An attribute definition. See {@link #getComponentType} */ static final int ATTRIBUTE = 3; /** An attribute group definition. See {@link #getComponentType} */ static final int ATTRIBUTE_GROUP = 4; /** An identity constraint definition. See {@link #getComponentType} */ static final int IDENTITY_CONSTRAINT = 5; /** A model group definition. See {@link #getComponentType} */ static final int MODEL_GROUP = 6; /** A notation definition. See {@link #getComponentType} */ static final int NOTATION = 7; /** An annotation. See {@link #getComponentType} */ static final int ANNOTATION = 8; /** * Returns the type code for the schema object, either {@link #TYPE}, * {@link #ELEMENT}, {@link #ATTRIBUTE}, {@link #ATTRIBUTE_GROUP}, * {@link #MODEL_GROUP}, {@link #IDENTITY_CONSTRAINT}, or {@link #NOTATION}. */ int getComponentType(); /** * Returns the typesystem within which this component definition resides */ SchemaTypeSystem getTypeSystem(); /** * The name of the schema component */ QName getName(); /** * The name of resource that represends the source .xsd in which this component was defined (if known) *
See: {@link org.apache.xmlbeans.SchemaTypeLoader#getSourceAsStream(String)} *

Example:

     *   SchemaType schemaType = ..;
     *   InputStream is = schemaType.getTypeSystem().getSourceAsStream(schemaType.getSourceName());
     * 
*/ String getSourceName(); /** * A lazy reference to a component. Used by SchemaTypeLoaders to * avoid loading components until they are actually needed. * * @exclude */ public static abstract class Ref { protected Ref(SchemaComponent schemaComponent) { _schemaComponent = schemaComponent; } protected Ref(SchemaTypeSystem schemaTypeSystem, String handle) { assert(handle != null); _schemaTypeSystem = schemaTypeSystem; _handle = handle; } private volatile SchemaComponent _schemaComponent; private SchemaTypeSystem _schemaTypeSystem; public String _handle; public abstract int getComponentType(); public final SchemaTypeSystem getTypeSystem() { return _schemaTypeSystem; } public final SchemaComponent getComponent() { if (_schemaComponent == null && _handle != null) { synchronized (this) { if (_schemaComponent == null && _handle != null) { _schemaComponent = _schemaTypeSystem.resolveHandle(_handle); _schemaTypeSystem = null; } } } return _schemaComponent; } } /** * Used for on-demand loading of schema components. */ public Ref getComponentRef(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedInt.java0000644000175000017500000002200211361341572023631 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaGlobalAttribute.java0000644000175000017500000000275511361341573025144 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * Represents a global attribute definition * * @see SchemaTypeLoader#findAttribute */ public interface SchemaGlobalAttribute extends SchemaLocalAttribute, SchemaComponent { /** * Used to allow on-demand loading of elements. * * @exclude */ public final static class Ref extends SchemaComponent.Ref { public Ref(SchemaGlobalAttribute element) { super(element); } public Ref(SchemaTypeSystem system, String handle) { super(system, handle); } public final int getComponentType() { return SchemaComponent.ATTRIBUTE; } public final SchemaGlobalAttribute get() { return (SchemaGlobalAttribute)getComponent(); } } /** * Retruns a SchemaGlobalElement.Ref pointing to this element itself. */ public Ref getRef(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlException.java0000644000175000017500000000620011361341573023343 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Collections; import java.util.Collection; import java.util.ArrayList; /** * A checked exception that can be thrown while processing, * parsing, or compiling XML. May contain any number of {@link XmlError} * objects. *

* @see XmlError * @see XmlRuntimeException */ public class XmlException extends Exception { private static final long serialVersionUID = 1L; /** * Constructs an XmlException from a message. */ public XmlException ( String m ) { super( m ); } /** * Constructs an XmlException from a message and a cause. */ public XmlException ( String m, Throwable t ) { super( m, t ); } /** * Constructs an XmlException from a cause. */ public XmlException ( Throwable t ) { super( t ); } /** * Constructs an XmlException from an {@link XmlError}. */ public XmlException ( XmlError error ) { this( error.toString(), null, error ); } /** * Constructs an XmlException from a message, a cause, and an {@link XmlError}. */ public XmlException ( String m, Throwable t, XmlError error ) { this( m, t, Collections.singletonList( error ) ); } /** * Constructs an XmlException from a message, a cause, and a collection of {@link XmlError XmlErrors}. */ public XmlException ( String m, Throwable t, Collection errors ) { super( m, t ); if (errors != null) _errors = Collections.unmodifiableList( new ArrayList( errors ) ); } /** * Constructs an XmlException from an {@link XmlRuntimeException}. */ public XmlException ( XmlRuntimeException xmlRuntimeException ) { super( xmlRuntimeException.getMessage(), xmlRuntimeException.getCause() ); Collection errors = xmlRuntimeException.getErrors(); if (errors != null) _errors = Collections.unmodifiableList( new ArrayList( errors ) ); } /** * Returns the first {@link XmlError XmlErrors} that caused the exception, if any. */ public XmlError getError ( ) { if (_errors == null || _errors.size() == 0) return null; return (XmlError) _errors.get( 0 ); } /** * Returns the collection of {@link XmlError XmlErrors} that caused the exception, if any. */ public Collection getErrors ( ) { return _errors; } private List _errors; }xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlGMonth.java0000644000175000017500000002315611361341573022612 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlErrorCodes.java0000644000175000017500000025063611714324517023473 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; public abstract class XmlErrorCodes { public static final int MISMATCHED_TARGET_NAMESPACE = 4; public static final int CANNOT_FIND_RESOURCE = 56; public static final int REDUNDANT_NESTED_TYPE = 7; public static final int ELEMENT_MISSING_NAME = 8; public static final int REDUNDANT_DEFAULT_FIXED = 9; public static final int MODEL_GROUP_MISSING_NAME = 10; public static final int ATTRIBUTE_GROUP_MISSING_NAME = 12; public static final int CYCLIC_DEPENDENCY = 13; public static final int FACET_DUPLICATED = 19; public static final int FACET_VALUE_MALFORMED = 20; public static final int MALFORMED_NUMBER = 21; public static final int REDUNDANT_CONTENT_MODEL = 26; public static final int MISSING_RESTRICTION_OR_EXTENSION = 27; public static final int MISSING_BASE = 28; public static final int ELEMENT_EXTRA_REF = 30; public static final int EXPLICIT_GROUP_NEEDED = 32; public static final int GROUP_MISSING_REF = 33; public static final int DUPLICATE_ATTRIBUTE_NAME = 37; public static final int DUPLICATE_ANY_ATTRIBUTE = 38; public static final int ATTRIBUTE_GROUP_MISSING_REF = 39; public static final int CANNOT_EXTEND_ALL = 42; public static final int INVALID_SCHEMA = 46; public static final int DUPLICATE_GLOBAL_ELEMENT = 47; public static final int DUPLICATE_GLOBAL_ATTRIBUTE = 48; public static final int DUPLICATE_GLOBAL_TYPE = 49; public static final int MALFORMED_SIMPLE_TYPE_DEFN = 52; public static final int INVALID_NAME = 53; public static final int CANNOT_DERIVE_FINAL = 54; public static final int IDC_NOT_FOUND = 55; public static final int NONDETERMINISTIC_MODEL = 57; public static final int XPATH_COMPILATION_FAILURE = 58; public static final int DUPLICATE_IDENTITY_CONSTRAINT = 59; public static final int ILLEGAL_RESTRICTION = 45; public static final int INCONSISTENT_TYPE = 50; /* general */ public static final int UNSUPPORTED_FEATURE = 51; public static final int GENERIC_ERROR = 60; // // xmlbeans errors // public static final String INVALID_DOCUMENT_TYPE = "invalid.document.type"; public static final String CANNOT_LOAD_FILE = "cannot.load.file"; public static final String EXCEPTION_EXCEEDED_ENTITY_BYTES = "exceeded-entity-bytes"; public static final String EXCEPTION_LOADING_URL = "exception.loading.url"; public static final String EXCEPTION_VALUE_NOT_SUPPORTED_J2S = "exception.value.not.supported.j2s"; public static final String EXCEPTION_VALUE_NOT_SUPPORTED_S2J = "exception.value.not.supported.s2j"; public static final String EXCEPTION_XQRL_XPATH_NOT_VALID = "exception.xqrl.xpath.not.valid"; public static final String EXCEPTION_XQRL_EXCEPTION = "exception.xqrl.exception"; // // xml errors // /** * uniqattspec: See * XML 1.0: Unique Att Spec */ public static final String XML_DUPLICATE_ATTRIBUTE = "uniqattspec"; // // schema errors // /** * cvc-assess-attr: See * XMLSchema Structures 1.0: Schema-Validity Assessment (Attribute) */ public static final String ASSESS_ATTR_SCHEMA_VALID = "cvc-assess-attr"; /** * cvc-assess-attr.1.2: See clause 1.2 of * XMLSchema Structures 1.0: Schema-Validity Assessment (Attribute) */ public static final String ASSESS_ATTR_SCHEMA_VALID$NOT_RESOLVED = "cvc-assess-attr.1.2"; /** * cvc-assess-elt: See * XMLSchema Structures 1.0: Schema-Validity Assessment (Element) */ public static final String ASSESS_ELEM_SCHEMA_VALID = "cvc-assess-elt"; /** * cvc-assess-elt.1.1.1.3.2: See clause 1.1.1.3.2 of * XMLSchema Structures 1.0: Schema-Validity Assessment (Element) */ public static final String ASSESS_ELEM_SCHEMA_VALID$NOT_RESOLVED = "cvc-assess-elt.1.1.1.3.2"; /** * cvc-attribute: See * XMLSchema Structures 1.0: Attribute Locally Valid */ public static final String ATTR_LOCALLY_VALID = "cvc-attribute"; /** * cvc-attribute.1: See clause 1 of * XMLSchema Structures 1.0: Attribute Locally Valid */ public static final String ATTR_LOCALLY_VALID$NO_TYPE = "cvc-attribute.1"; /** * cvc-attribute.4: See clause 4 of * XMLSchema Structures 1.0: Attribute Locally Valid */ public static final String ATTR_LOCALLY_VALID$FIXED = "cvc-attribute.4"; /** * cvc-au: See * XMLSchema Structures 1.0: Attribute Locally Valid (Use) */ public static final String ATTR_USE_LOCALLY_VALID = "cvc-au"; /** * cvc-complex-type: See * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID = "cvc-complex-type"; /** * cvc-complex-type.2.1: See clause 2.1 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$EMPTY_WITH_CONTENT = "cvc-complex-type.2.1"; /** * cvc-complex-type.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$SIMPLE_TYPE_WITH_CONTENT = "cvc-complex-type.2.2"; /** * cvc-complex-type.2.4a: See clause 2.4 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT = "cvc-complex-type.2.4a"; /** * cvc-complex-type.2.4b: See clause 2.4 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_NOT_ALLOWED = "cvc-complex-type.2.4b"; /** * cvc-complex-type.2.4c: See clause 2.4 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_ELEMENT = "cvc-complex-type.2.4c"; /** * cvc-complex-type.2.4d: See clause 2.4 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_ELEMENT = "cvc-complex-type.2.4d"; /** * cvc-complex-type.2.3: See clause 2.3 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_ONLY_WITH_TEXT = "cvc-complex-type.2.3"; /** * cvc-complex-type.3.1: See clause 3.1 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$ATTRIBUTE_VALID = "cvc-complex-type.3.1"; /** * cvc-complex-type.3.2.1: See clause 3.2.1 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD = "cvc-complex-type.3.2.1"; /** * cvc-complex-type.3.2.2: See clause 3.2.2 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$NOT_WILDCARD_VALID = "cvc-complex-type.3.2.2"; /** * cvc-complex-type.4: See clause 4 of * XMLSchema Structures 1.0: Element Locally Valid (Complex Type) */ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_REQUIRED_ATTRIBUTE = "cvc-complex-type.4"; /** * cvc-datatype-valid: See * XMLSchema Datatypes 1.0: Datatype Valid */ public static final String DATATYPE_VALID = "cvc-datatype-valid"; /** * cvc-datatype-valid.1.1: See clause 1.1 of * XMLSchema Datatypes 1.0: Datatype Valid */ public static final String DATATYPE_VALID$PATTERN_VALID = "cvc-datatype-valid.1.1"; /** * cvc-datatype-valid.1.1b: See clause 1.1 of * XMLSchema Datatypes 1.0: Datatype Valid */ public static final String DATATYPE_VALID$PATTERN_VALID$NO_VALUE = "cvc-datatype-valid.1.1b"; /** * cvc-datatype-valid.1.2.3: See clause 1.2.3 of * XMLSchema Datatypes 1.0: Datatype Valid */ public static final String DATATYPE_VALID$UNION = "cvc-datatype-valid.1.2.3"; /** * cvc-elt: See * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID = "cvc-elt"; /** * cvc-elt.1: See clause 1 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$NO_TYPE = "cvc-elt.1"; /** * cvc-elt.2: See clause 2 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$ABSTRACT = "cvc-elt.2"; /** * cvc-elt.3.1: See clause 3.1 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$NOT_NILLABLE = "cvc-elt.3.1"; /** * cvc-elt.3.2.1: See clause 3.2.1 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$NIL_WITH_CONTENT = "cvc-elt.3.2.1"; /** * cvc-elt.3.2.2: See clause 3.2.2 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$NIL_WITH_FIXED = "cvc-elt.3.2.2"; /** * cvc-elt.4.1: See clause 4.1 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$XSI_TYPE_INVALID_QNAME = "cvc-elt.4.1"; /** * cvc-elt.4.2: See clause 4.2 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$XSI_TYPE_NOT_FOUND = "cvc-elt.4.2"; /** * cvc-elt.4.3a: See clause 4.3 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$XSI_TYPE_NOT_DERIVED = "cvc-elt.4.3a"; /** * cvc-elt.4.3b: See clause 4.3 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$XSI_TYPE_BLOCK_EXTENSION = "cvc-elt.4.3b"; /** * cvc-elt.4.3c: See clause 4.3 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$XSI_TYPE_BLOCK_RESTRICTION = "cvc-elt.4.3c"; /** * cvc-elt.5.2.2.1: See clause 5.2.2.1 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$FIXED_WITH_CONTENT = "cvc-elt.5.2.2.1"; /** * cvc-elt.5.2.2.2.1: See clause 5.2.2.2.1 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$FIXED_VALID_MIXED_CONTENT = "cvc-elt.5.2.2.2.1"; /** * cvc-elt.5.2.2.2.2: See clause 5.2.2.2.2 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$FIXED_VALID_SIMPLE_TYPE = "cvc-elt.5.2.2.2.2"; /** * cvc-elt.4.3d: See clause 4.3 of * XMLSchema Structures 1.0: Element Locally Valid (Element) */ public static final String ELEM_LOCALLY_VALID$XSI_TYPE_PROHIBITED_SUBST = "cvc-elt.4.3d"; /** * cvc-enumeration-valid: See * XMLSchema Datatypes 1.0: enumeration valid */ public static final String DATATYPE_ENUM_VALID = "cvc-enumeration-valid"; /** * cvc-enumeration-valid.b: See * XMLSchema Datatypes 1.0: enumeration valid */ public static final String DATATYPE_ENUM_VALID$NO_VALUE = "cvc-enumeration-valid.b"; /** * cvc-facet-valid: See * XMLSchema Datatypes 1.0: Facet Valid */ public static final String DATATYPE_FACET_VALID = "cvc-facet-valid"; /** * cvc-fractionDigits-valid: See * XMLSchema Datatypes 1.0: fractionDigits Valid */ public static final String DATATYPE_FRACTION_DIGITS_VALID = "cvc-fractionDigits-valid"; /** * cvc-id.2: See clause 2 of * XMLSchema Structures 1.0: Validation Root Valid (ID/IDREF) */ public static final String ID_VALID$DUPLICATE = "cvc-id.2"; /** * cvc-identity-constraint: See * XMLSchema Structures 1.0: Identity-constraint Satisfied */ public static final String IDENTITY_CONSTRAINT_VALID = "cvc-identity-constraint"; /** * cvc-identity-constraint.4.1: See clause 4.1 of * XMLSchema Structures 1.0: Identity-constraint Satisfied */ public static final String IDENTITY_CONSTRAINT_VALID$DUPLICATE_UNIQUE = "cvc-identity-constraint.4.1"; /** * cvc-identity-constraint.4.2.2: See clause 4.2.2 * XMLSchema Structures 1.0: Identity-constraint Satisfied */ public static final String IDENTITY_CONSTRAINT_VALID$DUPLICATE_KEY = "cvc-identity-constraint.4.2.2"; /** * cvc-identity-constraint.4.3: See clause 4.3 * XMLSchema Structures 1.0: Identity-constraint Satisfied */ public static final String IDENTITY_CONSTRAINT_VALID$KEYREF_KEY_NOT_FOUND = "cvc-identity-constraint.4.3"; /** * cvc-length-valid: See * XMLSchema Datatypes 1.0: Length Valid */ public static final String DATATYPE_LENGTH_VALID = "cvc-length-valid"; /** * cvc-length-valid.1.1: See clause 1.1 of * XMLSchema Datatypes 1.0: Length Valid */ public static final String DATATYPE_LENGTH_VALID$STRING = "cvc-length-valid.1.1"; /** * cvc-length-valid.1.2: See clause 1.2 of * XMLSchema Datatypes 1.0: Length Valid */ public static final String DATATYPE_LENGTH_VALID$BINARY = "cvc-length-valid.1.2"; /** * cvc-length-valid.2: See clause 2 of * XMLSchema Datatypes 1.0: Length Valid */ public static final String DATATYPE_LENGTH_VALID$LIST_LENGTH = "cvc-length-valid.2"; /** * cvc-maxExclusive-valid: See * XMLSchema Datatypes 1.0: maxExclusive Valid */ public static final String DATATYPE_MAX_EXCLUSIVE_VALID = "cvc-maxExclusive-valid"; /** * cvc-maxInclusive-valid: See * XMLSchema Datatypes 1.0: maxInclusive Valid */ public static final String DATATYPE_MAX_INCLUSIVE_VALID = "cvc-maxInclusive-valid"; /** * cvc-maxLength-valid: See * XMLSchema Datatypes 1.0: maxLength Valid */ public static final String DATATYPE_MAX_LENGTH_VALID = "cvc-maxLength-valid"; /** * cvc-maxLength-valid.1.1: See clause 1.1 of * XMLSchema Datatypes 1.0: maxLength Valid */ public static final String DATATYPE_MAX_LENGTH_VALID$STRING = "cvc-maxLength-valid.1.1"; /** * cvc-maxLength-valid.1.2: See clause 1.2 of * XMLSchema Datatypes 1.0: maxLength Valid */ public static final String DATATYPE_MAX_LENGTH_VALID$BINARY = "cvc-maxLength-valid.1.2"; /** * cvc-maxLength-valid.2: See clause 2 of * XMLSchema Datatypes 1.0: maxLength Valid */ public static final String DATATYPE_MAX_LENGTH_VALID$LIST_LENGTH = "cvc-maxLength-valid.2"; /** * cvc-minExclusive-valid: See * XMLSchema Datatypes 1.0: minExclusive Valid */ public static final String DATATYPE_MIN_EXCLUSIVE_VALID = "cvc-minExclusive-valid"; /** * cvc-minInclusive-valid: See * XMLSchema Datatypes 1.0: minInclusive Valid */ public static final String DATATYPE_MIN_INCLUSIVE_VALID = "cvc-minInclusive-valid"; /** * cvc-minLength-valid: See * XMLSchema Datatypes 1.0: minLength Valid */ public static final String DATATYPE_MIN_LENGTH_VALID = "cvc-minLength-valid"; /** * cvc-minLength-valid.1.1: See clause 1.1 of * XMLSchema Datatypes 1.0: minLength Valid */ public static final String DATATYPE_MIN_LENGTH_VALID$STRING = "cvc-minLength-valid.1.1"; /** * cvc-minLength-valid.1.2: See clause 1.2 of * XMLSchema Datatypes 1.0: minLength Valid */ public static final String DATATYPE_MIN_LENGTH_VALID$BINARY = "cvc-minLength-valid.1.2"; /** * cvc-minLength-valid.2: See clause 2 of * XMLSchema Datatypes 1.0: minLength Valid */ public static final String DATATYPE_MIN_LENGTH_VALID$LIST_LENGTH = "cvc-minLength-valid.2"; /** * cvc-model-group: See * XMLSchema Structures 1.0: Element Sequence Valid */ public static final String MODEL_GROUP_VALID = "cvc-model-group"; /** * cvc-particle: See * XMLSchema Structures 1.0: Element Sequence Locally Valid (Particle) */ public static final String PARTICLE_VALID = "cvc-particle"; /** * cvc-particle.1.3: See * XMLSchema Structures 1.0: Element Sequence Locally Valid (Particle) */ public static final String PARTICLE_VALID$NOT_WILDCARD_VALID = "cvc-particle.1.3"; /** * cvc-particle.2.3.3a: See * XMLSchema Structures 1.0: Element Sequence Locally Valid (Particle) */ public static final String PARTICLE_VALID$BLOCK_SUBSTITUTION = "cvc-particle.2.3.3a"; /** * cvc-pattern-valid: See * XMLSchema Datatypes 1.0: pattern valid */ public static final String DATATYPE_PATTERN_VALID = "cvc-pattern-valid"; /** * cvc-resolve-instance: See * XMLSchema Structures 1.0: QName resolution (Instance) */ public static final String RESOLVE_QNAME_INSTANCE_VALID = "cvc-resolve-instance"; // KHK: ? is the name good /** * cvc-simple-type: See * XMLSchema Structures 1.0: String Valid */ public static final String SIMPLE_TYPE_STRING_VALID = "cvc-simple-type"; /** * cvc-totalDigits-valid: See * XMLSchema Datatypes 1.0: totalDigits Valid */ public static final String DATATYPE_TOTAL_DIGITS_VALID = "cvc-totalDigits-valid"; /** * cvc-type: See * XMLSchema Structures 1.0: Element Locally Valid (Type) */ public static final String ELEM_TYPE_LOCALLY_VALID = "cvc-type"; /** * cvc-type.2: See clause 2 of * XMLSchema Structures 1.0: Element Locally Valid (Type) */ public static final String ELEM_TYPE_LOCALLY_VALID$ABSTRACT = "cvc-type.2"; /** * cvc-wildcard: See * XMLSchema Structures 1.0: Item Valid (Wildcard) */ public static final String WILDCARD_ITEM_VALID = "cvc-wildcard"; /** * cvc-wildcard-namespace: See * XMLSchema Structures 1.0: Wildcard allows Namespace Name */ public static final String WILDCARD_NAMESPACE_NAME_VALID = "cvc-wildcard-namespace"; /** * schema_reference: See * XMLSchema Structures 1.0: Schema Document Location Strategy */ public static final String SCHEMA_REFERENCE = "schema_reference"; /** * src-annotation: See * XMLSchema Structures 1.0: Annotation Definition Representation OK */ public static final String SCHEMA_ANNOTATION = "src-annotation"; /** * src-attribute: See * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR = "src-attribute"; /** * src-attribute.1: See clause 1 of * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR$DEFAULT_OR_FIXED = "src-attribute.1"; /** * au-value_constraint: See description for * XMLSchema Structures 1.0: The Attribute Use Schema Component */ public static final String SCHEMA_ATTR$FIXED_NOT_MATCH = "au-value_constraint"; /** * src-attribute.2: See clause 2 of * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR$DEFAULT_AND_USE_OPTIONAL = "src-attribute.2"; /** * src-attribute.3.1a: See clause 3.1 of * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH = "src-attribute.3.1a"; /** * src-attribute.3.1b: See clause 3.1 of * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR$REF_OR_NAME_HAS_NEITHER = "src-attribute.3.1b"; /** * src-attribute.3.2: See clause 3.2 of * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR$REF_FEATURES = "src-attribute.3.2"; /** * src-attribute.4: See clause 4 of * XMLSchema Structures 1.0: Attribute Declaration Representation OK */ public static final String SCHEMA_ATTR$TYPE_ATTR_OR_NESTED_TYPE = "src-attribute.4"; /** * src-attribute_group: See * XMLSchema Structures 1.0: Attribute Group Definition Representation OK */ public static final String SCHEMA_ATTR_GROUP = "src-attribute_group"; /** * src-attribute_group.3: See clause 3 of * XMLSchema Structures 1.0: Attribute Group Definition Representation OK */ public static final String SCHEMA_ATTR_GROUP$SELF_REF = "src-attribute_group.3"; /** * src-ct: See * XMLSchema Structures 1.0: Complex Type Definition Representation OK */ public static final String SCHEMA_COMPLEX_TYPE = "src-ct"; /** * src-ct.1: See clause 1 of * XMLSchema Structures 1.0: Complex Type Definition Representation OK */ public static final String SCHEMA_COMPLEX_TYPE$COMPLEX_CONTENT = "src-ct.1"; /** * src-ct.2: See clause 2 of * XMLSchema Structures 1.0: Complex Type Definition Representation OK */ public static final String SCHEMA_COMPLEX_TYPE$SIMPLE_CONTENT = "src-ct.2"; /** * src-element: See * XMLSchema Structures 1.0: Element Declaration Representation OK */ public static final String SCHEMA_ELEM = "src-element"; /** * src-element.1: See clause 1 of * XMLSchema Structures 1.0: Element Declaration Representation OK */ public static final String SCHEMA_ELEM$DEFAULT_OR_FIXED = "src-element.1"; /** * src-element.2.1a: See clause 2.1 of * XMLSchema Structures 1.0: Element Declaration Representation OK */ public static final String SCHEMA_ELEM$REF_OR_NAME_HAS_BOTH = "src-element.2.1a"; /** * src-element.2.1b: See clause 2.1 of * XMLSchema Structures 1.0: Element Declaration Representation OK */ public static final String SCHEMA_ELEM$REF_OR_NAME_HAS_NEITHER = "src-element.2.1b"; /** * src-element.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Element Declaration Representation OK */ public static final String SCHEMA_ELEM$REF_FEATURES = "src-element.2.2"; /** * src-element.3: See clause 3 of * XMLSchema Structures 1.0: Element Declaration Representation OK */ public static final String SCHEMA_ELEM$TYPE_ATTR_OR_NESTED_TYPE = "src-element.3"; /** * src-expredef: See * XMLSchema Structures 1.0: Individual Component Redefinition */ public static final String SCHEMA_REDEFINITION = "src-expredef"; /** * src-identity-constraint: See * XMLSchema Structures 1.0: Identity-constraint Definition Representation OK */ public static final String SCHEMA_IDENTITY_CONSTRAINT = "src-identity-constraint"; /** * src-import: See * XMLSchema Structures 1.0: Import Constraints and Semantics */ public static final String SCHEMA_IMPORT = "src-import"; /** * src-include: See * XMLSchema Structures 1.0: Inclusion Constraints and Semantics */ public static final String SCHEMA_INCLUDE = "src-include"; /** * src-list-itemType-or-simpleType: See * XMLSchema Datatypes 1.0: itemType attribute or simpleType child */ public static final String SCHEMA_SIMPLE_TYPE$LIST_ITEM_TYPE_OR_SIMPLE_TYPE = "src-list-itemType-or-simpleType"; /** * src-model_group: See * XMLSchema Structures 1.0: Model Group Representation OK */ public static final String SCHEMA_MODEL_GROUP = "src-model_group"; /** * src-model_group_defn: See * XMLSchema Structures 1.0: Model Group Definition Representation OK */ public static final String SCHEMA_MODEL_GROUP_DEFN = "src-model_group_defn"; /** * src-multiple-enumerations: See * XMLSchema Datatypes 1.0: Multiple enumerations */ public static final String SCHEMA_MULTIPLE_ENUMS = "src-multiple-enumerations"; /** * src-multiple-patterns: See * XMLSchema Datatypes 1.0: Multiple patterns */ public static final String SCHEMA_MULTIPLE_PATTERNS = "src-multiple-patterns"; /** * src-notation: See * XMLSchema Structures 1.0: Notation Definition Representation OK */ public static final String SCHEMA_NOTATION = "src-notation"; /** * src-qname: See * XMLSchema Structures 1.0: QName Interpretation */ public static final String SCHEMA_QNAME = "src-qname"; /** * src-redefine: See * XMLSchema Structures 1.0: Redefinition Constraints and Semantics */ public static final String SCHEMA_REDEFINE = "src-redefine"; /** * src-redefine.5a: See clause 5 of * XMLSchema Structures 1.0: Redefinition Constraints and Semantics */ public static final String SCHEMA_REDEFINE$EXTEND_OR_RESTRICT = "src-redefine.5a"; /** * src-redefine.5b: See clause 5 of * XMLSchema Structures 1.0: Redefinition Constraints and Semantics */ public static final String SCHEMA_REDEFINE$SAME_TYPE = "src-redefine.5b"; /** * src-redefine.6.1.1: See clause 6.1.1 of * XMLSchema Structures 1.0: Redefinition Constraints and Semantics */ public static final String SCHEMA_REDEFINE$GROUP_SELF_REF = "src-redefine.6.1.1"; /** * src-redefine.6.1.2: See clause 6.1.2 of * XMLSchema Structures 1.0: Redefinition Constraints and Semantics */ public static final String SCHEMA_REDEFINE$GROUP_SELF_REF_MIN_MAX_1 = "src-redefine.6.1.2"; /** * src-redefine.7.1: See clause 7.1 of * XMLSchema Structures 1.0: Redefinition Constraints and Semantics */ public static final String SCHEMA_REDEFINE$ATTR_GROUP_SELF_REF = "src-redefine.7.1"; /** * src-resolve: See * XMLSchema Structures 1.0: QName resolution (Schema Document) */ public static final String SCHEMA_QNAME_RESOLVE = "src-resolve"; /** * src-resolve: See * XMLSchema Structures 1.0: QName resolution (Schema Document) */ public static final String SCHEMA_QNAME_RESOLVE$HELP = "src-resolve.a"; /** * src-restriction-base-or-simpleType: See * XMLSchema Datatypes 1.0: base attribute or simpleType child */ public static final String SCHEMA_SIMPLE_TYPE$RESTICTION_HAS_BASE_OR_SIMPLE_TYPE = "src-restriction-base-or-simpleType"; /** * src-simple-type: See * XMLSchema Structures 1.0: Simple Type Definition Representation OK */ public static final String SCHEMA_SIMPLE_TYPE = "src-simple-type"; /** * src-simple-type.2a: See clause 2 of * XMLSchema Structures 1.0: Simple Type Definition Representation OK */ public static final String SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_BOTH_BASE_OR_SIMPLE_TYPE = "src-simple-type.2a"; /** * src-simple-type.2b: See clause 2 of * XMLSchema Structures 1.0: Simple Type Definition Representation OK */ public static final String SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_NEITHER_BASE_OR_SIMPLE_TYPE = "src-simple-type.2b"; /** * src-simple-type.3a: See clause 3 of * XMLSchema Structures 1.0: Simple Type Definition Representation OK */ public static final String SCHEMA_SIMPLE_TYPE$LIST_HAS_BOTH_ITEM_OR_SIMPLE_TYPE = "src-simple-type.3a"; /** * src-simple-type.3b: See clause 3 of * XMLSchema Structures 1.0: Simple Type Definition Representation OK */ public static final String SCHEMA_SIMPLE_TYPE$LIST_HAS_NEITHER_ITEM_OR_SIMPLE_TYPE = "src-simple-type.3b"; /** * src-simple-type.4: See clause 4 of * XMLSchema Structures 1.0: Simple Type Definition Representation OK */ public static final String SCHEMA_SIMPLE_TYPE$CYCLIC_UNION = "src-simple-type.4"; /** * src-single-facet-value: See * XMLSchema Datatypes 1.0: Single Facet Value */ public static final String DATATYPE_SINGLE_FACET_VALUE = "src-single-facet-value"; /** * src-union-memberTypes-or-simpleTypes: See * XMLSchema Datatypes 1.0: memberTypes attribute or simpleType children */ public static final String SCHEMA_SIMPLE_TYPE$UNION_HAS_MEMBER_TYPES_OR_SIMPLE_TYPES = "src-union-memberTypes-or-simpleTypes"; /** * src-wildcard: See * XMLSchema Structures 1.0: Wildcard Representation OK */ public static final String SCHEMA_WILDCARD = "src-wildcard"; /** * a-props-correct: See * XMLSchema Structures 1.0: Attribute Declaration Properties Correct */ public static final String ATTR_PROPERTIES = "a-props-correct"; /** * a-props-correct.2: See clause 2 of * XMLSchema Spec: Attribute Declaration Properties */ public static final String ATTR_PROPERTIES$CONSTRAINT_VALID = "a-props-correct.2"; /** * a-props-correct.3: See clause 3 of * XMLSchema Spec: Attribute Declaration Properties */ public static final String ATTR_PROPERTIES$ID_FIXED_OR_DEFAULT = "a-props-correct.3"; /** * ag-props-correct: See * XMLSchema Structures 1.0: Attribute Group Definition Properties Correct */ public static final String ATTR_GROUP_PROPERTIES = "ag-props-correct"; /** * ag-props-correct.2: See clause 2 of * XMLSchema Structures 1.0: Attribute Group Definition Properties Correct */ public static final String ATTR_GROUP_PROPERTIES$2 = "ag-props-correct.2"; /** * ag-props-correct.3: See clause 3 of * XMLSchema Structures 1.0: Attribute Group Definition Properties Correct */ public static final String ATTR_GROUP_PROPERTIES$TWO_IDS = "ag-props-correct.3"; /** * an-props-correct: See * XMLSchema Structures 1.0: Annotation Correct */ public static final String ANNO_PROPERTIES = "an-props-correct"; /** * au-props-correct: See * XMLSchema Structures 1.0: Attribute Use Correct */ public static final String ATTR_USE_PROPERTIES = "au-props-correct"; /** * c-fields-xpaths: See * XMLSchema Structures 1.0: Fields Value OK */ public static final String FIELDS_XPATH = "c-fields-xpaths"; /** * c-props-correct: See * XMLSchema Structures 1.0: Identity-constraint Definition Properties Correct */ public static final String IDENTITY_CONSTRAINT_PROPERTIES = "c-props-correct"; /** * c-props-correct.1: See clause 1 of * XMLSchema Structures 1.0: Identity-constraint Definition Properties Correct */ public static final String IDENTITY_CONSTRAINT_PROPERTIES$KEYREF_REFERS_TO_KEYREF = "c-props-correct.1"; /** * c-props-correct.2: See clause 2 of * XMLSchema Structures 1.0: Identity-constraint Definition Properties Correct */ public static final String IDENTITY_CONSTRAINT_PROPERTIES$KEY_KEYREF_FIELD_COUNT_EQ = "c-props-correct.2"; /** * c-selector-xpath: See * XMLSchema Structures 1.0: Selector Value OK */ public static final String SELECTOR_XPATH = "c-selector-xpath"; /** * cos-all-limited: See * XMLSchema Structures 1.0: All Group Limited */ public static final String ALL_GROUP_LIMITED = "cos-all-limited"; /** * cos-all-limited.1.2a: See clause 1.2 of * XMLSchema Structures 1.0: All Group Limited */ public static final String ALL_GROUP_LIMITED$IN_MIN_MAX_1_PARTICLE = "cos-all-limited.1.2a"; /** * cos-all-limited.1.2b: See clause 1.2 of * XMLSchema Structures 1.0: All Group Limited */ public static final String ALL_GROUP_LIMITED$IN_COMPLEX_TYPE_DEF_PARTICLE = "cos-all-limited.1.2b"; /** * cos-all-limited.2: See clause 2 of * XMLSchema Structures 1.0: All Group Limited */ public static final String ALL_GROUP_LIMITED$CHILD_PARTICLES_MAX_LTE_1 = "cos-all-limited.2"; /** * cos-applicable-facets: See * XMLSchema Datatypes 1.0: applicable facets */ public static final String FACETS_APPLICABLE = "cos-applicable-facets"; // KHK: name ok? /** * notation-facets: See * http://www.w3.org/TR/xmlschema-2/#NOTATION-facets */ public static final String FACETS_DEPRECATED_NOTATION = "notation-facets"; /** * cos-aw-intersect: See * XMLSchema Structures 1.0: Attribute Wildcard Intersection */ public static final String ATTR_WILDCARD_INTERSECT = "cos-aw-intersect"; /** * cos-aw-union: See * XMLSchema Structures 1.0: Attribute Wildcard Union */ public static final String ATTR_WILDCARD_UNION = "cos-aw-union"; /** * enumeration-required-notation: See * XMLSchema Datatypes 1.0: Schema Component Constraint: enumeration facet value required for NOTATION */ public static final String ATTR_NOTATION_TYPE_FORBIDDEN = "enumeration-required-notation-attr"; /** * XMLSchema Datatypes 1.0: Definition of type NOTATION */ public static final String ATTR_COMPATIBILITY_TARGETNS = "notation-targetns-attr"; /** * cos-choice-range: See * XMLSchema Structures 1.0: Effective Total Range (choice) */ public static final String CHOICE_RANGE = "cos-choice-range"; /** * cos-ct-derived-ok: See * XMLSchema Structures 1.0: Type Derivation OK (Complex) */ public static final String COMPLEX_TYPE_DERIVATION = "cos-ct-derived-ok"; /** * cos-ct-extends: See * XMLSchema Structures 1.0: Derivation Valid (Extension) */ public static final String COMPLEX_TYPE_EXTENSION = "cos-ct-extends"; /** * cos-ct-extends.1.4.1: See clause 1.4.1 of * XMLSchema Structures 1.0: Derivation Valid (Extension) */ public static final String COMPLEX_TYPE_EXTENSION$EXTENDING_SIMPLE_CONTENT = "cos-ct-extends.1.4.1"; /** * cos-ct-extends.1.4.2.2: See clause 1.4.2.2 of * XMLSchema Structures 1.0: Derivation Valid (Extension) */ public static final String COMPLEX_TYPE_EXTENSION$BOTH_ELEMEMENT_OR_MIXED = "cos-ct-extends.1.4.2.2"; /** * derivation-ok-restriction.1.1: See clause 1.1 of * XMLSchema Structures 1.0: Derivation Valid (Extension) */ public static final String COMPLEX_TYPE_EXTENSION$FINAL = "cos-ct-extends.1.1"; /** * cos-element-consistant: See * XMLSchema Structures 1.0: Element Declarations Consistent */ public static final String ELEM_CONSISTANT = "cos-element-consistent"; /** * cos-equiv-class: See * XMLSchema Structures 1.0: Substitution Group */ public static final String SUBST_GROUP = "cos-equiv-class"; /** * cos-equiv-derived-ok-rec: See * XMLSchema Structures 1.0: Substitution Group OK (Transitive) */ public static final String SUBST_GROUP_DERIVED = "cos-equiv-derived-ok-rec"; /** * cos-group-emptiable: See * XMLSchema Structures 1.0: Particle Emptiable */ public static final String PARTICLE_EMPTIABLE = "cos-group-emptiable"; /** * cos-list-of-atomic: See * XMLSchema Datatypes 1.0: list of atomic */ public static final String DATATYPE_LIST_OF_ATOMIC = "cos-list-of-atomic"; /** * cos-no-circular-unions: See * XMLSchema Datatypes 1.0: no circular unions */ public static final String DATATYPE_CIRCULAR_UNION = "cos-no-circular-unions"; /** * cos-nonambig: See * XMLSchema Structures 1.0: Unique Particle Attribution */ public static final String UNIQUE_PARTICLE_ATTRIBUTION = "cos-nonambig"; /** * cos-ns-subset: See * XMLSchema Structures 1.0: Wildcard Subset */ public static final String WILDCARD_SUBSET = "cos-ns-subset"; /** * cos-particle-extend: See * XMLSchema Structures 1.0: Particle Valid (Extension) */ public static final String PARTICLE_EXTENSION = "cos-particle-extend"; /** * cos-particle-restrict: See * XMLSchema Structures 1.0: Particle Valid (Restriction) */ public static final String PARTICLE_RESTRICTION = "cos-particle-restrict"; /** * cos-particle-restrict.2: See clause 2 of * XMLSchema Structures 1.0: Particle Valid (Restriction) */ public static final String PARTICLE_RESTRICTION$INVALID_RESTRICTION = "cos-particle-restrict.2"; /** * cos-seq-range: See * XMLSchema Structures 1.0: Effective Total Range (all and sequence) */ public static final String SEQUENCE_RANGE = "cos-seq-range"; /** * cos-st-derived-ok: See * XMLSchema Structures 1.0: Type Derivation OK (Simple) */ public static final String SIMPLE_TYPE_DERIVATION = "cos-st-derived-ok"; /** * cos-st-restricts: See * XMLSchema Structures 1.0: Derivation Valid (Restriction, Simple) */ public static final String SIMPLE_TYPE_RESTRICTION = "cos-st-restricts"; /** * cos-st-restricts.1.1: See clause 1.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Simple) */ public static final String SIMPLE_TYPE_RESTRICTION$ATOMIC_NOT_SIMPLE = "cos-st-restricts.1.1"; /** * cos-st-restricts.2.1a: See clause 2.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Simple) */ public static final String SIMPLE_TYPE_RESTRICTION$LIST_ITEM_NOT_SIMPLE = "cos-st-restricts.2.1a"; /** * cos-st-restricts.2.1a: See clause 2.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Simple) */ public static final String SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_LIST = "cos-st-restricts.2.1b"; /** * cos-st-restricts.2.1a: See clause 2.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Simple) */ public static final String SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_UNION_OF_LIST = "cos-st-restricts.2.1c"; /** * cos-st-restricts.3.1: See clause 3.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Simple) */ public static final String SIMPLE_TYPE_RESTRICTION$UNION_MEMBER_NOT_SIMPLE = "cos-st-restricts.3.1"; /** * cos-valid-default: See * XMLSchema Structures 1.0: Element Default Valid (Immediate) */ public static final String ELEM_DEFAULT_VALID = "cos-valid-default"; /** * cos-valid-default.2.1: See clause 2.1 of * XMLSchema Structures 1.0: Element Default Valid (Immediate) */ public static final String ELEM_DEFAULT_VALID$SIMPLE_TYPE_OR_MIXED = "cos-valid-default.2.1"; /** * cos-valid-default.2.2.2: See clause 2.2.2 of * XMLSchema Structures 1.0: Element Default Valid (Immediate) */ public static final String ELEM_DEFAULT_VALID$MIXED_AND_EMPTIABLE = "cos-valid-default.2.2.2"; /** * XMLSchema Datatypes 1.0: Definitions of types ID, IDREF, IDREFS, ENTITY, ENTITIES, NOTATION */ public static final String ELEM_COMPATIBILITY_TYPE = "id-idref-idrefs-entity-entities-notation"; /** * XMLSchema Datatypes 1.0: Definition of type NOTATION */ public static final String ELEM_COMPATIBILITY_TARGETNS = "notation-targetns-elem"; /** * ct-props-correct: See * XMLSchema Structures 1.0: Complex Type Definition Properties Correct */ public static final String COMPLEX_TYPE_PROPERTIES = "ct-props-correct"; /** * ct-props-correct.2: See clause 2 of * XMLSchema Structures 1.0: Complex Type Definition Properties Correct */ public static final String COMPLEX_TYPE_PROPERTIES$SIMPLE_TYPE_EXTENSION = "ct-props-correct.2"; /** * ct-props-correct.4: See clause 4 of * XMLSchema Structures 1.0: Complex Type Definition Properties Correct */ public static final String COMPLEX_TYPE_PROPERTIES$DUPLICATE_ATTRIBUTE = "ct-props-correct.4"; /** * derivation-ok-restriction: See * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION = "derivation-ok-restriction"; /** * derivation-ok-restriction.1: See clause 1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$FINAL = "derivation-ok-restriction.1"; /** * derivation-ok-restriction.2.1.1: See clause 2.1.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ATTR_REQUIRED = "derivation-ok-restriction.2.1.1"; /** * derivation-ok-restriction.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ATTR_IN_BASE_WILDCARD_SET = "derivation-ok-restriction.2.2"; /** * derivation-ok-restriction.4.1: See clause 4.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$BASE_HAS_ATTR_WILDCARD = "derivation-ok-restriction.4.1"; /** * derivation-ok-restriction.4.2: See clause 4.2 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ATTR_WILDCARD_SUBSET = "derivation-ok-restriction.4.2"; /** * derivation-ok-restriction.5.1: See clause 5.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$SC_AND_SIMPLE_TYPE_OR_MIXED = "derivation-ok-restriction.5.1"; /** * derivation-ok-restriction.5.1.2: See clause 5.1.2 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$SC_AND_MIXED_EMPTIABLE = "derivation-ok-restriction.5.1.2"; /** * derivation-ok-restriction.5.2.2.1: See clause 5.2.2.1 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$SC_NOT_DERIVED = "derivation-ok-restriction.5.2.2.1"; /** * derivation-ok-restriction.5.2: See clause 5.2 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$EMPTY_AND_NOT_SIMPLE = "derivation-ok-restriction.5.2"; /** * derivation-ok-restriction.5.2.2: See clause 5.2.2 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$EMPTY_AND_ELEMENT_OR_MIXED_EMPTIABLE = "derivation-ok-restriction.5.2.2"; /** * derivation-ok-restriction.5.3: See clause 5.3 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_VALID = "derivation-ok-restriction.5.3"; /** * derivation-ok-restriction.5.3a: See clause 5.3 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_MIXED = "derivation-ok-restriction.5.3a"; /** * derivation-ok-restriction.5.3b: See clause 5.3 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_EMPTY = "derivation-ok-restriction.5.3b"; /** * derivation-ok-restriction.5.3c: See clause 5.3 of * XMLSchema Structures 1.0: Derivation Valid (Restriction, Complex) */ public static final String COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_SIMPLE = "derivation-ok-restriction.5.3c"; /** * e-props-correct: See * XMLSchema Structures 1.0: Element Declaration Properties Correct */ public static final String ELEM_PROPERTIES = "e-props-correct"; /** * e-props-correct.2: See clause 2 of * XMLSchema Structures 1.0: Element Declaration Properties Correct */ public static final String ELEM_PROPERTIES$CONSTRAINT_VALID = "e-props-correct.2"; /** * e-props-correct.4: See clause 4 of * XMLSchema Structures 1.0: Element Declaration Properties Correct */ public static final String ELEM_PROPERTIES$SUBSTITUTION_VALID = "e-props-correct.4"; /** * e-props-correct.4a: See clause 4 of * XMLSchema Structures 1.0: Element Declaration Properties Correct */ public static final String ELEM_PROPERTIES$SUBSTITUTION_FINAL = "e-props-correct.4a"; /** * enumeration-required-notation: See * XMLSchema Datatypes 1.0: Schema Component Constraint: enumeration facet value required for NOTATION */ public static final String ELEM_NOTATION_TYPE_FORBIDDEN = "enumeration-required-notation-elem"; /** * enumeration-required-notation: See * XMLSchema Datatypes 1.0: enumeration facet value required for NOTATION */ public static final String DATATYPE_ENUM_NOTATION = "enumeration-required-notation"; /** * enumeration-valid-restriction: See * XMLSchema Datatypes 1.0: enumeration valid restriction */ public static final String DATATYPE_ENUM_RESTRICTION = "enumeration-valid-restriction"; /** * fractionDigits-totalDigits: See * XMLSchema Datatypes 1.0: fractionDigits less than or equal to totalDigits */ public static final String DATATYPE_FRACTION_DIGITS_LE_TOTAL_DIGITS = "fractionDigits-totalDigits"; /** * fractionDigits-valid-restriction: See * XMLSchema Datatypes 1.0: fractionDigits valid restriction */ public static final String DATATYPE_FRACTION_DIGITS_RESTRICTION = "fractionDigits-valid-restriction"; /** * length-minLength-maxLength: See * XMLSchema Datatypes 1.0: length and minLength or maxLength */ public static final String DATATYPE_LENGTH = "length-minLength-maxLength"; /** * length-valid-restriction: See * XMLSchema Datatypes 1.0: length valid restriction */ public static final String DATATYPE_LENGTH_RESTRICTION = "length-valid-restriction"; /** * maxExclusive-valid-restriction: See * XMLSchema Datatypes 1.0: maxExclusive valid restriction */ public static final String DATATYPE_MAX_EXCLUSIVE_RESTRICTION = "maxExclusive-valid-restriction"; /** * maxInclusive-maxExclusive: See * XMLSchema Datatypes 1.0: maxInclusive and maxExclusive */ public static final String DATATYPE_MIN_INCLUSIVE_MAX_EXCLUSIVE = "maxInclusive-maxExclusive"; /** * maxInclusive-valid-restriction: See * XMLSchema Datatypes 1.0: maxInclusive valid restriction */ public static final String DATATYPE_MAX_INCLUSIVE_RESTRICTION = "maxInclusive-valid-restriction"; /** * maxLength-valid-restriction: See * XMLSchema Datatypes 1.0: maxLength valid restriction */ public static final String DATATYPE_MAX_LENGTH_RESTRICTION = "maxLength-valid-restriction"; /** * mg-props-correct: See * XMLSchema Structures 1.0: Model Group Correct */ public static final String MODEL_GROUP_PROPERTIES = "mg-props-correct"; /** * mg-props-correct.2: See clause 2 of * XMLSchema Structures 1.0: Model Group Correct */ public static final String MODEL_GROUP_PROPERTIES$CIRCULAR = "mg-props-correct.2"; /** * mgd-props-correct: See * XMLSchema Structures 1.0: Model Group Definition Properties Correct */ public static final String MODEL_GROUP_DEFN_PROPERTIES = "mgd-props-correct"; /** * minExclusive-less-than-equal-to-maxExclusive: See * XMLSchema Datatypes 1.0: minExclusive <= maxExclusive */ public static final String DATATYPE_MIN_EXCLUSIVE_LE_MAX_EXCLUSIVE = "minExclusive-less-than-equal-to-maxExclusive"; /** * minExclusive-less-than-maxInclusive: See * XMLSchema Datatypes 1.0: minExclusive < maxInclusive */ public static final String DATATYPE_MIN_EXCLUSIVE_LE_MAX_INCLUSIVE = "minExclusive-less-than-maxInclusive"; /** * minExclusive-valid-restriction: See * XMLSchema Datatypes 1.0: minExclusive valid restriction */ public static final String DATATYPE_MIN_EXCLUSIVE_RESTRICTION = "minExclusive-valid-restriction"; /** * minInclusive-less-than-equal-to-maxInclusive: See * XMLSchema Datatypes 1.0: minInclusive <= maxInclusive */ public static final String DATATYPE_MIN_INCLUSIVE_LTE_MAX_INCLUSIVE = "minInclusive-less-than-equal-to-maxInclusive"; /** * minInclusive-less-than-maxExclusive: See * XMLSchema Datatypes 1.0: minInclusive < maxExclusive */ public static final String DATATYPE_MIN_INCLUSIVE_LE_MAX_EXCLUSIVE = "minInclusive-less-than-maxExclusive"; /** * minInclusive-minExclusive: See * XMLSchema Datatypes 1.0: minInclusive and minExclusive */ public static final String DATATYPE_MIN_INCLUSIVE_MIN_EXCLUSIVE = "minInclusive-minExclusive"; /** * minInclusive-valid-restriction: See * XMLSchema Datatypes 1.0: minInclusive valid restriction */ public static final String DATATYPE_MIN_INCLUSIVE_RESTRICTION = "minInclusive-valid-restriction"; /** * minLength-less-than-equal-to-maxLength: See * XMLSchema Datatypes 1.0: minLength <= maxLength */ public static final String DATATYPE_MIN_LENGTH_LE_MAX_LENGTH = "minLength-less-than-equal-to-maxLength"; /** * minLength-valid-restriction: See * XMLSchema Datatypes 1.0: minLength valid restriction */ public static final String DATATYPE_MIN_LENGTH_RESTRICTION = "minLength-valid-restriction"; /** * n-props-correct: See * XMLSchema Structures 1.0: Notation Declaration Correct */ public static final String NOTATION_PROPERTIES = "n-props-correct"; /** * no-xmlns: See * XMLSchema Structures 1.0: xmlns Not Allowed */ public static final String NO_XMLNS = "no-xmlns"; /** * no-xsi: See * XMLSchema Structures 1.0: xsi: Not Allowed */ public static final String NO_XSI = "no-xsi"; /** * p-props-correct: See * XMLSchema Structures 1.0: Particle Correct */ public static final String PARTICLE_PROPERTIES = "p-props-correct"; /** * p-props-correct.2.1: See clause 2.1 of * XMLSchema Structures 1.0: Particle Correct */ public static final String PARTICLE_PROPERTIES$MIN_LTE_MAX = "p-props-correct.2.1"; /** * p-props-correct.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Particle Correct */ public static final String PARTICLE_PROPERTIES$MAX_GTE_1 = "p-props-correct.2.2"; /** * range-ok: See * XMLSchema Structures 1.0: Occurrence Range OK */ public static final String OCCURRENCE_RANGE = "range-ok"; /** * range-ok.1: See clause 1 of * XMLSchema Structures 1.0: Occurrence Range OK */ public static final String OCCURRENCE_RANGE$MIN_GTE_MIN = "range-ok.1"; /** * range-ok.2: See clause 2 of * XMLSchema Structures 1.0: Occurrence Range OK */ public static final String OCCURRENCE_RANGE$MAX_LTE_MAX = "range-ok.2"; /** * rcase-MapAndSum: See * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:Choice -- MapAndSum) */ public static final String PARTICLE_DERIVATION_MAP_AND_SUM = "rcase-MapAndSum"; /** * rcase-MapAndSum.1: See clause 1 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:Choice -- MapAndSum) */ public static final String PARTICLE_DERIVATION_MAP_AND_SUM$MAP = "rcase-MapAndSum.1"; /** * rcase-MapAndSum.2a: See clause 2 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:Choice -- MapAndSum) */ public static final String PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MIN_OCCURS_GTE_MIN_OCCURS = "rcase-MapAndSum.2a"; /** * rcase-MapAndSum.2b: See clause 2 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:Choice -- MapAndSum) */ public static final String PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MAX_OCCURS_LTE_MAX_OCCURS = "rcase-MapAndSum.2b"; /** * rcase-NameAndTypeOK: See * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE = "rcase-NameAndTypeOK"; /** * rcase-NameAndTypeOK.1: See clause 1 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$NAME = "rcase-NameAndTypeOK.1"; /** * rcase-NameAndTypeOK.2: See clause 2 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$NILLABLE = "rcase-NameAndTypeOK.2"; /** * rcase-NameAndTypeOK.3: See clause 3 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ //public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$NAME = "rcase-NameAndTypeOK.3"; /** * rcase-NameAndTypeOK.4: See clause 4 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$FIXED = "rcase-NameAndTypeOK.4"; /** * rcase-NameAndTypeOK.5: See clause 5 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$IDENTITY_CONSTRAINTS = "rcase-NameAndTypeOK.5"; /** * rcase-NameAndTypeOK.6: See clause 6 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS = "rcase-NameAndTypeOK.6"; /** * rcase-NameAndTypeOK.7a: See clause 7 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$TYPE_VALID = "rcase-NameAndTypeOK.7a"; /** * rcase-NameAndTypeOK.7b: See clause 7 of * XMLSchema Structures 1.0: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) */ public static final String PARTICLE_RESTRICTION_NAME_AND_TYPE$TYPE_RESTRICTED = "rcase-NameAndTypeOK.7b"; /** * rcase-NSCompat: See * XMLSchema Structures 1.0: Particle Derivation OK (Elt:Any -- NSCompat) */ public static final String PARTICLE_DERIVATION_NS_COMPAT = "rcase-NSCompat"; /** * rcase-NSCompat.1: See clause 1 of * XMLSchema Structures 1.0: Particle Derivation OK (Elt:Any -- NSCompat) */ public static final String PARTICLE_DERIVATION_NS_COMPAT$WILDCARD_VALID = "rcase-NSCompat.1"; /** * rcase-NSRecurseCheckCardinality: See * XMLSchema Structures 1.0: Particle Derivation OK (All/Choice/Sequence:Any -- NSRecurseCheckCardinality) */ public static final String PARTICLE_DERIVATION_NS_RECURSE = "rcase-NSRecurseCheckCardinality"; /** * rcase-NSSubset: See * XMLSchema Structures 1.0: Particle Derivation OK (Any:Any -- NSSubset) */ public static final String PARTICLE_DERIVATION_NS_SUBST = "rcase-NSSubset"; /** * rcase-NSSubset.2: See clause 2 of * XMLSchema Structures 1.0: Particle Derivation OK (Any:Any -- NSSubset) */ public static final String PARTICLE_DERIVATION_NS_SUBST$WILDCARD_SUBSET = "rcase-NSSubset.2"; /** * rcase-Recurse: See * XMLSchema Structures 1.0: Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) */ public static final String PARTICLE_DERIVATION_RECURSE = "rcase-Recurse"; /** * rcase-Recurse.2: See clause 2 of * XMLSchema Structures 1.0: Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) */ public static final String PARTICLE_DERIVATION_RECURSE$MAP = "rcase-Recurse.2"; /** * rcase-Recurse.2.1: See clause 2.1 of * XMLSchema Structures 1.0: Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) */ public static final String PARTICLE_DERIVATION_RECURSE$MAP_VALID = "rcase-Recurse.2.1"; /** * rcase-Recurse.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) */ public static final String PARTICLE_DERIVATION_RECURSE$UNMAPPED_ARE_EMPTIABLE = "rcase-Recurse.2.2"; /** * rcase-RecurseAsIfGroup: See * XMLSchema Structures 1.0: Particle Derivation OK (Elt:All/Choice/Sequence -- RecurseAsIfGroup) */ public static final String PARTICLE_DERIVATION_RECURSE_GROUP = "rcase-RecurseAsIfGroup"; /** * rcase-RecurseLax: See * XMLSchema Structures 1.0: Particle Derivation OK (Choice:Choice -- RecurseLax) */ public static final String PARTICLE_DERIVATION_RECURSE_LAX = "rcase-RecurseLax"; /** * rcase-RecurseLax.2: See clause 2 of * XMLSchema Structures 1.0: Particle Derivation OK (Choice:Choice -- RecurseLax) */ public static final String PARTICLE_DERIVATION_RECURSE_LAX$MAP = "rcase-RecurseLax.2"; /** * rcase-RecurseUnordered: See * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:All -- RecurseUnordered) */ public static final String PARTICLE_DERIVATION_RECURSE_UNORDERED = "rcase-RecurseUnordered"; /** * rcase-RecurseUnordered.2: See clause 2 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:All -- RecurseUnordered) */ public static final String PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP = "rcase-RecurseUnordered.2"; /** * rcase-RecurseUnordered.2.1: See clause 2.1 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:All -- RecurseUnordered) */ public static final String PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_UNIQUE = "rcase-RecurseUnordered.2.1"; /** * rcase-RecurseUnordered.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:All -- RecurseUnordered) */ public static final String PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_VALID = "rcase-RecurseUnordered.2.2"; /** * rcase-RecurseUnordered.2.2: See clause 2.2 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:All -- RecurseUnordered) */ public static final String PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_MAX_OCCURS_1 = "rcase-RecurseUnordered.2.2a"; /** * rcase-RecurseUnordered.2.3: See clause 2.3 of * XMLSchema Structures 1.0: Particle Derivation OK (Sequence:All -- RecurseUnordered) */ public static final String PARTICLE_DERIVATION_RECURSE_UNORDERED$UNMAPPED_ARE_EMPTIABLE = "rcase-RecurseUnordered.2.3"; /** * sch-props-correct: See * XMLSchema Structures 1.0: Schema Properties Correct */ public static final String SCHEMA_PROPERTIES = "sch-props-correct"; /** * sch-props-correct.2: See clause 2 of * XMLSchema Structures 1.0: Schema Properties Correct */ public static final String SCHEMA_PROPERTIES$DUPLICATE = "sch-props-correct.2"; /** * st-props-correct: See * XMLSchema Structures 1.0: Simple Type Definition Properties Correct */ public static final String SIMPLE_TYPE_PROPERTIES = "st-props-correct"; /** * st-props-correct.3: See clause 3 of * XMLSchema Structures 1.0: Simple Type Definition Properties Correct */ public static final String SIMPLE_TYPE_PROPERTIES$RESTRICTION_FINAL = "st-props-correct.3"; /** * st-props-correct.4.2.1: See clause 4.2.1 of * XMLSchema Structures 1.0: Simple Type Definition Properties Correct */ public static final String SIMPLE_TYPE_PROPERTIES$LIST_FINAL = "st-props-correct.4.2.1"; /** * st-props-correct.4.2.2: See clause 4.2.2 of * XMLSchema Structures 1.0: Simple Type Definition Properties Correct */ public static final String SIMPLE_TYPE_PROPERTIES$UNION_FINAL = "st-props-correct.4.2.2"; /** * st-restrict-facets: See * XMLSchema Structures 1.0: Simple Type Restriction (Facets) */ public static final String SIMPLE_TYPE_RESTRICTION_FACETS = "st-restrict-facets"; /** * totalDigits-valid-restriction: See * XMLSchema Datatypes 1.0: totalDigits valid restriction */ public static final String DATATYPE_TOTAL_DIGITS_RESTRICTION = "totalDigits-valid-restriction"; /** * w-props-correct: See * XMLSchema Structures 1.0: Wildcard Properties Correct */ public static final String WILDCARD_PROPERTIES = "w-props-correct"; /** * whiteSpace-valid-restriction: See * XMLSchema Datatypes 1.0: whiteSpace valid restriction */ public static final String DATATYPE_WHITESPACE_RESTRICTION = "whiteSpace-valid-restriction"; // // datatypes // /** * anyURI: See * XMLSchema Datatypes 1.0: anyURI */ public static final String ANYURI = "anyURI"; /** * base64Binary: See * XMLSchema Datatypes 1.0: base64Binary */ public static final String BASE64BINARY = "base64Binary"; /** * boolean: See * XMLSchema Datatypes 1.0: boolean */ public static final String BOOLEAN = "boolean"; /** * date: See * XMLSchema Datatypes 1.0: date */ public static final String DATE = "date"; /** * decimal: See * XMLSchema Datatypes 1.0: decimal */ public static final String DECIMAL = "decimal"; /** * double: See * XMLSchema Datatypes 1.0: double */ public static final String DOUBLE = "double"; /** * duration: See * XMLSchema Datatypes 1.0: duration */ public static final String DURATION = "duration"; /** * float: See * XMLSchema Datatypes 1.0: float */ public static final String FLOAT = "float"; /** * hexBinary: See * XMLSchema Datatypes 1.0: hexBinary */ public static final String HEXBINARY = "hexBinary"; /** * int: See * XMLSchema Datatypes 1.0: int */ public static final String INT = "int"; /** * integer: See * XMLSchema Datatypes 1.0: integer */ public static final String INTEGER = "integer"; /** * list: See * XMLSchema Datatypes 1.0: list */ public static final String LIST = "list"; /** * long: See * XMLSchema Datatypes 1.0: long */ public static final String LONG = "long"; /** * NCName: See * XMLSchema Datatypes 1.0: NCName */ public static final String NCNAME = "NCName"; /** * NMTOKEN: See * XMLSchema Datatypes 1.0: NMTOKEN */ public static final String NMTOKEN = "NMTOKEN"; /** * QName: See * XMLSchema Datatypes 1.0: QName */ public static final String QNAME = "QName"; /** * union: See * XMLSchema Datatypes 1.0: union */ public static final String UNION = "union"; // // following error codes aren't defined by the XMLSchema spec // /** * Found an attribute during validation that was declared use='prohibited': * See second NOTE at the end of 3.4.2 XML Representation of Complex Type Definitions. * *

* NOTE: * The only substantive function of the value prohibited for the * use attribute of an <attribute> is in establishing * the correspondence between a complex type defined by restriction and its XML * representation. It serves to prevent inheritance of an identically named attribute * use from the {base type definition}. * Such an <attribute> * does not correspond to any component, and hence there is no interaction with either explicit * or inherited wildcards in the operation of Complex Type Definition Validation Rules (3.4.4) * or Constraints on Complex Type Definition Schema Components (3.4.6). *
*/ public static final String ELEM_COMPLEX_TYPE_LOCALLY_VALID$PROHIBITED_ATTRIBUTE = "cvc-complex-type.prohibited-attribute"; /** * */ public static final String SOAPARRAY = "soaparray"; /** * */ public static final String FACET_FIXED = "facet-fixed"; /** * */ public static final String PATTERN_REGEX = "pattern-regex"; /** * */ public static final String MISSING_NAME = "missing-name"; /** * */ public static final String RESERVED_TYPE_NAME = "reserved-type-name"; /** * Error code for an invalid attribute value. */ public static final String INVALID_VALUE = "invalid-value"; /** * Error code for an invalid attribute value. */ public static final String INVALID_VALUE_DETAIL = "invalid-value-detail"; /** * */ public static final String INVALID_XPATH = "invalid-xpath"; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlQName.java0000644000175000017500000002212211361341573022407 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java0000644000175000017500000010364611777644722022466 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 = "2.6.0"; 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 { Class clazz = loader.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 ( ) { } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaBookmark.java0000644000175000017500000000254011361341573023615 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * Represents a Schema bookmark. The XMLSchema compiler will copy the value * returned by {@link #getValue} when this bookmark is found in the XMLStore * to the corresponding Schema* objects, and the value will be accessible using * the getUserInfo method on these objects. * * @see SchemaType * @see SchemaField * @see SchemaAttributeGroup * @see SchemaModelGroup * @see SchemaIdentityConstraint */ public class SchemaBookmark extends XmlCursor.XmlBookmark { private Object _value; public SchemaBookmark(Object value) { _value = value; } /** * Getter. Called during the Schema compilation process. */ public Object getValue() { return _value; } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java0000644000175000017500000002573111361341572023127 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.GregorianCalendar; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.math.BigDecimal; /** * An XML Schema compatible subclass of {@link java.util.GregorianCalendar GregorianCalendar}. * XmlCalendar modifies several key details in the behavior of * GregorianCalendar to make it more useful when dealing with XML dates. *

* It is easy to convert between XmlCalendar and {@link GDate}, or to * parse or emit an XmlCalendar using a standard XML Schema * lexical representation. *

    *
  1. * To match XML Schema dates, this XmlCalendar is a fully proleptic * Gregorian calendar by default, which means that Gregorian calendar * rules are applied backwards in time as if they had always been in * effect, actual historical circumstances concerning the observance * of the 1582 decree of Pope Gregory XIII notwithstanding. *
  2. *
  3. * In order to better support partially-specified dates for XML Schema, * this implementation provides a stable get(field) method * that does not modify the instance if you are acessing a field right * after it was explicitly set: a set followed by a get will always * return the same thing and will not fill in any other fields. However, * if you get a field that was not explicitly set, then all the fields * are still automatically filled and normalized for you, just like a * regular GregorianCalendar. If you wish to force the completion and * defaulting of all the fields (without hunting to get one that happens * to be unset), you can always do so by calling getTime(). *
  4. *
  5. * When a year is unspecified and needs to be filled in automatically * (for example when using a .get or .getTime method as discussed above), * the year is defaulted to year 0 (also known as 1 BC). This is different * from {@link GregorianCalendar}, which chooses 1970. The reason 0 is preferable * is that it is a leap year and so it permits the date --2-29 to be specified * stably. A different default year can be chosen via the static method * {@link #setDefaultYear(int) XmlCalendar.setDefaultYear()}, or by setting the * system property "user.defaultyear". If you do change this value, you should * pick another leap year such as 2000 and avoid non-leap years such as 1900. *
  6. *
  7. * When constructing an XmlCalendar from an XML Schema * formatted date or time string or GDate object, the timezone * for the calendar is taken from the string if it is present, or * taken to be {@link java.util.TimeZone#getDefault() TimeZone.getDefault()} if not. *

    * For example, the XML timezone "Z" is translated to "GMT"; * the XML timezone "+05:00" is translated to "GMT+05:00". *

    *
  8. *
  9. * Finally, this implementation provides a String constructor and a * toString() method that comply with the XML Schema conventions * for formatting a date. If only a subset of fields have been * explicitly set, toString() produces a string with the proper subset * of information. *
  10. *
*/ public class XmlCalendar extends GregorianCalendar { /** * Constructs an XmlCalendar for a standard XML * schema formatted date string. * * The parser accepts any of the following formats: * * YYYY-MM-DDThh:mm:ss - dateTime * YYYY-MM-DD - date * hh:mm:ss - time * YYYY - gYear * --MM - gMonth * ---DD - gDay * * The parser actually accepts all 16 combinations of subsets of * fields (Y, M, D, T) using the same scheme, even for combinations * that are not defined as types in the schema spec, such as * year, day, and time: * * YYYY--DDThh:mm:ss - [everything but month specified] * * In the string, each field must be padded to its full width, for * example, January must be --01, not just --1. * * In particular, a year must be padded to at least four digits, so * "98" is not a valid year, although "1998" and "0098" are both valid * years, unambiguously 19 centuries separated from each other. A year * may also be preceded by a minus symbol: -0001 is 1 BC and -0002 is * 2 BC. * * Finally a timezone is always allowed (yet optional) at the end. * Timezones must be either "Z" (UTC, which we translate to GMT), * or simple offsets from UTC in the range "-14:00" to "+14:00", * for example: "14:30:00-05:00" specifies 2:30 PM in the * afternoon at UTC-05:00, which is the same as EST. * * If a timezone is not specified, the default TimeZone is used. */ public XmlCalendar(String xmlSchemaDateString) { this(new GDate(xmlSchemaDateString)); // use GDate to parse } /** * Constructs an XmlCalendar from a GDate. * * If the instance is not completed, you can round-trip to an * equivalent GDate by writing "new GDate(new XmlCalendar(gdate))". * However, if you access any of the unset fields of the calendar, all * the fields will be automatically filled in, so partial dates * without timezones or other fields will not round-trip after access. */ public XmlCalendar(GDateSpecification date) { this(GDate.timeZoneForGDate(date), date); } private XmlCalendar(TimeZone tz, GDateSpecification date) { super(tz); setGregorianChange(_beginningOfTime); // proleptic clear(); if (date.hasYear()) { int y = date.getYear(); // is never 0 if (y > 0) { set(Calendar.ERA, GregorianCalendar.AD); } else // y < 0 { set(Calendar.ERA, GregorianCalendar.BC); //y = 1 - y; y = -y; // no need to add 1 } set(Calendar.YEAR, y); } if (date.hasMonth()) set(Calendar.MONTH, date.getMonth() - 1); // note!! if (date.hasDay()) set(Calendar.DAY_OF_MONTH, date.getDay()); if (date.hasTime()) { set(Calendar.HOUR_OF_DAY, date.getHour()); set(Calendar.MINUTE, date.getMinute()); set(Calendar.SECOND, date.getSecond()); if (date.getFraction().scale() > 0) set(Calendar.MILLISECOND, date.getMillisecond()); } if (date.hasTimeZone()) { set(Calendar.ZONE_OFFSET, date.getTimeZoneSign() * 1000 * 60 * (date.getTimeZoneHour() * 60 + date.getTimeZoneMinute())); set(Calendar.DST_OFFSET, 0); // note!! if we don't do this, then GregorianCalendar will pick up DST from the time zone } } /** * Constructs an XmlCalendar from a Date. * * The default TimeZone is used for computing the various fields. */ public XmlCalendar(Date date) { this(TimeZone.getDefault(), new GDate(date)); complete(); } /** * Constructs an XmlCalendar with the specified year, month, day, * hours, minutes, seconds, and optional fractional seconds, in * the default timezone. */ public XmlCalendar( int year, int month, int day, int hour, int minute, int second, BigDecimal fraction) { this(TimeZone.getDefault(), new GDate(year, month, day, hour, minute, second, fraction)); } /** * Constructs an XmlCalendar with the specified year, month, day, * hours, minutes, seconds, and optional fractional seconds, in * the specified timezone. */ public XmlCalendar( int year, int month, int day, int hour, int minute, int second, BigDecimal fraction, int tzSign, int tzHour, int tzMinute) { this(new GDate(year, month, day, hour, minute, second, fraction, tzSign, tzHour, tzMinute)); } /** * Gets the value for a given time field. * * Unlike the GregorianCalendar implementation, the get() does not * force a complete of all fields. If you wish to force a completion * of all the fields, call getTime() first. */ public int get(int field) { if (!isSet(field) || isTimeSet) return super.get(field); // forces a complete else return internalGet(field); // does not force a complete. } /** * Constructs an empty instance with no fields set. */ public XmlCalendar() { setGregorianChange(_beginningOfTime); // proleptic clear(); } private static int defaultYear = Integer.MIN_VALUE; private static final int DEFAULT_DEFAULT_YEAR = 0; /** * Returns the default year that is used when no year is specified. */ public static int getDefaultYear() { if (defaultYear == Integer.MIN_VALUE) { try { String yearstring = SystemProperties.getProperty("user.defaultyear"); if (yearstring != null) defaultYear = Integer.parseInt(yearstring); else defaultYear = DEFAULT_DEFAULT_YEAR; } catch (Throwable t) { defaultYear = DEFAULT_DEFAULT_YEAR; } } return defaultYear; } /** * Sets the default year to be used when no year is specified. */ public static void setDefaultYear(int year) { defaultYear = year; } /** * Overrides GregorianCalendar.computeTime to apply a different * default year. (It must be a leap year.) */ protected void computeTime() { boolean unsetYear = !isSet(YEAR); if (unsetYear) set(YEAR, getDefaultYear()); try { super.computeTime(); } finally { if (unsetYear) clear(YEAR); } } private static Date _beginningOfTime = new Date(Long.MIN_VALUE); /** * Prints the XmlCalendar using a standard XML Schema * format, as described in XmlCalendar(String s). */ public String toString() { return (new GDate(this)).toString(); // use GDate to print } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlToken.java0000644000175000017500000002172511361341573022476 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlObject.java0000644000175000017500000011165511361341573022626 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 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 java.io.InputStream; import java.io.File; import java.io.Reader; import java.io.IOException; /** * Corresponds to the XML Schema * xs:anyType, * the base type for all XML Beans. *

* Since all XML Schema types are translated into corresponding XML Bean * classes, and all Schema type derivation corresponds to Java class * inheritance, the fact that all Schema types derive from xs:anyType means * that all XML Bean classes derive from XmlObject. *

* On this base class you will find a number of common facilities that * all XML Bean classes provide: *

*

    *
  • Every XML Bean class has an inner Factory class for creating and parsing * instances, including XmlObject. Use {@link XmlObject.Factory} itself * to produce untyped XML trees or XML trees that implement specific * subtypes of XmlObject depending on a recognized root document element. * If you depend on the automatic type inference, you will want to understand * the type inference issues described below. *
  • To write out an accurate XML file for the XML tree under this * XmlObject, use one of the {@link #save} methods, * or {@link #newInputStream} or {@link #newReader}. * Use {@link #toString} to produce a pretty-printed representation of the * XML subtree under this XML Object. If you save interior portions of * an XML document, you will want to understand the inner contents * versus outer container issues described below. *
  • 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 * {@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 * XML Object. If you wish to get information about the location * and reason for validation errors, see {@link XmlOptions#setErrorListener}, * and use {@link #validate(XmlOptions)}. *
  • 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 * 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 * the current element or attribute.) *
*

* Type inference. When using {@link XmlObject.Factory} to parse XML documents, * the actual document type is not {@link XmlObject#type} itself, but a subtype * based on the contents of the parsed document. If the parsed document * contains a recognized root document element, then the actual type of the * loaded instance will be the matching Document type. For example: *

 * XmlObject xobj = XmlObject.Factory.parse(myDocument);
 * if (xobj instanceof MyOrderDocument) // starts w/ <my-order>
 * {
 *     MyOrderDocument mydoc = (MyOrderDocument)xobj;
 *     if (!xobj.validate())
 *         System.out.println("Not a valid my-order document");
 * }
 * else
 * {
 *     System.out.println("Not a my-order document");
 * }
 * 
* Every XML Bean class has its own inner Factory class, * so if you actually know exactly which XML Bean document type * you want to load as in the example above, you should use the * the specific XML Bean Factory class instead. For example: *
 * MyOrderDocument mydoc = MyOrderDocument.Factory.parse(myDocument);
 * 
* The code above will throw an exception if the parsed document * does not begin with the proper (my-order) element. *

* Inner versus outer. An XmlObject represents the * contents of an element or attribute, not the element * or attribute itself. So when you validate or save an XmlObject, you * are validating or saving its contents, not its container. For example, * if the XmlObject represents the contents of an element which happens * to itself be in the wrong order relative to its siblings, validate will * not complain about the misplacement of the element itself. On the other hand, if * elements within the XmlObject are in the wrong order, validate * will complain. Similarly, when saving the contents of an interior * XmlObject, it is the contents of an element, not the element itself, * which is saved by default. *

* Reading and writing fragments. When reading or writing the contents of a * whole XML document, the standard XML reprentation for a document is used. * However, there is no standard concrete XML representation for "just the * contents" of an interior element or attribute. So when one is needed, * the tag <xml-fragment> is used to wrap the contents. This tag is used * can also be used to load just the contents for an XmlObject document fragment * of arbitrary type. If you wish to save out the XmlObject's container element * along with its contents, use {@link XmlOptions#setSaveOuter}. *

* Implementing XmlObject. The XMLBeans library does not support arbitrary * implementations of XmlObject - in almost all cases, you should only use * the implementations of XmlObject provided by the XMLBeans compiler itself. * 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"); /** * The schema type for this instance. This is a permanent, * unchanging property of the instance. */ SchemaType schemaType(); /** * Returns true if the contents of this object are valid * accoring to schemaType(). *

* Does a deep validation of the entire subtree under the * object, but does not validate the parents or siblings * of the object if the object is in the interior of an xml * tree. */ boolean validate(); /** *

Just like validate(), but with options.

*

If you wish to collect error messages and locations while validating, * 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)
     * {
     *      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 options An object that implements the {@link java.util.Collection * Collection} interface. */ boolean validate(XmlOptions options); /** * 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": *

     *   <schema targetNamespace="http://openuri.org/sample">
     *      <element name="owner" type="person"/>
     *      <complexType name="person">
     *         [...]
     *      </complexType>
     *   </schema>
     * 
* and suppose "owner" tags can be scattered throughout the * document. Then we can write the following code to find * them all: *
     * import org.openuri.sample.Person;
     * import org.apache.xmlbeans.*;
     * [...]
     *   XmlObject xobj = XmlObject.Factory.parse(myFile);
     *   Person[] results;
     *   results = (Person[])xobj.selectPath(
     *      "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 * the same XML document as this XmlObject itself. */ XmlObject[] selectPath ( String path ); /** * Selects a path, applying options. * * @see #selectPath(String) */ XmlObject[] selectPath ( String path, XmlOptions options ); /** * Executes a query. Query can be a string or precompiled query String. *

* An XQuery is very similar to an XPath, except that it also permits * construction of new XML. As a result, the XmlObjects that are * returned from execQuery are in newly created documents, separate * from the XmlObject on which the query is executed. *

* Syntax and usage is otherwise similar to selectPath. *

* @see #selectPath(String) */ XmlObject[] execQuery ( String query ); /** * Executes a query with options. * * Use the options parameter to specify the following:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
To specify thisUse this method
The document type for the root element.{@link XmlOptions#setDocumentType}
To replace the document element with the specified QName when constructing the * resulting document.{@link XmlOptions#setLoadReplaceDocumentElement}
To strip all insignificant whitespace when constructing a document.{@link XmlOptions#setLoadStripWhitespace}
To strip all comments when constructing a document.{@link XmlOptions#setLoadStripComments}
To strip all processing instructions when constructing a document.{@link XmlOptions#setLoadStripProcinsts}
A map of namespace URI substitutions to use when constructing a document.{@link XmlOptions#setLoadSubstituteNamespaces}
Additional namespace mappings to be added when constructing a document.{@link XmlOptions#setLoadAdditionalNamespaces}
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. * * @see #execQuery(String) */ XmlObject[] execQuery ( String query, XmlOptions options ); /** * Changes the schema type associated with this data and * returns a new XmlObject instance whose schemaType is the * new type. *

* Returns the new XmlObject if the type change was successful, * the old XmlObject if no changes could be made.

* Certain type changes may be prohibited in the interior of an xml * tree due to schema type system constraints (that is, due * to a parent container within which the newly specified * type is not permissible), but there are no constraints * at the roottype changes are never * prohibited at the root of an xml tree. *

* If the type change is allowed, then the new XmlObject should * be used rather than the old one. The old XmlObject instance and * 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. */ XmlObject changeType(SchemaType newType); /** * Changes the schema type associated with this data using substitution * groups and returns an XmlObject instance whose schemaType is the * new type and container name is the new name. *

* Returns the new XmlObject if the substitution was successful, * the old XmlObject if no changes could be made.

* In order for the operation to succeed, several conditions must hold: *

  • the container of this type must be an element
  • *
  • a global element with the name newName must exist * and must be in the substition group of the containing element
  • *
  • the newType type must be consistent with the declared * type of the new element
*

* If the type change is allowed, then the new XmlObject should * be used rather than the old one. The old XmlObject instance and * 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 necessary, xsi:type attributes are updated. */ XmlObject substitute(QName newName, SchemaType newType); /** * True if the value is nil. Note that in order to be nil, * the value must be in an element, and the element containing * the value must be marked as nillable in the schema. */ boolean isNil(); /** * Sets the value to nil. The element containing the value must * be marked as nillable in the schema. */ void setNil(); /** * Returns an XML string for this XML object. *

* The string is pretty-printed. If you want a non-pretty-printed * string, or if you want to control options precisely, use the * xmlText() methods. *

* Note that when producing XML any object other than very root of the * document, then you are guaranteed to be looking at only a fragment * of XML, i.e., just the contents of an element or attribute, and * and we will produce a string that starts with an <xml-fragment> tag. * The XmlOptions.setSaveOuter() option on xmlText can be used to produce * the actual element name above the object if you wish. */ String toString(); /** * True if the value is an immutable value. Immutable values do not * have a position in a tree; rather, they are stand-alone simple type * values. If the object is immutable, the equals() methods tests for * value equality, and the object can be used as the key for a hash. */ boolean isImmutable(); /** * Set the value/type of this XmlObject to be a copy of the source * XmlObject. Because the type of the source may be different than this * target, this XmlObject may become defunct. In this case the new * XmlObject is returned. If no type change happens, the same this will be * returned. */ XmlObject set(XmlObject srcObj); /** * Returns a deep copy of this XmlObject. The returned object has the * same type as the current object, and has all the content of * 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) */ XmlObject copy(); /** * Returns a deep copy of this XmlObject. The returned object has the * same type as the current object, and has all the content of * 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); /** * True if the xml values are equal. Two different objects * (which are distinguished by equals(obj) == false) may of * course have equal values (valueEquals(obj) == true). *

* Usually this method can be treated as an ordinary equvalence * relation, but actually it is not is not transitive. * Here is a precise specification: *

* There are two categories of XML object: objects with a known * instance type, and objects whose only known type is one of the * ur-types (either AnyType or AnySimpleType). The first category * is compared in terms of logical value spaces, and the second * category is compared lexically. *

* Within each of these two categories, valueEquals is a well-behaved * equivalence relation. However, when comparing an object of known * type with an object with ur-type, the comparison is done by attempting * to convert the lexical form of the ur-typed object into the other * type, and then comparing the results. Ur-typed objects are therefore * treated as lexical wildcards and may be equal to objects in different * value spaces, even though the objects in different value spaces are * not equal to each other. *

* For example, the anySimpleType value "1" will compare as an * equalValue to the string "1", the float value "1.0", the double * value "1.0", the decimal "1", and the GYear "1", even though * all these objects will compare unequal to each other since they * lie in different value spaces. * Note: as of XMLBeans 2.2.1 only implemented for simple type values. */ boolean valueEquals(XmlObject obj); int valueHashCode(); /** * Impelements the Comparable interface by comparing two simple * xml values based on their standard XML schema ordering. * Throws a ClassCastException if no standard ordering applies, * or if the two values are incomparable within a partial order. */ int compareTo(Object obj); /** * This comparison method is similar to compareTo, but rather * than throwing a ClassCastException when two values are incomparable, * it returns the number 2. The result codes are -1 if this object * is less than obj, 1 if this object is greater than obj, zero if * the objects are equal, and 2 if the objects are incomparable. */ int compareValue(XmlObject obj); /** LESS_THAN is -1. See {@link #compareValue}. */ static final int LESS_THAN = -1; /** EQUAL is 0. See {@link #compareValue}. */ static final int EQUAL = 0; /** GREATER_THAN is 1. See {@link #compareValue}. */ static final int GREATER_THAN = 1; /** 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. */ XmlObject[] selectChildren(QName elementName); /** * Selects the contents of the children elements with the given name. * @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. */ XmlObject[] selectChildren(String elementUri, String elementLocalName); /** * 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() * @see QNameSetBuilder for creating sets of qnames */ XmlObject[] selectChildren(QNameSet elementNameSet); /** * 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. */ XmlObject selectAttribute(QName attributeName); /** * Selects the content of the attribute with the given name. * @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. */ XmlObject selectAttribute(String attributeUri, String attributeLocalName); /** * 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() * @see QNameSetBuilder for creating sets of qnames */ XmlObject[] selectAttributes(QNameSet attributeNameSet); /** * Static factory class for creating new instances. Note that if * a type can be inferred from the XML being loaded (for example, * by recognizing the document element QName), then the instance * returned by a factory will have the inferred type. Otherwise * the Factory will returned an untyped document. */ public static final class Factory { /** * Creates a new, completely empty instance. */ 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:

* * * * * * * * * * * *
To specify thisUse this method
The document type for the root element.{@link XmlOptions#setDocumentType}
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. * @return A new, empty instance of XmlObject. */ 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 ); } /** * Parses the given {@link String} as XML. */ 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:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
To specify thisUse this method
The document type for the root element.{@link XmlOptions#setDocumentType}
To place line number annotations in the store when parsing a document.{@link XmlOptions#setLoadLineNumbers}
To replace the document element with the specified QName when parsing.{@link XmlOptions#setLoadReplaceDocumentElement}
To strip all insignificant whitespace when parsing a document.{@link XmlOptions#setLoadStripWhitespace}
To strip all comments when parsing a document.{@link XmlOptions#setLoadStripComments}
To strip all processing instructions when parsing a document.{@link XmlOptions#setLoadStripProcinsts}
A map of namespace URI substitutions to use when parsing a document.{@link XmlOptions#setLoadSubstituteNamespaces}
Additional namespace mappings to be added when parsing a document.{@link XmlOptions#setLoadAdditionalNamespaces}
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. * @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 ); } /** * Parses the given {@link File} as XML. */ 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 ); } /** * 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 ); } /** * 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 ); } /** * 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 ); } /** * Decodes and parses the given {@link XMLStreamReader} as XML. */ 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:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
To specify thisUse this method
The character encoding to use when parsing or writing a document.{@link XmlOptions#setCharacterEncoding}
The document type for the root element.{@link XmlOptions#setDocumentType}
Place line number annotations in the store when parsing a document.{@link XmlOptions#setLoadLineNumbers}
Replace the document element with the specified QName when parsing.{@link XmlOptions#setLoadReplaceDocumentElement}
Strip all insignificant whitespace when parsing a document.{@link XmlOptions#setLoadStripWhitespace}
Strip all comments when parsing a document.{@link XmlOptions#setLoadStripComments}
Strip all processing instructions when parsing a document.{@link XmlOptions#setLoadStripProcinsts}
Set a map of namespace URI substitutions to use when parsing a document.{@link XmlOptions#setLoadSubstituteNamespaces}
Set additional namespace mappings to be added when parsing a document.{@link XmlOptions#setLoadAdditionalNamespaces}
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 ); } /** * Parses the given {@link XMLStreamReader} as XML. */ 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 ); } /** * 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 ); } /** * 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 ); } /** * Loads the given {@link XMLInputStream} into an XmlObject. * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. */ public static XmlObject parse ( XMLInputStream xis, XmlOptions options ) throws XmlException, XMLStreamException { return XmlBeans.getContextTypeLoader().parse( xis, null, options ); } /** * Returns an {@link XmlSaxHandler} that can load an XmlObject from SAX events. */ 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 ); } /** * 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 ); } /** * 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. */ public static XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, XmlOptions options ) throws XmlException, XMLStreamException { return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, null, options ); } /** * Instances cannot be created. */ private Factory() { } } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlHexBinary.java0000644000175000017500000002142211361341573023301 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/message.properties0000644000175000017500000006370011714325344023633 0ustar apoapo## ## Copyright 2004 The Apache Software Foundation ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT 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 message properties # # xmlbean messages # message.missing.resource = \ Message property value not found: {0} message.pattern.invalid = \ Message property value invalid: {0} invalid.document.type = \ Document {0} is not a {1} file cannot.load.file = \ Cannot load {0} file {1}: {2} exception.loading.url = \ {0} exception while trying to load {1}: {2} exception.value.not.supported.j2s = \ Could not set Java {0} type to Schema {1} type exception.value.not.supported.s2j = \ Could not get a Java {1} type from a Schema {0} type exception.xqrl.xpath.not.valid = \ Path expression is not selective, it creates new nodes: {0} exception.xqrl.exception = \ XQuery engine exception: {0} for expresion: {1} # # xml messages # uniqattspec = \ Duplicate attribute: {0} # # schema messages # cvc-assess-attr = \ Schema-Validity Assessment (Attribute) cvc-assess-attr.1.2 = \ Attribute not allowed (strict wildcard, and no definition found): {0} cvc-assess-elt = \ Schema-Validity Assessment (Element) cvc-assess-elt.1.1.1.3.2 = \ Element not allowed (strict wildcard, and no definition found): {0} cvc-attribute = \ Attribute Locally Valid cvc-attribute.1 = \ Invalid type for attribute cvc-attribute.4 = \ The value ''{0}'' does not equal the fixed value ''{1}'' of attribute ''{2}'' #The value ''{0}'' does not equal the fixed value ''{1}'' cvc-au = \ Attribute Locally Valid (Use) cvc-complex-type = \ Element Locally Valid (Complex Type) cvc-complex-type.2.1 = \ Element ''{0}'' with empty content type cannot have text or element content. cvc-complex-type.2.2 = \ Element ''{0}'' with a simple type definition cannot have element content. cvc-complex-type.2.3 = \ Element ''{0}'' with element-only content type cannot have text content. cvc-complex-type.2.4a = \ Expected {0,choice,1#element|1 or from type redefinition. src-redefine.5b = \ A {0} type redefinition must extend or restrict the original definition of the type. The attribute base=''{1}'' must match the attribute name=''{2}'' of the redefined {0}. src-redefine.6.1.1 = \ The group redefinition {0} must reference the originial definition at most once. src-redefine.6.1.2 = \ When referencing the original group definition in the redefinition {0}, maxOccurs and minOccurs must be 1. src-redefine.7.1 = \ The attribute group redefinition {0} must reference the original definition at most once. src-resolve = \ {0} ''{1}'' not found. # e.g., "element 'foo' not found." src-resolve.a = \ Could not find {0} ''{1}''. Do you mean to refer to the {2} {3,choice,0#with that name|1#named {4}}{5,choice,0#|1# (in {6})}? src-restriction-base-or-simpleType = \ base attribute or simpleType child src-simple-type = \ Simple Type Definition Representation OK src-simple-type.2a = \ Simple type restrictions must name a base type or contain a nested simple type: both were found. src-simple-type.2b = \ Simple type restrictions must name a base type or contain a nested simple type: neither were found. src-simple-type.3a = \ List type definitions provide either an itemType attribute or contain a nested simpleType: both were found. src-simple-type.3b = \ List type definitions provide either an itemType attribute or contain a nested simpleType: neither were found. src-simple-type.4 = \ Member {0}has a cyclic dependency on the union. src-single-facet-value = \ Facet specified multiple times. src-union-memberTypes-or-simpleTypes = \ A union type must specify at least one member type. src-wildcard = \ Wildcard Representation OK a-props-correct = \ Attribute Declaration Properties Correct a-props-correct.2 = \ The {0} attribute {1} value ''{2}'' is not a valid value for {3}. a-props-correct.3 = \ An attribute of type xs:ID is not allowed to have a default or fixed constraint. ag-props-correct = \ Attribute Group Definition Properties Correct ag-props-correct.2 = \ KHK: TBD ag-props-correct.3 = \ Both {0} and {1} are xs:ID attributes; only one ID attribute is allowed on a type. an-props-correct = \ Annotation Correct au-props-correct = \ Attribute Use Correct c-fields-xpaths = \ Invalid xpath value in field: {0} c-props-correct = \ Identity-constraint Definition Properties Correct c-props-correct.1 = \ Keyref cannot refer to another keyref. c-props-correct.2 = \ Keyref does not have same number of fields as key c-selector-xpath = \ Invalid xpath value in selector: {0} cos-all-limited = \ All Group Limited cos-all-limited.1.2a = \ An all group must have maxOccurs <= 1. cos-all-limited.1.2b = \ An all group is only allowed at the top level of the content model. cos-all-limited.2 = \ An all group can contain only element particles with maxOccurs <= 1 cos-applicable-facets = \ The facet ''{0}'' does not apply to the base type {1}. cos-aw-intersect = \ Attribute Wildcard Intersection cos-aw-union = \ Attribute Wildcard Union cos-choice-range = \ Effective Total Range (choice) cos-ct-derived-ok = \ Type Derivation OK (Complex) cos-ct-extends = \ Derivation Valid (Extension) cos-ct-extends.1.1 = \ The base complex type {0} cannot be restricted by {1} when final=''extension''. cos-ct-extends.1.4.1 = \ This type extends a base type ''{0}'' which has simpleContent. In that case this type cannot add particles. cos-ct-extends.1.4.2.2 = \ Cannot extend an element-only type with a mixed type or vice-versa. cos-element-consistent = \ Type of ''{0}'' is inconsistent with another element with the same name in this content model. cos-equiv-class = \ Substitution Group cos-equiv-derived-ok-rec = \ Substitution Group OK (Transitive) cos-group-emptiable = \ Particle Emptiable cos-list-of-atomic = \ list of atomic cos-no-circular-unions = \ no circular unions cos-nonambig = \ Content model violates the unique particle attribution rule. cos-ns-subset = \ Wildcard Subset cos-particle-extend = \ Particle Valid (Extension) cos-particle-restrict = \ Particle Valid (Restriction) cos-particle-restrict.2 = \ Invalid Restriction. The derived content model {0} cannot restrict base content model {1}. cos-seq-range = \ Effective Total Range (all and sequence) cos-st-derived-ok = \ Type Derivation OK (Simple) cos-st-restricts = \ Derivation Valid (Restriction, Simple) cos-st-restricts.1.1 = \ Base type for this simple type restriction is not simple. cos-st-restricts.2.1a = \ Item type for this list type is not simple. cos-st-restricts.2.1b = \ This item type is another list type; lists of lists are not allowed. cos-st-restricts.2.1c = \ This item type is a union containing a list; lists of lists are not allowed. cos-st-restricts.3.1 = \ Member {0}is not simple. cos-valid-default = \ Element Default Valid (Immediate) cos-valid-default.2.1 = \ The {0} element cannot have a default value ''{1}'' because its type has {2} content only. cos-valid-default.2.2.2 = \ The {0} element cannot have a {1} value ''{2}'' because it's content is mixed but not emptiable. id-idref-idrefs-entity-entities-notation = \ For compatibility, type ''{1}'' should only be used for attributes (used for element ''{0}''). ct-props-correct = \ Complex Type Definition Properties Correct ct-props-correct.2 = \ The simple type ''{0}'' cannot be used as the base type of a simple content restriction. (Use extension instead.) ct-props-correct.4 = \ Attribute with the name ''{0}'' already defined for {1}. derivation-ok-restriction = \ Derivation Valid (Restriction, Complex) derivation-ok-restriction.1 = \ The base type {0} cannot be restricted by {1} when final=''restriction''. derivation-ok-restriction.2.1.1 = \ The attribute ''{0}'' cannot be modified by restriction to be prohibited or optional since it is required in the base type {1}. derivation-ok-restriction.2.2 = \ The attribute ''{0}'' cannot be introduced by restriction since it is not allowed in the base type {1}. derivation-ok-restriction.4.1 = \ A restriction cannot add anyAttribute when the base type does not have anyAttribute. derivation-ok-restriction.4.2 = \ The anyAttribute namespace=''{0}'' is not a subset of the base type anyAttribute. derivation-ok-restriction.5.1 = \ A complex type with a simple content model can only restrict a complex type with simple or mixed content model. derivation-ok-restriction.5.1.2 = \ A type with a simple content model can only restrict a mixed content model that has skippable elements. derivation-ok-restriction.5.2.2.1 = \ The simple content is not validly derived from the base simple content type. derivation-ok-restriction.5.2 = \ A type with an empty content model cannot restrict a type with a simple content model. derivation-ok-restriction.5.2.2 = \ A type with an empty content model can only restrict a content model that has skippable elements. derivation-ok-restriction.5.3 = \ Must be a valid restriction. derivation-ok-restriction.5.3a = \ A type with a mixed content model can only restrict another type with a mixed content model. derivation-ok-restriction.5.3b = \ A type with element or mixed content cannot restrict an empty type. derivation-ok-restriction.5.3c = \ A type with element or mixed content cannot restrict a simple type. e-props-correct = \ Element Declaration Properties Correct e-props-correct.2 = \ The ''{0}'' element {1} value ''{2}'' is not a valid value for ''{3}'' e-props-correct.4 = \ Element ''{0}'' is not a valid substitution for element ''{1}'': its type is not validly derived from element ''{1}''''s type e-props-correct.4a = \ Element ''{0}'' is not a valid substitution for element ''{1}'' with final=''{2}'' notation-targetns-attr = \ For compatibility, NOTATION should only be used in schemas with no target namespace (attribute ''{0}''). notation-targetns-elem = \ For compatibility, NOTATION should only be used in schemas with no target namespace (element ''{0}''). enumeration-required-notation = \ enumeration facet value required for NOTATION notation-facets = \ The use of {0} on datatypes derived from NOTATION (''{1}'') is deprecated. enumeration-valid-restriction = \ Enumerated value ''{0}'' invalid: {1} fractionDigits-totalDigits = \ fractionDigits must be less than or equal to totalDigits fractionDigits-valid-restriction = \ Larger than prior fractionDigits. length-minLength-maxLength = \ Cannot specify length in addition to minLength or maxLength. length-valid-restriction = \ length valid restriction maxExclusive-valid-restriction = \ Invalid maxExclusive restriction: {0} maxInclusive-maxExclusive = \ maxInclusive and maxExclusive maxInclusive-valid-restriction = \ Invalid maxInclusive restriction: {0} maxLength-valid-restriction = \ Larger than prior maxLength. mg-props-correct = \ Model Group Correct mg-props-correct.2 = \ Model group ''{0}'' references itself. mgd-props-correct = \ Model Group Definition Properties Correct minExclusive-less-than-equal-to-maxExclusive = \ minExclusive <= maxExclusive minExclusive-less-than-maxInclusive = \ minExclusive < maxInclusive minExclusive-valid-restriction = \ Invalid minExclusive restriction: {0} minInclusive-less-than-equal-to-maxInclusive = \ minInclusive <= maxInclusive minInclusive-less-than-maxExclusive = \ minInclusive < maxExclusive minInclusive-minExclusive = \ minInclusive and minExclusive minInclusive-valid-restriction = \ Invalid minInclusive restriction: {0} minLength-less-than-equal-to-maxLength = \ minLength <= maxLength minLength-valid-restriction = \ Smaller than prior minLength. n-props-correct = \ Notation Declaration Correct no-xmlns = \ The name of an attribute declaration must not match ''xmlns''. no-xsi = \ Illegal namespace for attribute declaration: {0} enumeration-required-notation-attr = \ It is an error for NOTATION to be used directly in a schema. Only datatypes that are derived from NOTATION by specifying a value for enumeration can be used in a schema (attribute ''{0}''). enumeration-required-notation-elem = \ It is an error for NOTATION to be used directly in a schema. Only datatypes that are derived from NOTATION by specifying a value for enumeration can be used in a schema (element ''{0}''). p-props-correct = \ Particle Correct p-props-correct.2.1 = \ maxOccurs must not be less than minOccurs. p-props-correct.2.2 = \ maxOccurs must be greater than or equal to 1. range-ok = \ Occurrence Range OK range-ok.1 = \ Invalid Restriction. The minOccurs ({1}) for the derived {0} is less than the minOccurs ({3}) of the base {2}. range-ok.2 = \ Invalid Restriction. The maxOccurs ({1}) for the derived {0} is greater than the maxOccurs ({3}) of the base {2}. rcase-MapAndSum = \ Particle Derivation OK (Sequence:Choice -- MapAndSum) rcase-MapAndSum.1 = \ Invalid Restriction. The {0} particle of the derived cannot be mapped to any one of the base ''s particles. rcase-MapAndSum.2a = \ Invalid Restriction. The total minOccurs for the derived ''s elements ({0}) must not be less than the base ''s minOccurs ({1}). rcase-MapAndSum.2b = \ Invalid Restriction. The total maxOccurs for the derived ''s elements ({0}) must not be greater than the base ''s maxOccurs ({1}). rcase-NameAndTypeOK = \ Particle Restriction OK (Elt:Elt -- NameAndTypeOK) rcase-NameAndTypeOK.1 = \ Invalid Restriction. The derived {0}''s name and namespace must match the base {1}''s name and namespace. rcase-NameAndTypeOK.2 = \ Invalid Restriction. The derived {0} must not be nillable=''true'' when the base {1} is nillable=''false''. rcase-NameAndTypeOK.4 = \ Invalid Restriction. The derived {0} has a fixed value of ''{1}'' which does not match the base {2}''s fixed value of ''{3}''. rcase-NameAndTypeOK.5 = \ Invalid Restriction. The derived {0}''s identity constraints must be a subset of the base {1}''s identity constraints. rcase-NameAndTypeOK.6 = \ Invalid Restriction. The derived {0} must block {1} when the base {1} does. rcase-NameAndTypeOK.7a = \ Invalid Restriction. The derived type {0} is not a sub-type of the base type {1}. rcase-NameAndTypeOK.7b = \ Invalid Restriction. The derived type {0} from base type {1} has an intermediate type {2} that is not derived by restriction. rcase-NSCompat = \ Particle Derivation OK (Elt:Any -- NSCompat) rcase-NSCompat.1 = \ Invalid Restriction. The namespace of the derived {0} is not valid with respect to the namespace(s) of the base {1}. rcase-NSRecurseCheckCardinality = \ Particle Derivation OK (All/Choice/Sequence:Any -- NSRecurseCheckCardinality) rcase-NSSubset = \ Particle Derivation OK (Any:Any -- NSSubset) rcase-NSSubset.2 = \ Invalid Restriction. The namespace(s) of the derived field {0} are not a subset of the namespace(s) of the base field {1}. rcase-Recurse = \ Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) rcase-Recurse.2 = \ Invalid Restriction. The following particles of the derived {0} cannot be mapped to the base {1}''s particles: {2} rcase-Recurse.2.1 = \ Invalid Restriction. The particle {0} of the derived {1} is not a valid restriction of the non-optional particle {2} in the base {3} model. rcase-Recurse.2.2 = \ Invalid Restriction. The following non-optional particles of the base {0} were not mapped in the derived {1}: {2} rcase-RecurseAsIfGroup = \ Particle Derivation OK (Elt:All/Choice/Sequence -- RecurseAsIfGroup) rcase-RecurseLax = \ Particle Derivation OK (Choice:Choice -- RecurseLax) rcase-RecurseLax.2 = \ Invalid Restriction. The following particles of the derived cannot be mapped to the base ''s particles: {0} rcase-RecurseUnordered = \ Particle Derivation OK (Sequence:All -- RecurseUnordered) rcase-RecurseUnordered.2 = \ Invalid Restriction. The particle {0} in the derived cannot be mapped to an in the base . rcase-RecurseUnordered.2.1 = \ Invalid Restriction. The particle {0} in the derived maps to more than one element in the base . rcase-RecurseUnordered.2.2 = \ Particle Derivation OK (Sequence:All -- RecurseUnordered) rcase-RecurseUnordered.2.2a = \ Invalid Restriction. The particle {0} in the derived has a maxOccurs greater than 1 ({1}). When restricting an with a , no can have a maxOccurs > 1. rcase-RecurseUnordered.2.3 = \ Invalid Restriction. The particle {0} in the base must be mapped by one of the members of the derived unless it is optional (particle emptiable). sch-props-correct = \ Schema Properties Correct sch-props-correct.2 = \ Duplicate {0}: {1} (Original {0} found in file: {2}) st-props-correct = \ Simple Type Definition Properties Correct st-props-correct.3 = \ Cannot restrict a final type. st-props-correct.4.2.1 = \ Cannot derive by list a final type. st-props-correct.4.2.2 = \ Cannot derive by union a final type. st-restrict-facets = \ Simple Type Restriction (Facets) totalDigits-valid-restriction = \ Larger than prior totalDigits. w-props-correct = \ Wildcard Properties Correct whiteSpace-valid-restriction = \ Cannot apply this whitespace facet over the previous one. # # datatypes # anyURI = \ Invalid value: {0} base64Binary = \ Invalid value: {0} boolean = \ Invalid boolean value ''{0}'' date = \ Invalid date value: {0} decimal = \ Invalid decimal value: {0} double = \ Invalid double value: {0} duration = \ Invalid duration value: {0} float = \ Invalid float value: {0} hexBinary = \ Invalid hexBinary value: {0} int = \ Invalid int value: {0} integer = \ Invalid integer value: {0} list = \ Invalid list value: {0} long = \ Invalid long value: {0} NCName = \ Invalid NCName value: {0} NMTOKEN = \ Invalid NMTOKEN value: {0} QName = \ Invalid QName value: {0} union = \ Invalid union value: {0} # # following error codes aren't defined by the XMLSchema spec # cvc-complex-type.prohibited-attribute = \ Attribute is prohibited: {0} soaparray = \ Invalid SOAP Array reference: {0} (prefix declaration not found or incorrect format) facet-fixed = \ The facet ''{0}'' is fixed and cannot be overridden. pattern-regex = \ The regular expression ''{0}'' is malformed: {1} missing-name = \ The {0} must have a name. reserved-type-name = \ Skipping definition of built-in type {0}. # {1} may be either an attribute name ('type', 'name') or a type name ('nonNegativeInteger') invalid-value = \ The value ''{0}'' is an invalid {1}. # {1} may be either an attribute name ('type', 'name') or a type name ('nonNegativeInteger') invalid-value-detail = \ The value ''{0}'' is an invalid {1}: {2} invalid-xpath = \ Invalid xpath in identity constraint: {0} exceeded-entity-bytes = \ Exceeded Entity dereference bytes limit, limit is {0} bytes.xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/GDurationBuilder.java0000644000175000017500000004457211361341572024144 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNegativeInteger.java0000644000175000017500000002160111361341573024467 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlGDay.java0000644000175000017500000002276511361341573022247 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlAnySimpleType.java0000644000175000017500000002200711361341573024153 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaAnnotation.java0000644000175000017500000000340111361341573024157 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 annotation. */ public interface SchemaAnnotation extends SchemaComponent { /** * Retrieves all application information items from this annotation */ public XmlObject[] getApplicationInformation(); /** * Retrieves all document information items from this annotation */ public XmlObject[] getUserInformation(); /** * Retrieves all attributes that are is a namespace other than * http://www.w3.org/2001/XMLSchema * from the annotation element and from the enclosing Schema component */ public Attribute[] getAttributes(); /** * Represents an attribute instance */ public static interface Attribute { /** * Returns the name of the attribute */ QName getName(); /** * Returns the value of the attribute */ String getValue(); /** * In case the value of this attribute is a QName, * returns the URI to which the prefix in the value is bound */ String getValueUri(); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/QNameSetSpecification.java0000644000175000017500000001002711361341573025104 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Represents a lattice of finite and infinite sets of QNames. * * @see QNameSet */ public interface QNameSetSpecification { /** * True if the set contains the given QName. * * Roughly equivalent to: * (includedURIs() == null ? * excludedURIs().contains(namespace) : * includedURIs().contains(namespace) * ) ? * !excludedQNamesInIncludedURIs().contains(name) : * includedQNamesInExcludedURIs().contains(name) */ boolean contains(QName name); /** * True if the set is the set of all QNames. */ boolean isAll(); /** * True if the set is empty. */ boolean isEmpty(); /** * True if the parameter is a subset of this set. */ boolean containsAll(QNameSetSpecification set); /** * True if is disjoint from the specified set. */ boolean isDisjoint(QNameSetSpecification set); /** * Returns the intersection with another QNameSet. */ QNameSet intersect(QNameSetSpecification set); /** * Returns the union with another QNameSet. */ QNameSet union(QNameSetSpecification set); /** * Return the inverse of this QNameSet. That is the QNameSet which * contains all the QNames not contained in this set. In other words * for which set.contains(name) != set.inverse().contains(name) for * all names. */ QNameSet inverse(); /** * The finite set of namespace URIs that are almost completely excluded from * the set (that is, each namespace URI that included in the set with with * a finite number of QName exceptions). Null if the set of namespaceURIs * that are almost completely included is infinite. *

* Null (meaning almost all URIs excluded) if includedURIs() is non-null; * non-null otherwise. *

* The same set as inverse().includedURIs(). */ Set excludedURIs(); /** * The finite set of namespace URIs that are almost completely included in * the set (that is, each namespace URI that included in the set with with * a finite number of QName exceptions). Null if the set of namespaceURIs * that are almost completely included is infinite. *

* Null (meaning almost all URIs included) if excludedURIs() is non-null; * non-null otherwise. *

* The same as inverse.excludedURIs(). */ Set includedURIs(); /** * The finite set of QNames that are excluded from the set within namespaces * that are otherwise included. Should only contain QNames within namespace * that are within the set includedURIs() (or any URI, if includedURIs() * is null, which means that all URIs are almost completely included). *

* Never null. *

* The same set as inverse().includedQNames(). */ Set excludedQNamesInIncludedURIs(); /** * The finite set of QNames that are included in the set within namespaces * that are otherwise excluded. Should only contain QNames within namespace * that are within the set excludedURIs() (or any URI, if excludedURIs() * is null, which means that all URIs are almost completely excluded). *

* Never null. *

* The same as inverse().excludedQNames(). */ Set includedQNamesInExcludedURIs(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNonNegativeInteger.java0000644000175000017500000002206711361341572025150 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/GDateSpecification.java0000644000175000017500000001572411361341573024424 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.util.Date; /** * Represents an XML Schema-compatible Gregorian date. *

* Both the immutable GDate and the mutable GDateBuilder are * GDateSpecifications. Use this interface where you want to * allow callers to pass any implementation of a GDate. * * @see GDate * @see XmlCalendar */ public interface GDateSpecification { /** * Returns a combination of flags indicating the information * contained by this GDate. The five flags are * {@link #HAS_TIMEZONE}, {@link #HAS_YEAR}, {@link #HAS_MONTH}, * {@link #HAS_DAY}, and {@link #HAS_TIME}. */ int getFlags(); /** Timezone is specified. See {@link #getFlags}. */ public final int HAS_TIMEZONE = 1; /** Year is specified. See {@link #getFlags}. */ public final int HAS_YEAR = 2; /** Month of year is specified. See {@link #getFlags}. */ public final int HAS_MONTH = 4; /** Day of month is specified. See {@link #getFlags}. */ public final int HAS_DAY = 8; /** Time of day is specified. See {@link #getFlags}. */ public final int HAS_TIME = 16; /** * True if this GDate specification is immutable. GDate returns true, * and GDateBuilder returns false. */ boolean isImmutable(); /** * True if this GDate corresponds to a valid gregorian date value * in XML schema. */ boolean isValid(); /** * True if this date/time specification specifies a timezone. */ boolean hasTimeZone(); /** * True if this date/time specification specifies a year. */ boolean hasYear(); /** * True if this date/time specification specifies a month-of-year. */ boolean hasMonth(); /** * True if this date/time specification specifies a day-of-month. */ boolean hasDay(); /** * True if this date/time specification specifies a time-of-day. */ boolean hasTime(); /** * True if this date/time specification specifies a full date (year, month, day) */ boolean hasDate(); /** * Gets the year. Should be a four-digit year specification. */ int getYear(); /** * Gets the month-of-year. January is 1. */ int getMonth(); /** * Gets the day-of-month. The first day of each month is 1. */ int getDay(); /** * Gets the hour-of-day. Midnight is 0, and 11PM is 23. */ int getHour(); /** * Gets the minute-of-hour. Range from 0 to 59. */ int getMinute(); /** * Gets the second-of-minute. Range from 0 to 59. */ int getSecond(); /** * Gets the time zone sign. For time zones east of GMT, * this is positive; for time zones west, this is negative. */ int getTimeZoneSign(); /** * Gets the time zone hour. * This is always positive: for the sign, look at * getTimeZoneSign(). */ int getTimeZoneHour(); /** * Gets the time zone minutes. * This is always positive: for the sign, look at * getTimeZoneSign(). */ int getTimeZoneMinute(); /** * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). */ BigDecimal getFraction(); /** * Gets the rounded millisecond value. Range from 0 to 999 */ int getMillisecond(); /** * Returns the Julian date corresponding to this Gregorian date. * The Julian date (JD) is a continuous count of days from * 1 January 4713 BC. */ int getJulianDate(); /** * 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(). */ XmlCalendar getCalendar(); /** * Retrieves the value of the current time as a java.util.Date * instance. */ Date getDate(); /** * 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 gdatespec the date to compare against. */ int compareToGDate(GDateSpecification gdatespec); /** * 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}. */ int getBuiltinTypeCode(); /** * 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. */ String canonicalString(); /** * 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. */ String toString(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaParticle.java0000644000175000017500000001435311361341572023617 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import javax.xml.namespace.QName; /** * Represents a Schema particle definition. *

* The content model of a complex type is a tree of particles. Each * particle is either an {@link #ALL}, {@link #CHOICE}, {@link #SEQUENCE}, * {@link #ELEMENT}, or {@link #WILDCARD}. * All, choice and sequence particles are groups that can have child * particles; elements and wildcards are always leaves of the particle tree. *

* The tree of particles available on a schema type is minimized, that * is, it already has removed "pointless" particles such as empty * 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 { /** * Returns the particle type ({@link #ALL}, {@link #CHOICE}, * {@link #SEQUENCE}, {@link #ELEMENT}, or {@link #WILDCARD}). */ int getParticleType(); /** * An xs:all group. * See {@link #getParticleType}. */ static final int ALL = 1; /** * A xs:choice group. * See {@link #getParticleType}. */ static final int CHOICE = 2; /** * A xs:sequence group. * See {@link #getParticleType}. */ static final 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; /** * An xs:any particle, * also known as an element wildcard. * See {@link #getParticleType}. */ static final int WILDCARD = 5; /** * Returns the minOccurs value for this particle. * If it's not specified explicitly, this returns BigInteger.ONE. */ BigInteger getMinOccurs(); /** * Returns the maxOccurs value for this particle, or null if it * is unbounded. * If it's not specified explicitly, this returns BigInteger.ONE. */ BigInteger getMaxOccurs(); /** * Returns the minOccurs value, pegged to a 32-bit int for * convenience of a validating state machine that doesn't count * higher than MAX_INT anyway. */ public 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(); /** * One if minOccurs == maxOccurs == 1. */ boolean isSingleton(); /** * Applies to sequence, choice, and all particles only: returns an array * of all the particle children in order. */ SchemaParticle[] getParticleChildren(); /** * Another way to access the particle children. */ SchemaParticle getParticleChild(int i); /** * The number of children. */ int countOfParticleChild(); /** * True if this particle can start with the given element * (taking into account the structure of all child particles * of course). */ boolean canStartWithElement(QName name); /** * Returns the QNameSet of element names that can be * accepted at the beginning of this particle. */ QNameSet acceptedStartNames(); /** * True if this particle can be skipped (taking into account * both the minOcurs as well as the structure of all the * child particles) */ boolean isSkippable(); /** * For wildcards, returns a QNameSet representing the wildcard. */ QNameSet getWildcardSet(); /** * For wildcards, returns the processing code ({@link #STRICT}, {@link #LAX}, {@link #SKIP}). */ 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; /** * 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. */ SchemaType getType(); /** * For elements only: true if nillable. */ boolean isNillable(); /** * For elements only: returns the default (or fixed) text value */ String getDefaultText(); /** * For elements only: returns the default (or fixed) strongly-typed value */ XmlAnySimpleType getDefaultValue(); /** * For elements only: True if has default. If isFixed, then isDefault is always true. */ boolean isDefault(); /** * For elements only: true if is fixed value. */ boolean isFixed(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XMLStreamValidationException.java0000644000175000017500000000231411361341573026434 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; }xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlSimpleList.java0000644000175000017500000001752111361341573023502 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNonPositiveInteger.java0000644000175000017500000002207211361341572025204 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlTokenSource.java0000644000175000017500000003424011361341573023653 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at\\ * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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; /** * Represents a holder of XML that can return an {@link XmlCursor} * or copy itself to various media such as * {@link Writer Writers} or {@link File Files}. * Both {@link XmlObject} * (and thus all XML Beans) and {@link XmlCursor} are * XmlTokenSource implementations. * * @see XmlObject * @see XmlCursor */ public interface XmlTokenSource { /** * Returns the synchronization object for the document. If concurrent * multithreaded access to a document is required, the access should should * be protected by synchronizing on this monitor() object. There is one * monitor per XML document tree. */ Object monitor(); /** * Returns the XmlDocumentProperties object for the document this token * source is associated with. */ XmlDocumentProperties documentProperties(); /** * 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. *

* The text returned represents the document contents starting at * the current begin-tag or begin-document and ending at the matching * end-tag or end-document. This is same content as newReader, but * it is returned as a single string. *

* Throws an IllegalStateException if the XmlTokenSource is not * 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 * the XML, see {@link #save(OutputStream)} or {@link #save(OutputStream, XmlOptions)}. */ String xmlText(); /** * 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). */ InputStream newInputStream(); /** * 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 * not a live with the underlying store of this token source. * If this is the document node, then a Document is returned, else * a DocumentFragment is returned. */ Node newDomNode(); /** * Returns a W3C DOM Node containing the XML represented by this source. * This is a live DOM node, not a copy. Any changes made through this node * are immediately reflected in the document associated with this token * source. Depending on the kind of token this XmlTokenSource represents, * an appropriate node will be returned. */ Node getDomNode(); /** * 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)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ 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; /** * 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; /** * 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)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ 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:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
To specify thisUse this method
The character encoding to use when converting the character * data in the XML to bytess.{@link XmlOptions#setCharacterEncoding}
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 * the outer document.{@link XmlOptions#setSaveImplicitNamespaces}
Suggested namespace prefixes to use when saving. Used only * when a namespace attribute needs to be synthesized.{@link XmlOptions#setSaveSuggestedPrefixes}
That namespace attributes should occur first in elements when * the XML is saved. By default, they occur last.{@link XmlOptions#setSaveNamespacesFirst}
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 default is 2.{@link XmlOptions#setSavePrettyPrintIndent}
The additional number of spaces indented from the left * for pretty printed XML.{@link XmlOptions#setSavePrettyPrintOffset}
To minimize the number of namespace attributes generated for the * saved XML. Note that this can reduce performance significantly.{@link XmlOptions#setSaveAggresiveNamespaces}
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 * present as the value of an attribute or element.{@link XmlOptions#setUseDefaultNamespace}
To filter out processing instructions with the specified target name.{@link XmlOptions#setSaveFilterProcinst}
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}
Saving should begin on the element's contents.{@link XmlOptions#setSaveInner}
Saving should begin on the element, rather than its contents.{@link XmlOptions#setSaveOuter}
To rename the document element, or to specify the document element * for this XML.{@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. * @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 * 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)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ 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; /** * 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; /** * 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)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ void save ( Writer w, XmlOptions options ) throws IOException; /** * Prints to stdout the state of the document in which this token source is positioned. * This is very implementation specific and may change at any time. Dump can be useful * for debugging purposes. It is very different from the save methods which produce * XML text which only approximates the actual state of the document. */ void dump ( ); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java0000644000175000017500000013647411361341573023240 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlCursor.java0000644000175000017500000021017211361341573022667 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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. */ public final XmlCursor createCursor ( ) { return _currentMark == null ? null : _currentMark.createCursor(); } /** * Moves the given cursor to this bookmark, and returns it. */ 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. */ 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 ); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaType.java0000644000175000017500000010424611361341573022777 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaAttributeGroup.java0000644000175000017500000000414411361341573025032 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 an attribute group. *

* An attribute group is a syntactic construct, not a part * of the logical model. For example, types declared within an * attribute group become local to the type that uses the group - * they're not local to the attribute group itself. Therefore * in the logical model of a schema type system, an attribute * group doesn't represent anything. Its contents are merged * into the logical model at parse time. * * @see SchemaTypeLoader#findAttributeGroup */ public interface SchemaAttributeGroup extends SchemaComponent, SchemaAnnotated { /** * Returns SchemaComponent.ATTRIBUTE_GROUP. */ int getComponentType(); /** * The name of the model group. */ QName getName(); /** * Used to allow on-demand loading of attribute groups. * * @exclude */ public final static class Ref extends SchemaComponent.Ref { public Ref(SchemaAttributeGroup attributeGroup) { super(attributeGroup); } public Ref(SchemaTypeSystem system, String handle) { super(system, handle); } public final int getComponentType() { return SchemaComponent.ATTRIBUTE_GROUP; } public final SchemaAttributeGroup get() { return (SchemaAttributeGroup)getComponent(); } } /** * Returns user-specific information. * @see SchemaBookmark */ Object getUserData(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/DelegateXmlObject.java0000644000175000017500000000162611361341573024255 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * See {@link FilterXmlObject} */ public interface DelegateXmlObject { /** * This method is called to obtain the underlying XmlObject. * Implement this method to supply or compute the wrapped object. */ XmlObject underlyingXmlObject(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlTime.java0000644000175000017500000002211211361341573022303 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaTypeSystem.java0000644000175000017500000002003611361341573024176 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.File; /** * A finite set of XML Schema component definitions. *

* Every {@link SchemaComponent} such as a {@link SchemaType}, * {@link SchemaGlobalElement}, {@link SchemaGlobalAttribute}, * {@link SchemaModelGroup}, {@link SchemaAttributeGroup}, or * {@link SchemaIdentityConstraint}, is defined in exactly one * SchemaTypeSystem. (See {@link SchemaComponent#getTypeSystem()}.) * A single SchemaTypeSystem can include definitions * from any number of namespaces; one SchemaTypeSystem consists simply * of a set of component definitions that were compiled together. *

* Since every component is defined in a single SchemaTypeSystem, no * SchemaTypeSystem other than {@link XmlBeans#getBuiltinTypeSystem()} * includes any of the the built-in types. That means * you cannot ordinarily load instances using a single * SchemaTypeSystem by itself. Instead, you will want to combine a path of * SchemaTypeSystems together using {@link XmlBeans#typeLoaderUnion} * to form a SchemaTypeLoader that can be used for loading instances. *

* For example, the following code compiles the schema in myXSDFile * in the presence of only the minimal builtin type system. * The resulting SchemaTypeSystem sts contains only the definitions * from myXSD file. In order to load and validate an instance within * the context of those types, we must next construct a * {@link SchemaTypeLoader} stl that contains both * the builtin type system and the types defined within the myXSD file. *

 * SchemaTypeSystem sts = XmlBeans.compileXsd(new XmlObject[]
 *    { XmlObject.Factory.parse(myXSDFile) },
 *    XmlBeans.getBuiltinTypeSystem(),
 *    null);
 * SchemaTypeLoader stl = XmlBeans.typeLoaderUnion(new SchemaTypeLoader[]
 *    { sts, XmlBeans.getBuiltinTypeSystem() });
 * XmlObject mydoc = stl.parse(instanceFile, null, null);
 * System.out.println("Document valid: " + mydoc.validate());
 * 
*

* As you can see, for working with instances, you typically want to * work with a SchemaTypeLoader constructed from a path rather than * a solitary SchemaTypeSystem. See {@link XmlBeans#loadXsd} for * a convenient alternative to {@link XmlBeans#compileXsd}. *

* A SchemaTypeSystem is useful when you need to enumerate the exact set * of component definitions derived from a set of XSD files, for example, * when you are analyzing the contents of the XSD files themselves. * Here is how to use a SchemaTypeSystem to inspect a set of schema * definitions: *

    *
  1. First, use {@link XmlBeans#compileXsd} to compile any number * of schema files. If the schema files are valid, result will * be a SchemaTypeSystem that contains all the component definitions * from those files. It will contain no other component definitions. *
  2. Alternatively, call {@link SchemaComponent#getTypeSystem} on * a precompiled schema component to discover the SchemaTypeSystem * within which that component was originally compiled. *
  3. Once you have a SchemaTypeSystem, call: *
      *
    • {@link #globalTypes()} for all the global type definitions. *
    • {@link #globalElements()} for all the global element definitions. *
    • {@link #globalAttributes()} for all the global attribute definitions. *
    • {@link #modelGroups()} for all the named model group definitions. *
    • {@link #attributeGroups()} for all the attribute group definitions. *
    *
  4. In addition, there are special types generated for XML Beans thare * are not formally part of the Schema specification: *
      *
    • {@link #documentTypes()} returns all the document types. *
    • {@link #attributeTypes()} returns all the attribute types. *
    *
* *

* A document type is a type that contains a single global element; there * is one document type for each global element definition in a * SchemaTypeSystem. In an instance document, only the root XmlObject * can have a document type as its type. *

* Similarly, an attribute type is a type that contains a single global * attribute, and there is one attribute type for each global attribute * definition in a SchemaTypeSystem. It is possible to have a root * XmlObject representing a fragment whose type is an attribute type, * but attribute types are present mainly for symmetry and to simplify * code such as the type-tree-walking code below. *

* The global component methods above only provide a view of the top-level * components of a SchemaTypeSystem and do not include any nested * definitions. To view all the nested definitions, you will want to * traverse the entire tree of {@link SchemaType} defintions within a * SchemaTypeSystem by examining the {@link SchemaType#getAnonymousTypes()} * within each {@link SchemaType} recursively. *

The following code is a standard treewalk that visits every * {@link SchemaType} in the SchemaTypeSystem once, including nested * definitions. *

 * List allSeenTypes = new ArrayList();
 * allSeenTypes.addAll(Arrays.asList(typeSystem.documentTypes()));
 * allSeenTypes.addAll(Arrays.asList(typeSystem.attributeTypes()));
 * allSeenTypes.addAll(Arrays.asList(typeSystem.globalTypes()));
 * for (int i = 0; i < allSeenTypes.size(); i++)
 * {
 *     SchemaType sType = (SchemaType)allSeenTypes.get(i);
 *     System.out.prinlnt("Visiting " + sType.toString());
 *     allSeenTypes.addAll(Arrays.asList(sType.getAnonymousTypes()));
 * }
 * 
* * @see SchemaType * @see SchemaTypeLoader * @see XmlBeans#compileXsd * @see XmlBeans#typeLoaderUnion * @see XmlBeans#getBuiltinTypeSystem */ public interface SchemaTypeSystem extends SchemaTypeLoader { /** * Returns the name of this loader. */ public String getName(); /** * Returns the global types defined in this loader. */ public org.apache.xmlbeans.SchemaType[] globalTypes(); /** * Returns the document types defined in this loader. */ public org.apache.xmlbeans.SchemaType[] documentTypes(); /** * Returns the attribute types defined in this loader. */ public org.apache.xmlbeans.SchemaType[] attributeTypes(); /** * Returns the global elements defined in this loader. */ public SchemaGlobalElement[] globalElements(); /** * Returns the global attributes defined in this loader. */ public SchemaGlobalAttribute[] globalAttributes(); /** * Returns the model groups defined in this loader. */ public SchemaModelGroup[] modelGroups(); /** * Returns the attribute groups defined in this loader. */ public SchemaAttributeGroup[] attributeGroups(); /** * Returns the top-level annotations */ public SchemaAnnotation[] annotations(); /** * Initializes a type system (resolves all handles within the type system). */ public void resolve(); /** * Locates a type, element, or attribute using the handle. */ public SchemaComponent resolveHandle(String handle); /** * Locates a type, element, or attribute using the handle. */ public SchemaType typeForHandle(String handle); /** * Returns the classloader used by this loader for resolving types. */ public ClassLoader getClassLoader(); /** * Saves this type system to a directory. */ public void saveToDirectory(File classDir); /** * Saves this type system using a Filer */ public void save(Filer filer); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlIDREFS.java0000644000175000017500000002164311361341573022371 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlShort.java0000644000175000017500000002116311361341573022511 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaAttributeModel.java0000644000175000017500000000336411361341573025001 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 the attribute structure allowed on a complex type. * * @see SchemaType#getAttributeModel */ public interface SchemaAttributeModel { /** * Returns an array containing all the attributes in the model. */ SchemaLocalAttribute[] getAttributes(); /** * Returns the attribute with the given name. */ SchemaLocalAttribute getAttribute(QName name); /** * QNameSet representing the attribute wildcard specification. */ QNameSet getWildcardSet(); /** * Returns the processing code ({@link #STRICT}, {@link #LAX}, {@link #SKIP}). * Returns 0 ({@link #NONE}) if no wildcard specified. */ int getWildcardProcess(); /** See {@link #getWildcardProcess} */ static final int NONE = 0; /** 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; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlGYearMonth.java0000644000175000017500000002273511361341573023435 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlBase64Binary.java0000644000175000017500000002171711361341572023607 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKENS.java0000644000175000017500000002207711361341573022655 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/QNameCache.java0000644000175000017500000001053311361341573022655 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * A cache that can be used to pool QName instances. Each thread has one. */ public final class QNameCache { private static final float DEFAULT_LOAD = 0.70f; private final float loadFactor; private int numEntries = 0; private int threshold; private int hashmask; private QName[] table; /** * Creates a QNameCache with the given initialCapacity and loadFactor. * * @param initialCapacity the number of entries to initially make space for * @param loadFactor a number to control the density of the hashtable */ public QNameCache(int initialCapacity, float loadFactor) { assert initialCapacity > 0; assert loadFactor > 0 && loadFactor < 1; // Find a power of 2 >= initialCapacity int capacity = 16; while (capacity < initialCapacity) capacity <<= 1; this.loadFactor = loadFactor; this.hashmask = capacity - 1; threshold = (int)(capacity * loadFactor); table = new QName[capacity]; } /** * Creates a QNameCache with the given initialCapacity. * * @param initialCapacity the number of entries to initially make space for */ public QNameCache(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD); } public QName getName(String uri, String localName) { return getName( uri, localName, "" ); } /** * Fetches a QName with the given namespace and localname. * Creates one if one is not found in the cache. * * @param uri the namespace * @param localName the localname * @param prefix the prefix * @return the cached QName */ public QName getName(String uri, String localName, String prefix) { /* return new QName(uri, localName, prefix); */ assert localName != null; if (uri == null) uri = ""; if (prefix == null) prefix = ""; int index = hash(uri, localName, prefix) & hashmask; while (true) { QName q = table[index]; if (q == null) { numEntries++; if (numEntries >= threshold) rehash(); return table[index] = new QName(uri, localName, prefix); } else if (equals(q, uri, localName, prefix)) return q; else index = (index-1) & hashmask; } } private void rehash() { int newLength = table.length * 2; QName[] newTable = new QName[newLength]; int newHashmask = newLength - 1; for (int i = 0 ; i < table.length ; i++) { QName q = table[i]; if (q != null) { int newIndex = hash( q.getNamespaceURI(), q.getLocalPart(), q.getPrefix() ) & newHashmask; while (newTable[newIndex] != null) newIndex = (newIndex - 1) & newHashmask; newTable[newIndex] = q; } } table = newTable; hashmask = newHashmask; threshold = (int) (newLength * loadFactor); } private static int hash(String uri, String localName, String prefix) { int h = 0; h += prefix.hashCode() << 10; h += uri.hashCode() << 5; h += localName.hashCode(); return h; } private static boolean equals(QName q, String uri, String localName, String prefix) { return q.getLocalPart().equals(localName) && q.getNamespaceURI().equals(uri) && q.getPrefix().equals(prefix); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/GDate.java0000644000175000017500000010504111361341573021713 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaLocalElement.java0000644000175000017500000000320611361341573024414 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * Represents a local or global element definition. */ public interface SchemaLocalElement extends SchemaField, SchemaAnnotated { /** * True if extension is blocked. */ boolean blockExtension(); /** * True if restriction is blocked. */ boolean blockRestriction(); /** * True if element substitution is blocked. */ boolean blockSubstitution(); /** * True if this element is prohibited in content. Only * sensible if this is the head of a substitution group; * then only substitution group members can appear.

* * Although local elements cannot be abstract, if an element * use is a ref to a global element, then the flag from the * global element is copied in to the local element where the * use occurs. */ boolean isAbstract(); /** * Returns all the Key, KeyRef, and Unique constraints * on this element. */ SchemaIdentityConstraint[] getIdentityConstraints(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoader.java0000644000175000017500000001731611361341573024127 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaLocalAttribute.java0000644000175000017500000000262711361341572024773 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * Represents a local or global attribute definition. */ public interface SchemaLocalAttribute extends SchemaField, SchemaAnnotated { /** * Returns {@link #PROHIBITED}, {@link #OPTIONAL}, or {@link #REQUIRED}. * (Actually, never returns PROHIBITED because the schema specificaion * states that a prohibited attribute is equivalent to no attribute * at all, so a prohibited attribute will never be present in the compiled * model.) */ int getUse(); /** A prohibited attribute. See {@link #getUse}. */ static final int PROHIBITED = 1; /** An optional attribute. See {@link #getUse}. */ static final int OPTIONAL = 2; /** A required attribute. See {@link #getUse}. */ static final int REQUIRED = 3; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaField.java0000644000175000017500000000433611361341573023100 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.BigInteger; /** * Represents an element or an attribute declaration. * * @see SchemaType#getContainerField * @see SchemaLocalElement * @see SchemaLocalAttribute */ public interface SchemaField { /** * Returns the form-unqualified-or-qualified name. */ QName getName(); /** * True if this use is an attribute */ boolean isAttribute(); /** * True if nillable; always false for attributes. */ boolean isNillable(); /** * Returns the type of this use. */ SchemaType getType(); /** * Returns the minOccurs value for this particle. * If it is not specified explicitly, this defaults to BigInteger.ONE. */ BigInteger getMinOccurs(); /** * Returns the maxOccurs value for this particle, or null if it * is unbounded. * If it is not specified explicitly, this defaults to BigInteger.ONE. */ BigInteger getMaxOccurs(); /** * The default value as plain text. See {@link #isDefault} and {@link #isFixed}. */ String getDefaultText(); /** * The default value as a strongly-typed value. See {@link #isDefault} and {@link #isFixed}. */ XmlAnySimpleType getDefaultValue(); /** * True if a default is supplied. If {@link #isFixed}, then isDefault is always true. */ boolean isDefault(); /** * True if the value is fixed. */ boolean isFixed(); /** * Returns user-specific information. * @see SchemaBookmark */ Object getUserData(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlPositiveInteger.java0000644000175000017500000002157711361341572024542 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlOptions.java0000644000175000017500000011632211714325344023047 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 uses an internal Piccolo 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 ? Boolean.TRUE : Boolean.FALSE ); } /** * 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); } 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"; 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); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlDateTime.java0000644000175000017500000002363211361341573023111 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlDouble.java0000644000175000017500000002107611361341573022627 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlBoolean.java0000644000175000017500000002117111361341573022770 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlSaxHandler.java0000644000175000017500000000360011361341572023436 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.sax.ContentHandler; import org.xml.sax.ext.LexicalHandler; /** * A holder for a SAX {@link ContentHandler} and {@link LexicalHandler} that are * capable of loading an {@link XmlObject} instance. Once all the SAX events are pushed * to the handlers, call {@link #getObject()} to get the loaded XmlObject. * * @see XmlObject.Factory#newXmlSaxHandler * @see SchemaTypeLoader#newXmlSaxHandler */ public interface XmlSaxHandler { /** * The ContentHandler expecting SAX content events. * @see ContentHandler */ ContentHandler getContentHandler ( ); /** * The LexicalHandler expecting SAX lexical events. * @see LexicalHandler */ LexicalHandler getLexicalHandler ( ); /** * Insert a bookmark before the token associated with the last SAX event. */ void bookmarkLastEvent ( XmlCursor.XmlBookmark mark ); /** * Insert a bookmark before the attr token associated with the last SAX element event. */ void bookmarkLastAttr ( QName attrName, XmlCursor.XmlBookmark mark ); /** Returns the loaded XmlObject after all the SAX events have been finished */ XmlObject getObject ( ) throws XmlException; }xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaProperty.java0000644000175000017500000002111611361341572023673 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import javax.xml.namespace.QName; /** * Represents a summary of similar SchemaFields in a complex type. *

* In a schema type, every element with the same name must have the * same type. Therefore, all together, elements with the same name * form a coherent collection of similar elements. Similarly, attributes * can only be defined once, so each attribute obviously is a coherent * group on its own. *

* A SchemaProperty represents a summary of the the elements with a * given name or the attribute with a given name. It represents the * summary cardinality of the fields, the summary default and fixed * values, and so on. When inferring information about an element * or attribute, it is typically easier to consult then SchemaProperty * than to hunt for the exact SchemaField in the particle tree or * attribute model. * * @see SchemaType#getProperties * @see SchemaType#getAttributeProperties * @see SchemaType#getElementProperties * @see SchemaType#getAttributeProperty * @see SchemaType#getElementProperty */ public interface SchemaProperty { /** * The type within which this property appears */ SchemaType getContainerType(); /** * The name of this element or attribute */ QName getName(); /** * For element properties the set of names that are accepted for this property * if this element is the head of a substitution group. This will always * have at least one element, ie, the property's name. */ QName[] acceptedNames(); /** * The Java name for this property. For example, if the method to * access this property is called getFirstName, then this method * returns the string "FirstName". May be null if the schema type * has not been compiled to Java. */ String getJavaPropertyName(); /** * True for read-only properties. */ boolean isReadOnly(); /** * True for attributes. */ boolean isAttribute(); /** * The schema type for the property. */ SchemaType getType(); // note that in the inheritance hierarchy, if the array getter shows up first, // then the singelton getter is never allowed to show up. /** * The schema type returned from the Java getter for this property. * Applies only to types that have been code generated to Java; may * be a base type of getType(). */ public SchemaType javaBasedOnType(); // Java property type based on this base type /** * True if there is a Java getter that returns a singleton. */ boolean extendsJavaSingleton(); // has singleton getter /** * True if there is an Java isSet method that tests for presence. */ boolean extendsJavaOption(); // has isSet tester /** * True if there is a Java getter that returns an array. */ boolean extendsJavaArray(); // has array getter (called -Array, if singleton is present) /** * Returns the natural Java type for this property. Returns either * XML_OBJECT (for complex types) or one of the JAVA_* constants described * in this interface. */ int getJavaTypeCode(); /** * Returns the set of element names which should appear strictly after all * occurences of the elements described by this property. For element properties only. */ QNameSet getJavaSetterDelimiter(); /** * Returns a summarized minimum occurrance number. * For example, a sequence containing a nonoptional singleton element repeated twice will * result in a property getMinOccurs() of 2. */ BigInteger getMinOccurs(); /** * Returns a summarized minimum occurrance number. * For example, a sequence containing a nonoptional singleton element repeated twice will * result in a property getMaxOccurs() of 2. */ BigInteger getMaxOccurs(); /** * Returns {@link #NEVER}, {@link #VARIABLE}, or {@link #CONSISTENTLY} nillable, depending on the * nillability of the elements in this property. */ int hasNillable(); /** * Returns {@link #NEVER}, {@link #VARIABLE}, or {@link #CONSISTENTLY} defaulted, depending on the * defaults present in the elements in this property. */ int hasDefault(); /** * Returns {@link #NEVER}, {@link #VARIABLE}, or {@link #CONSISTENTLY} fixed, depending on the * fixed constraints present in the elements in this property. */ int hasFixed(); /** Applies to no elements for this property. See {@link #hasNillable}, {@link #hasDefault}, {@link #hasFixed} */ static final int NEVER = 0; /** Applies to some, but not other elements for this property. See {@link #hasNillable}, {@link #hasDefault}, {@link #hasFixed} */ static final int VARIABLE = 1; /** Applies to all elements for this property. See {@link #hasNillable}, {@link #hasDefault}, {@link #hasFixed} */ static final int CONSISTENTLY = 2; /** An XML Bean type that inherits from {@link XmlObject}. See {@link #getJavaTypeCode}. */ static final int XML_OBJECT = 0; /** Java primitive type codes (for non-nullable Java types) are between JAVA_FIRST_PRIMITIVE and JAVA_LAST_PRIMITIVE, inclusive. */ static final int JAVA_FIRST_PRIMITIVE = 1; /** A Java boolean. See {@link #getJavaTypeCode}. */ static final int JAVA_BOOLEAN = 1; /** A Java float. See {@link #getJavaTypeCode}. */ static final int JAVA_FLOAT = 2; /** A Java double. See {@link #getJavaTypeCode}. */ static final int JAVA_DOUBLE = 3; /** A Java byte. See {@link #getJavaTypeCode}. */ static final int JAVA_BYTE = 4; /** A Java short. See {@link #getJavaTypeCode}. */ static final int JAVA_SHORT = 5; /** A Java int. See {@link #getJavaTypeCode}. */ static final int JAVA_INT = 6; /** A Java long. See {@link #getJavaTypeCode}. */ static final int JAVA_LONG = 7; /** Java primitive type codes (for non-nullable Java types) are between JAVA_FIRST_PRIMITIVE and JAVA_LAST_PRIMITIVE, inclusive. */ static final int JAVA_LAST_PRIMITIVE = 7; /** A {@link java.math.BigDecimal}. See {@link #getJavaTypeCode}. */ static final int JAVA_BIG_DECIMAL = 8; /** A {@link java.math.BigInteger}. See {@link #getJavaTypeCode}. */ static final int JAVA_BIG_INTEGER = 9; /** A {@link String}. See {@link #getJavaTypeCode}. */ static final int JAVA_STRING = 10; /** A byte[]. See {@link #getJavaTypeCode}. */ static final int JAVA_BYTE_ARRAY = 11; /** A {@link GDate}. See {@link #getJavaTypeCode}. */ static final int JAVA_GDATE = 12; /** A {@link GDuration}. See {@link #getJavaTypeCode}. */ static final int JAVA_GDURATION = 13; /** A {@link java.util.Date}. See {@link #getJavaTypeCode}. */ static final int JAVA_DATE = 14; /** A {@link javax.xml.namespace.QName}. See {@link #getJavaTypeCode}. */ static final int JAVA_QNAME = 15; /** A {@link java.util.List}. See {@link #getJavaTypeCode}. */ static final int JAVA_LIST = 16; /** A {@link java.util.Calendar}. See {@link #getJavaTypeCode}. */ static final int JAVA_CALENDAR = 17; /** A generated {@link StringEnumAbstractBase} subclass. See {@link #getJavaTypeCode}. */ static final int JAVA_ENUM = 18; /** A {@link java.lang.Object}, used for some simple type unions. See {@link #getJavaTypeCode}. */ static final int JAVA_OBJECT = 19; // for some unions /** A user specified type. */ static final int JAVA_USER = 20; /** * Returns the default or fixed value, * if it is consistent. If it is not consistent, * then returns null. * See {@link #hasDefault} and {@link #hasFixed}. */ String getDefaultText(); /** * Returns the default or fixed value as a strongly-typed value, * if it is consistent. If it is not consistent, * then returns null. * See {@link #hasDefault} and {@link #hasFixed}. */ XmlAnySimpleType getDefaultValue(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaModelGroup.java0000644000175000017500000000376211361341573024134 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 model group. *

* A model group is a syntactic construct, not a part of * the logical model. For example, types declared within a * model group become local to the type that uses the group - * they're not local to the model group itself. Therefore in * the logical model of a schema type system, a model group * doesn't represent anything. Its contents are merged into * the logical model at parse time. */ public interface SchemaModelGroup extends SchemaComponent, SchemaAnnotated { /** * Returns SchemaComponent.GROUP. */ int getComponentType(); /** * The name of the model group. */ QName getName(); /** * Used to allow on-demand loading of model groups. * * @exclude */ public final static class Ref extends SchemaComponent.Ref { public Ref(SchemaModelGroup modelGroup) { super(modelGroup); } public Ref(SchemaTypeSystem system, String handle) { super(system, handle); } public final int getComponentType() { return SchemaComponent.MODEL_GROUP; } public final SchemaModelGroup get() { return (SchemaModelGroup)getComponent(); } } /** * Returns user-specific information. * @see SchemaBookmark */ Object getUserData(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlLineNumber.java0000644000175000017500000000461311361341572023452 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.XmlCursor.XmlBookmark; /** * A subclass of XmlBookmark that holds line number information. * If a document is parsed with line numbers * enabled, these bookmarks will be placed at appropriate locations * within the document. * * @see XmlOptions#setLoadLineNumbers */ public class XmlLineNumber extends XmlBookmark { /** * Constructs a line number with no column or offset information. * @param line the line number - the first line is 1 */ public XmlLineNumber ( int line ) { this( line, -1, -1 ); } /** * Constructs a line number and column with no file offset information. * @param line the line number - the first line is 1 * @param line the column number - the first column is 1 */ public XmlLineNumber ( int line, int column ) { this( line, column, -1 ); } /** * Constructs a line number and column with no file offset information. * @param line the line number - the first line is 1 * @param line the column number - the first column is 1 * @param line the file character offset - the first character in the file is 0 */ public XmlLineNumber ( int line, int column, int offset ) { super( false ); _line = line; _column = column; _offset = offset; } /** * Returns the 1-based line number, or -1 if not known. */ public int getLine ( ) { return _line; } /** * Returns the 1-based column number, or -1 if not known. */ public int getColumn ( ) { return _column; } /** * Returns the 0-based file offset number, or -1 if not known. */ public int getOffset ( ) { return _offset; } private int _line, _column, _offset; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlOptionsBean.java0000644000175000017500000002366411361341573023643 0ustar apoapopackage 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 ); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/GDurationSpecification.java0000644000175000017500000000454211361341573025330 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Represents an XML Schema-compatible duration. *

* Both the immutable GDuration and the mutable GDurationBuilder are * GDurationSpecifications. Use this interface where you want to * allow callers to pass any implementation of a GDuration. * * @see GDuration */ public interface GDurationSpecification { /** * True if this instance is immutable. */ boolean isImmutable(); /** * Returns the sign of the duration: +1 is forwards * and -1 is backwards in time. */ int getSign(); /** * Gets the year component. */ int getYear(); /** * Gets the month-of-year component. */ int getMonth(); /** * Gets the day-of-month component. */ int getDay(); /** * Gets the hour-of-day component. */ int getHour(); /** * Gets the minute-of-hour component. */ int getMinute(); /** * Gets the second-of-minute component. */ int getSecond(); /** * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). */ BigDecimal getFraction(); /** * Returns true if all of the individual components * of the duration are nonnegative. */ boolean isValid(); /** * 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. */ int compareToGDuration(GDurationSpecification duration); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlInt.java0000644000175000017500000002071011361341573022141 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlLong.java0000644000175000017500000002102711361341572022307 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaAnnotated.java0000644000175000017500000000157311361341573023772 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * Marker interface denoting that an annotation can be present */ public interface SchemaAnnotated { /** * Returns the Schema annotation object or null if none present */ SchemaAnnotation getAnnotation(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoaderException.java0000644000175000017500000000554211361341572026003 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * An exception that is thrown if there is corruption or a version mismatch * in a compiled schema type system. */ public class SchemaTypeLoaderException extends XmlRuntimeException { private int _code; /** Constructs an exception with the given message, filename, extension, and code */ public SchemaTypeLoaderException(String message, String name, String handle, int code) { super(message + " (" + name + "." + handle + ") - code " + code); _code = code; } /** Constructs an exception with the given message, filename, extension, code, and cause */ public SchemaTypeLoaderException(String message, String name, String handle, int code, Exception cause) { super(message + " (" + name + "." + handle + ") - code " + code); _code = code; initCause(cause); } /** Returns the reason for the failure, given by one of the numeric constants in this class */ public int getCode() { return _code; } /* See {@link #getCode}. */ public static final int NO_RESOURCE = 0; /* See {@link #getCode}. */ public static final int WRONG_MAGIC_COOKIE = 1; /* See {@link #getCode}. */ public static final int WRONG_MAJOR_VERSION = 2; /* See {@link #getCode}. */ public static final int WRONG_MINOR_VERSION = 3; /* See {@link #getCode}. */ public static final int WRONG_FILE_TYPE = 4; /* See {@link #getCode}. */ public static final int UNRECOGNIZED_INDEX_ENTRY = 5; /* See {@link #getCode}. */ public static final int WRONG_PROPERTY_TYPE = 6; /* See {@link #getCode}. */ public static final int MALFORMED_CONTENT_MODEL = 7; /* See {@link #getCode}. */ public static final int WRONG_SIMPLE_VARIETY = 8; /* See {@link #getCode}. */ public static final int IO_EXCEPTION = 9; /* See {@link #getCode}. */ public static final int INT_TOO_LARGE = 10; /* See {@link #getCode}. */ public static final int BAD_PARTICLE_TYPE = 11; /* See {@link #getCode}. */ public static final int NOT_WRITEABLE = 12; /* See {@link #getCode}. */ public static final int BAD_HANDLE = 13; /* See {@link #getCode}. */ public static final int NESTED_EXCEPTION = 14; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedLong.java0000644000175000017500000002136411361341573024011 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java0000644000175000017500000000611211361341573024711 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Collections; import java.util.Collection; import java.util.ArrayList; /** * An unchecked XML exception. * May contain any number of {@link XmlError} objects. * * @see XmlError * @see XmlException */ public class XmlRuntimeException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Constructs an XmlRuntimeException from a message. */ public XmlRuntimeException ( String m ) { super( m ); } /** * Constructs an XmlRuntimeException from a message and a cause. */ public XmlRuntimeException ( String m, Throwable t ) { super( m, t ); } /** * Constructs an XmlRuntimeException from a cause. */ public XmlRuntimeException ( Throwable t ) { super( t ); } /** * Constructs an XmlRuntimeException from a message, a cause, and a collection of XmlErrors. */ public XmlRuntimeException ( String m, Throwable t, Collection errors ) { super( m, t ); if (errors != null) _errors = Collections.unmodifiableList( new ArrayList(errors) ); } /** * Constructs an XmlRuntimeException from an XmlError. */ public XmlRuntimeException ( XmlError error ) { this( error.toString(), null, error ); } /** * Constructs an XmlRuntimeException from a message, a cause, and an XmlError. */ public XmlRuntimeException ( String m, Throwable t, XmlError error ) { this( m, t, Collections.singletonList( error ) ); } /** * Constructs an XmlRuntimeException from an {@link XmlException}. */ public XmlRuntimeException ( XmlException xmlException ) { super( xmlException.getMessage(), xmlException.getCause() ); Collection errors = xmlException.getErrors(); if (errors != null) _errors = Collections.unmodifiableList( new ArrayList( errors ) ); } /** * Returns the first {@link XmlError} that caused this exception, if any. */ public XmlError getError ( ) { if (_errors == null || _errors.size() == 0) return null; return (XmlError) _errors.get( 0 ); } /** * Returns the collection of {@link XmlError XmlErrors} that caused this exception, if any. */ public Collection getErrors ( ) { return _errors; } private List _errors; }xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlDocumentProperties.java0000644000175000017500000001553011361341572025245 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xmlbeans; /** * This class is used to attach arbitrary information to an XML * document. It also defines several well-known types of * information that can be attached or found on a document. *

* For example, suppose you wanted to associate a filename * with the document containing an xml object "xobj". This * could be done via the following code: *

* tokenSource.documentProperties().set(XmlDocumentProperties.NAME, "MyFilename.xml"); *

* To fetch the filename later, given an xobj2 anywhere in the * same document, you can write: *

* filename = (String)tokenSource.documentProperties().get(XmlDocumentProperties.NAME); */ public abstract class XmlDocumentProperties { /** * Sets the name of the XML document file. Typically a URL, but may * be any String. * @param sourceName the name to set * @see XmlOptions#setDocumentSourceName */ public void setSourceName ( String sourceName ) { put( SOURCE_NAME, sourceName ); } /** * Returns the name of the XML document file. Typically a URL, but may * be any String. * @see XmlOptions#setDocumentSourceName */ public String getSourceName ( ) { return (String) get( SOURCE_NAME ); } /** * Sets the encoding to use for the XML document. Should be a valid * XML encoding string. * @param encoding the ISO encoding name * @see XmlOptions#setCharacterEncoding */ public void setEncoding ( String encoding ) { put( ENCODING, encoding ); } /** * Returns the encoding used for the XML document, as an ISO encoding name. * @see XmlOptions#setCharacterEncoding */ public String getEncoding ( ) { return (String) get( ENCODING ); } /** * Sets the XML version string to use in the <?xml?> declaration. * (The XML specification is quite stable at "1.0".) * @param version the XML version string */ public void setVersion ( String version ) { put( VERSION, version ); } /** * Returns the XML version string used in the <?xml?> declaration. */ public String getVersion ( ) { return (String) get( VERSION ); } /** * Sets the standalone property. * @param standalone whether standalone is true or not */ public void setStandalone ( boolean standalone ) { put( STANDALONE, standalone ? "true" : null ); } /** * Returns the standalone property */ public boolean getStandalone ( ) { return get( STANDALONE ) != null; } /** * Sets the DOCTYPE name use in the <!DOCTYPE> declaration. * @param doctypename the doctypename */ public void setDoctypeName ( String doctypename ) { put( DOCTYPE_NAME, doctypename ); } /** * Returns the DOCTYPE name used in the <!DOCTYPE> declaration. */ public String getDoctypeName ( ) { return (String) get( DOCTYPE_NAME ); } /** * Sets the DOCTYPE public ID to use in the <!DOCTYPE> declaration. * @param publicid the public ID */ public void setDoctypePublicId ( String publicid ) { put( DOCTYPE_PUBLIC_ID, publicid ); } /** * Returns the DOCTYPE public ID used in the <!DOCTYPE> declaration. */ public String getDoctypePublicId ( ) { return (String) get( DOCTYPE_PUBLIC_ID ); } /** * Sets the DOCTYPE system ID to use in the <!DOCTYPE> declaration. * @param systemid the system ID */ public void setDoctypeSystemId ( String systemid ) { put( DOCTYPE_SYSTEM_ID, systemid ); } /** * Returns the DOCTYPE system ID used in the <!DOCTYPE> declaration. */ public String getDoctypeSystemId ( ) { return (String) get( DOCTYPE_SYSTEM_ID ); } /** * Sets the message digest used to summarize the document. * @param digest the bytes of the digest * * @see XmlOptions#setLoadMessageDigest */ public void setMessageDigest( byte[] digest ) { put( MESSAGE_DIGEST, digest ); } /** * Returns the message digest used to summarize the document. * * @see XmlOptions#setLoadMessageDigest */ public byte[] getMessageDigest( ) { return (byte[]) get( MESSAGE_DIGEST ); } /** * Used to store the original name (a String) for * the source from which the XML document was loaded. * This name, if present, is used to identify the * document when reporting validation or comilation errors. * * XmlObject.Factory.parse(File) and SchemaTypeLoader.loadInstance(File) * both automatically set this value to the filename. */ public static final Object SOURCE_NAME = new Object(); /** * Document encoding */ public static final Object ENCODING = new Object(); /** * Document version */ public static final Object VERSION = new Object(); /** * Document standlone */ public static final Object STANDALONE = new Object(); /** * Doc type name */ public static final Object DOCTYPE_NAME = new Object(); /** * Doc type public id */ public static final Object DOCTYPE_PUBLIC_ID = new Object(); /** * Doc type system id */ public static final Object DOCTYPE_SYSTEM_ID = new Object(); /** * SHA message digest */ public static final Object MESSAGE_DIGEST = new Object(); /** * Attaches a value to the root of the document containing * the given token source. * * @param key The key: there can be one value for each key. * @param value The value to attach to the document. */ public abstract Object put ( Object key, Object value ); /** * Returns a value previously attached to a document using set. * * @param key The key: this is the key that was previously * passed to set to store the value. * @return The saved value, or null if none is found. */ public abstract Object get ( Object key ); /** * Removes a value previously attached to a document using set. * * @param key The key: this is the key that was previously * passed to set to store the value. */ public abstract Object remove ( Object key ); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/BindingConfig.java0000644000175000017500000000713211361341573023431 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Get the package name for a namespace or null. */ public String lookupPackageForNamespace(String uri) { return null; } /** * Get the prefix applied to each java name for a namespace or null. */ public String lookupPrefixForNamespace(String uri) { return null; } /** * Get the suffix applied to each java name for a namespace or null. */ public String lookupSuffixForNamespace(String uri) { return null; } /** * Get the java name for a QName or null. * @deprecated replaced with {@link #lookupJavanameForQName(QName, int)} */ public String lookupJavanameForQName(QName qname) { return null; } /** * Get the java name for a QName of a specific component kind, or null. * @see #QNAME_TYPE * @see #QNAME_TYPE_DOCUMENT * @see #QNAME_METHOD_ELEMENT * @see #QNAME_METHOD_ATTRIBUTE */ public String lookupJavanameForQName(QName qname, int kind) { return null; } /** * Returns all configured InterfaceExtensions or an empty array. */ public InterfaceExtension[] getInterfaceExtensions() { return EMPTY_INTERFACE_EXT_ARRAY; } /** * Returns 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; } /** * Returns all configued PrePostExtensions or an empty array. */ public PrePostExtension[] getPrePostExtensions() { return EMPTY_PREPOST_EXT_ARRAY; } /** * Returns the PrePostExtension defined for the fully qualified java * type generated from schema compilation or null. */ public PrePostExtension getPrePostExtension(String fullJavaName) { return null; } /** * Returns all defined user types. */ public UserType[] getUserTypes() { return EMPTY_USER_TYPE_ARRY; } /** * Returns a user defined Java type for a given QName. */ public UserType lookupUserTypeForQName(QName qname) { return null; } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlByte.java0000644000175000017500000002065311361341572022317 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SimpleValue.java0000644000175000017500000002577511361341573023174 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/QNameSet.java0000644000175000017500000003711111361341572022405 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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(); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedByte.java0000644000175000017500000002216211361341573024012 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/FilterXmlObject.java0000644000175000017500000004633711361341573024000 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNOTATION.java0000644000175000017500000002047511361341572022651 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/StringEnumAbstractBase.java0000644000175000017500000000663511361341573025312 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.List; import java.util.ArrayList; /** * The base class for code-generated string enumeration value classes. *

* Subclasses are intended to be final types with a finite set of * singleton instances. Each instance has a string value, which * it returns via {@link #toString}, and an int value for the purpose * of switching in case statements, returned via {@link #intValue}. *

* Each subclass manages an instance of {@link StringEnumAbstractBase.Table}, * which holds all the singleton instances for the subclass. A Table * can return a singleton instance given a String or an integer code. */ public class StringEnumAbstractBase implements java.io.Serializable { private static final long serialVersionUID = 1L; private String _string; private int _int; /** * Singleton instances should only be created by subclasses. */ protected StringEnumAbstractBase(String s, int i) { _string = s; _int = i; } /** Returns the underlying string value */ public final String toString() { return _string; } /** Returns an int code that can be used for switch statements */ public final int intValue() { return _int; } /** Returns the hash code of the underlying string */ public final int hashCode() { return _string.hashCode(); } /** * Used to manage singleton instances of enumerations. * Each subclass of StringEnumAbstractBase has an instance * of a table to hold the singleton instances. */ public static final class Table { private Map _map; private List _list; public Table(StringEnumAbstractBase[] array) { _map = new HashMap(array.length); _list = new ArrayList(array.length + 1); for (int i = 0; i < array.length; i++) { _map.put(array[i].toString(), array[i]); int j = array[i].intValue(); while (_list.size() <= j) _list.add(null); _list.set(j, array[i]); } } /** Returns the singleton for a {@link String}, or null if none. */ public StringEnumAbstractBase forString(String s) { return (StringEnumAbstractBase)_map.get(s); } /** Returns the singleton for an int code, or null if none. */ public StringEnumAbstractBase forInt(int i) { if (i < 0 || i > _list.size()) return null; return (StringEnumAbstractBase)_list.get(i); } /** Returns the last valid int code (the first is 1; zero is not used). */ public int lastInt() { return _list.size() - 1; } } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlGYear.java0000644000175000017500000002306011361341573022417 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/GDuration.java0000644000175000017500000003154611403474652022635 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Represents an XML Schema-compatible duration. *

* A duration is made up of a number of years, months, days, hours, * minutes, seconds, and fractions of seconds. See the * XML Schema specification * section on xs:duration * for details on the rules for * comparing durations and * adding durations to dates. */ public final class GDuration 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 GDuration representing zero seconds. */ public GDuration() { _sign = +1; _fs = GDate._zero; } private static final int SEEN_NOTHING = 0; private static final int SEEN_YEAR = 1; private static final int SEEN_MONTH = 2; private static final int SEEN_DAY = 3; private static final int SEEN_HOUR = 4; private static final int SEEN_MINUTE = 5; private static final int SEEN_SECOND = 6; /** * Constructs a GDuration 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 GDuration(CharSequence str) { // Form: -PnYnMnDTnHnMnS // (where each n may be unsigned integer, i.e., an integer that conforms to the pattern [0-9]+ // {was: preceded by a - for us}, and the whole may be -) // first trim XML whitespace int len = str.length(); int start = 0; while (len > 0 && GDate.isSpace(str.charAt(len - 1))) len -= 1; while (start < len && GDate.isSpace(str.charAt(start))) start += 1; _sign = 1; boolean tmark = false; if (start < len && str.charAt(start) == '-') { _sign = -1; start += 1; } if (start >= len || str.charAt(start) != 'P') throw new IllegalArgumentException("duration must begin with P"); start += 1; int seen = SEEN_NOTHING; _fs = GDate._zero; for (;start < len; start += 1) { char ch = str.charAt(start); if (ch == 'T') { if (tmark) throw new IllegalArgumentException("duration must have no more than one T'"); if (seen > SEEN_DAY) throw new IllegalArgumentException("T in duration must precede time fields"); seen = SEEN_DAY; tmark = true; start += 1; if (start >= len) throw new IllegalArgumentException("illegal duration"); ch = str.charAt(start); } if (!GDate.isDigit(ch)) throw new IllegalArgumentException("illegal duration at char[" + start + "]: '" + ch + "'"); int value = GDate.digitVal(ch); for (;;) { start += 1; ch = (start < len) ? str.charAt(start) : '\0'; if (!GDate.isDigit(ch)) break; value = value * 10 + GDate.digitVal(ch); } if (ch == '.') { int i = start; do i += 1; while (i < len && GDate.isDigit(ch = str.charAt(i))); _fs = new BigDecimal(str.subSequence(start, i).toString()); if (i >= len || ch != 'S') throw new IllegalArgumentException("illegal duration"); start = i; } switch (seen) { case SEEN_NOTHING: if (ch == 'Y') { seen = SEEN_YEAR; _CY = value; break; } // fallthrough case SEEN_YEAR: if (ch == 'M') { seen = SEEN_MONTH; _M = value; break; } // fallthrough case SEEN_MONTH: if (ch == 'D') { seen = SEEN_DAY; _D = value; break; } // fallthrough case SEEN_DAY: if (ch == 'H') { if (!tmark) throw new IllegalArgumentException("time in duration must follow T"); seen = SEEN_HOUR; _h = value; break; } // fallthrough case SEEN_HOUR: if (ch == 'M') { if (!tmark) throw new IllegalArgumentException("time in duration must follow T"); seen = SEEN_MINUTE; _m = value; break; } // fallthrough case SEEN_MINUTE: if (ch == 'S') { if (!tmark) throw new IllegalArgumentException("time in duration must follow T"); seen = SEEN_SECOND; _s = value; break; } // fallthrough default: throw new IllegalArgumentException("duration must specify Y M D T H M S in order"); } } if ( seen == SEEN_NOTHING ) throw new IllegalArgumentException("duration must contain at least one number and its designator: " + str); } /** * Constructs a GDuration 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 GDuration( 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 GDuration from another GDurationSpecification. */ public GDuration(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 GDate with the same value * as this one. */ public Object clone() { return new GDuration(this); } /** * 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. */ 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); } /** * 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); } /** * Returns a new GDuration which is the sum of this one and the * supplied duration. Does a fieldwise addition, with no normalization. */ public GDuration add(GDurationSpecification duration) { int sign = _sign * duration.getSign(); return _add(duration, sign); } /** * Returns a new GDuration which is the result of subtracting * the supplied duration from this one. Does a fieldwise * subtraction, with no normalization. */ public GDuration subtract(GDurationSpecification duration) { int sign = -_sign * duration.getSign(); return _add(duration, sign); } private GDuration _add(GDurationSpecification duration, int sign) { GDuration result = new GDuration(this); result._CY += sign * duration.getYear(); result._M += sign * duration.getMonth(); result._D += sign * duration.getDay(); result._h += sign * duration.getHour(); result._m += sign * duration.getMinute(); result._s += sign * duration.getSecond(); if (duration.getFraction().signum() == 0) return result; if (result._fs.signum() == 0 && sign == 1) result._fs = duration.getFraction(); else result._fs = sign > 0 ? result._fs.add(duration.getFraction()) : result._fs.subtract(duration.getFraction()); return result; } /** * Two GDurations are equal if all their fields are equal. * The equals function does not apply normalizatin. */ public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof GDuration)) return false; GDuration duration = (GDuration)obj; return (_sign == duration.getSign() && _CY == duration.getYear() && _M == duration.getMonth() && _D == duration.getDay() && _h == duration.getHour() && _m == duration.getMinute() && _s == duration.getSecond() && _fs.equals(duration.getFraction())); } public int hashCode() { return (_s + _m * (60 + 7) + _h * (60 * 60 + 7) + _D * (60 * 60 * 24 + 7) + _M * (60 * 60 * 24 * 31 + 7) + _CY *(60 * 60 * 24 * 372 + 7) + _sign * 11917049); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java0000644000175000017500000005264211361341573023723 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Collections; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * Used to build {@link QNameSet QNameSets}. */ public class QNameSetBuilder implements QNameSetSpecification, java.io.Serializable { private static final long serialVersionUID = 1L; private boolean _inverted; private Set _includedURIs; private Set _excludedQNames; private Set _includedQNames; /** * Constructs an empty QNameSetBuilder. */ public QNameSetBuilder() { _inverted = false; _includedURIs = new HashSet(); _excludedQNames = new HashSet(); _includedQNames = new HashSet(); } /** * Constructs a QNameSetBuilder whose initial contents are given by * another QNameSetSpecification. * @param set the QNameSetSpecificaiton to copy */ public QNameSetBuilder(QNameSetSpecification set) { Set includedURIs = set.includedURIs(); if (includedURIs != null) { _inverted = false; _includedURIs = new HashSet(includedURIs); _excludedQNames = new HashSet(set.excludedQNamesInIncludedURIs()); _includedQNames = new HashSet(set.includedQNamesInExcludedURIs()); } else { _inverted = true; _includedURIs = new HashSet(set.excludedURIs()); _excludedQNames = new HashSet(set.includedQNamesInExcludedURIs()); _includedQNames = new HashSet(set.excludedQNamesInIncludedURIs()); } } /** * Constructs a QNameSetBuilder whose inital contents are given by * the four sets. Exactly one of either excludedURIs or includedURIs must * be non-null. * * @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 */ public QNameSetBuilder(Set excludedURIs, Set includedURIs, Set excludedQNamesInIncludedURIs, Set includedQNamesInExcludedURIs) { if (includedURIs != null && excludedURIs == null) { _inverted = false; _includedURIs = new HashSet(includedURIs); _excludedQNames = new HashSet(excludedQNamesInIncludedURIs); _includedQNames = new HashSet(includedQNamesInExcludedURIs); } else if (excludedURIs != null && includedURIs == null) { _inverted = true; _includedURIs = new HashSet(excludedURIs); _excludedQNames = new HashSet(includedQNamesInExcludedURIs); _includedQNames = new HashSet(excludedQNamesInIncludedURIs); } else throw new IllegalArgumentException("Exactly one of excludedURIs and includedURIs must be null"); } /** * Constructs a QNameSetBuilder whose initial contents are given * as a list of namespace URIs, using the same format used by wildcards * in XSD files. * * @param str a wildcard namespace specification string such as "##any", * "##other", "##local", "##targetNamespace", or a space-separated * list of URIs. * @param targetURI the current targetNamespace */ public QNameSetBuilder(String str, String targetURI) { this(); if (str == null) str = "##any"; String[] uri = splitList(str); for (int i = 0; i < uri.length; i++) { String adduri = uri[i]; if (adduri.startsWith("##")) { if (adduri.equals("##other")) { if (targetURI == null) throw new IllegalArgumentException(); QNameSetBuilder temp = new QNameSetBuilder(); temp.addNamespace(targetURI); temp.addNamespace(""); temp.invert(); addAll(temp); continue; } else if (adduri.equals("##any")) { clear(); invert(); continue; } else if (uri[i].equals("##targetNamespace")) { if (targetURI == null) throw new IllegalArgumentException(); adduri = targetURI; } else if (uri[i].equals("##local")) { adduri = ""; } } addNamespace(adduri); } } /** * Local xml names are hased using "" as the namespace. */ private static String nsFromName(QName QName) { String ns = QName.getNamespaceURI(); return ns == null ? "" : ns; } private static final String[] EMPTY_STRINGARRAY = new String[0]; private static boolean isSpace(char ch) { switch (ch) { case ' ': case '\t': case '\r': case '\n': return true; default: return false; } } private static String[] splitList(String s) { if (s.length() == 0) return EMPTY_STRINGARRAY; List result = new ArrayList(); int i = 0; int start = 0; for (;;) { while (i < s.length() && isSpace(s.charAt(i))) i += 1; if (i >= s.length()) return (String[])result.toArray(EMPTY_STRINGARRAY); start = i; while (i < s.length() && !isSpace(s.charAt(i))) i += 1; result.add(s.substring(start, i)); } } /** * Remove all xml names from qnameset whose namespace matches the uri. */ private static void removeAllMatchingNs(String uri, Set qnameset) { for (Iterator i = qnameset.iterator(); i.hasNext(); ) { if (uri.equals(nsFromName((QName)i.next()))) i.remove(); } } /** * Remove all xml names from qnameset whose namespace is in the * first set of uris but not the second. */ private static void removeAllMatchingFirstOnly(Set setFirst, Set setSecond, Set qnameset) { for (Iterator i = qnameset.iterator(); i.hasNext(); ) { String ns = nsFromName((QName)i.next()); if (setFirst.contains(ns) && !setSecond.contains(ns)) i.remove(); } } /** * Remove all xml names from qnameset whose namespace is in both * sets of uris. */ private static void removeAllMatchingBoth(Set setFirst, Set setSecond, Set qnameset) { for (Iterator i = qnameset.iterator(); i.hasNext(); ) { String ns = nsFromName((QName)i.next()); if (setFirst.contains(ns) && setSecond.contains(ns)) i.remove(); } } /** * Remove all xml names from qnameset whose namespace is in neither * set of uris. */ private static void removeAllMatchingNeither(Set setFirst, Set setSecond, Set qnameset) { for (Iterator i = qnameset.iterator(); i.hasNext(); ) { String ns = nsFromName((QName)i.next()); if (!setFirst.contains(ns) && !setSecond.contains(ns)) i.remove(); } } /** * 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.size() == 0 && _includedQNames.size() == 0; } /** * True if this ModelTransitionSet contains no QNames. */ public boolean isEmpty() { return !_inverted && _includedURIs.size() == 0 && _includedQNames.size() == 0; } /** * Returns a new QNameSet that is the intersection of this one and another. */ 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. */ 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() { return QNameSet.forSets(includedURIs(), excludedURIs(), includedQNamesInExcludedURIs(), excludedQNamesInIncludedURIs()); } /** * True if the parameter is a subset of this set. */ public boolean containsAll(QNameSetSpecification set) { if (!_inverted && set.excludedURIs() != null) return false; return inverse().isDisjoint(set); } /** * True if the given set is disjoint from this one. */ 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; } /** * Clears this QNameSetBuilder */ public void clear() { _inverted = false; _includedURIs.clear(); _excludedQNames.clear(); _includedQNames.clear(); } /** * Inverts this QNameSetBuilder. */ public void invert() { _inverted = !_inverted; } /** * Adds a single QName to this QNameSetBuilder. */ public void add(QName qname) { if (!_inverted) addImpl(qname); else removeImpl(qname); } /** * Adds an entire namespace URI of QNames to this QNameSetBuilder. * The empty string is used to signifiy the (local) no-namespace. */ public void addNamespace(String uri) { if (!_inverted) addNamespaceImpl(uri); else removeNamespaceImpl(uri); } /** * Adds the contents of another QNameSet to this QNameSetBuilder. */ public void addAll(QNameSetSpecification set) { if (_inverted) removeAllImpl(set.includedURIs(), set.excludedURIs(), set.includedQNamesInExcludedURIs(), set.excludedQNamesInIncludedURIs()); else addAllImpl(set.includedURIs(), set.excludedURIs(), set.includedQNamesInExcludedURIs(), set.excludedQNamesInIncludedURIs()); } /** * Removes the given qname from this QNameSetBuilder. */ public void remove(QName qname) { if (_inverted) addImpl(qname); else removeImpl(qname); } /** * Removes an entire namespace URI from this QNameSetBuilder. */ public void removeNamespace(String uri) { if (_inverted) addNamespaceImpl(uri); else removeNamespaceImpl(uri); } /** * Removes all contents of a given QNameSet from this QNameSetBuilder. */ public void removeAll(QNameSetSpecification set) { if (_inverted) addAllImpl(set.includedURIs(), set.excludedURIs(), set.includedQNamesInExcludedURIs(), set.excludedQNamesInIncludedURIs()); else removeAllImpl(set.includedURIs(), set.excludedURIs(), set.includedQNamesInExcludedURIs(), set.excludedQNamesInIncludedURIs()); } /** * Restricts the contents of this QNameSetBuilder to be a subset of the * given QNameSet. In other words, computes an intersection. */ public void restrict(QNameSetSpecification set) { if (_inverted) addAllImpl(set.excludedURIs(), set.includedURIs(), set.excludedQNamesInIncludedURIs(), set.includedQNamesInExcludedURIs()); else removeAllImpl(set.excludedURIs(), set.includedURIs(), set.excludedQNamesInIncludedURIs(), set.includedQNamesInExcludedURIs()); } /** * Implementation of add(qname) that ignores inversion. */ private void addImpl(QName qname) { if (_includedURIs.contains(nsFromName(qname))) _excludedQNames.remove(qname); else _includedQNames.add(qname); } /** * Implementation of add(ns) that ignores inversion. */ private void addNamespaceImpl(String uri) { if (_includedURIs.contains(uri)) { removeAllMatchingNs(uri, _excludedQNames); } else { removeAllMatchingNs(uri, _includedQNames); _includedURIs.add(uri); } } /** * Implementation of add(set) that ignores inversion. */ private void addAllImpl(Set includedURIs, Set excludedURIs, Set includedQNames, Set excludedQNames) { boolean exclude = (excludedURIs != null); Set specialURIs = exclude ? excludedURIs : includedURIs; for (Iterator i = _excludedQNames.iterator(); i.hasNext(); ) { QName name = (QName)i.next(); String uri = nsFromName(name); if ((exclude ^ specialURIs.contains(uri)) && !excludedQNames.contains(name)) i.remove(); } for (Iterator i = excludedQNames.iterator(); i.hasNext(); ) { QName name = (QName)i.next(); String uri = nsFromName(name); if (!_includedURIs.contains(uri) && !_includedQNames.contains(name)) _excludedQNames.add(name); } for (Iterator i = includedQNames.iterator(); i.hasNext(); ) { QName name = (QName)i.next(); String uri = nsFromName(name); if (!_includedURIs.contains(uri)) _includedQNames.add(name); else _excludedQNames.remove(name); } if (!exclude) { removeAllMatchingFirstOnly(includedURIs, _includedURIs, _includedQNames); _includedURIs.addAll(includedURIs); } else { removeAllMatchingNeither(excludedURIs, _includedURIs, _includedQNames); for (Iterator i = _includedURIs.iterator(); i.hasNext(); ) { String uri = (String)i.next(); if (!excludedURIs.contains(uri)) i.remove(); } for (Iterator i = excludedURIs.iterator(); i.hasNext(); ) { String uri = (String)i.next(); if (!_includedURIs.contains(uri)) _includedURIs.add(uri); else _includedURIs.remove(uri); } Set temp = _excludedQNames; _excludedQNames = _includedQNames; _includedQNames = temp; _inverted = !_inverted; } } /** * Implementation of remove(qname) that ignores inversion. */ private void removeImpl(QName qname) { if (_includedURIs.contains(nsFromName(qname))) _excludedQNames.add(qname); else _includedQNames.remove(qname); } /** * Implementation of remove(ns) that ignores inversion. */ private void removeNamespaceImpl(String uri) { if (_includedURIs.contains(uri)) { removeAllMatchingNs(uri, _excludedQNames); _includedURIs.remove(uri); } else { removeAllMatchingNs(uri, _includedQNames); } } /** * Implementation of remove(set) that ignores inversion. */ private void removeAllImpl(Set includedURIs, Set excludedURIs, Set includedQNames, Set excludedQNames) { boolean exclude = (excludedURIs != null); Set specialURIs = exclude ? excludedURIs : includedURIs; for (Iterator i = _includedQNames.iterator(); i.hasNext(); ) { QName name = (QName)i.next(); String uri = nsFromName(name); if (exclude ^ specialURIs.contains(uri)) { if (!excludedQNames.contains(name)) i.remove(); } else { if (includedQNames.contains(name)) i.remove(); } } for (Iterator i = includedQNames.iterator(); i.hasNext(); ) { QName name = (QName)i.next(); String uri = nsFromName(name); if (_includedURIs.contains(uri)) _excludedQNames.add(name); } for (Iterator i = excludedQNames.iterator(); i.hasNext(); ) { QName name = (QName)i.next(); String uri = nsFromName(name); if (_includedURIs.contains(uri) && !_excludedQNames.contains(name)) _includedQNames.add(name); } if (exclude) { removeAllMatchingFirstOnly(_includedURIs, excludedURIs, _excludedQNames); } else { removeAllMatchingBoth(_includedURIs, includedURIs, _excludedQNames); } for (Iterator i = _includedURIs.iterator(); i.hasNext(); ) { if (exclude ^ specialURIs.contains(i.next())) i.remove(); } } public Set excludedURIs() { if (_inverted) return Collections.unmodifiableSet(_includedURIs); return null; } public Set includedURIs() { if (!_inverted) return _includedURIs; return null; } public Set excludedQNamesInIncludedURIs() { return Collections.unmodifiableSet(_inverted ? _includedQNames : _excludedQNames); } 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("QNameSetBuilder"); 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(); } /** * Returns a {@link QNameSet} equivalent to the current state of this * QNameSetBuilder. */ public QNameSet toQNameSet() { return QNameSet.forSpecification(this); } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlFloat.java0000644000175000017500000002075611361341573022466 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlAnyURI.java0000644000175000017500000002024311361341573022517 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaTypeElementSequencer.java0000644000175000017500000000275711361341573026170 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * This class is used to programatically validate the contents of an * XML element.Call to both {@link #next} and {@link #peek} * will return true if the element * with the provided name is allowed at the current position in the element * content, the difference being that {@link #next} will advance * the current position, while {@link #peek} won't. * * @see SchemaType#getElementSequencer */ public interface SchemaTypeElementSequencer { /** * Returns true if the element with the given name is valid at the * current position. Advances the current position. */ boolean next(QName elementName); /** * Return true if the element with the given name is valid at the * current position. Does not advance the current position. */ boolean peek(QName elementName); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlDuration.java0000644000175000017500000002143511361341572023200 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKEN.java0000644000175000017500000002104011361341572022516 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 } } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaGlobalElement.java0000644000175000017500000000516711361341573024572 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 global element definition. * * @see SchemaTypeLoader#findElement */ public interface SchemaGlobalElement extends SchemaLocalElement, SchemaComponent { /** * Set of QNames for elements that are the members of the * substitution group for which this element is the head, * not including this element. */ QName[] substitutionGroupMembers(); /** * The element that is the head of this element's substitution * group, or null if this element is not a member * of a substitution group. */ SchemaGlobalElement substitutionGroup(); /** * True if using this element as the head of a substitution * group for a substitution via type extension is prohibited. * If both finalExtension and finalRestriction are true, this * element cannot be head of a substitution group. * Sensible only for global elements. */ public boolean finalExtension(); /** * True if using this element as the head of a substitution * group for a substitution via type restriction is prohibited. * If both finalExtension and finalRestriction are true, this * element cannot be head of a substitution group. * Sensible only for global elements. */ public boolean finalRestriction(); /** * Used to allow on-demand loading of elements. * * @exclude */ public final static class Ref extends SchemaComponent.Ref { public Ref(SchemaGlobalElement element) { super(element); } public Ref(SchemaTypeSystem system, String handle) { super(system, handle); } public final int getComponentType() { return SchemaComponent.ELEMENT; } public final SchemaGlobalElement get() { return (SchemaGlobalElement)getComponent(); } } /** * Retruns a SchemaGlobalElement.Ref pointing to this element itself. */ public Ref getRef(); } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/SchemaCodePrinter.java0000644000175000017500000000233111361341572024263 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; } xmlbeans-2.6.0/src/xmlpublic/org/apache/xmlbeans/XmlOptionCharEscapeMap.java0000644000175000017500000001073711361341573025244 0ustar apoapo/* Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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). *

*