pax_global_header00006660000000000000000000000064145144713270014522gustar00rootroot0000000000000052 comment=b7f9d851b854686ccbc1495ad8c71615265f6b71 jsonp-api-2.1.3-RELEASE/000077500000000000000000000000001451447132700145035ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/.github/000077500000000000000000000000001451447132700160435ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/.github/workflows/000077500000000000000000000000001451447132700201005ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/.github/workflows/maven.yml000066400000000000000000000020351451447132700217310ustar00rootroot00000000000000# # Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation # # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v. 2.0 which is available at # http://www.eclipse.org/legal/epl-2.0, # or the Eclipse Distribution License v. 1.0 which is available at # http://www.eclipse.org/org/documents/edl-v10.php. # # SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause # name: JSON-P API on: pull_request: push: concurrency: group: ${{ github.ref }} cancel-in-progress: true jobs: build: name: Test on JDK ${{ matrix.java_version }} runs-on: ubuntu-latest strategy: matrix: java_version: [ 11, 17, 21 ] steps: - name: Checkout for build uses: actions/checkout@v3 - name: Set up JDK uses: actions/setup-java@v3 with: distribution: 'zulu' java-version: ${{ matrix.java_version }} cache: 'maven' - name: Verify run: cd api && mvn -B -V -U -C -Poss-release -Pstaging clean verify -Dgpg.skip=true jsonp-api-2.1.3-RELEASE/.gitignore000066400000000000000000000003471451447132700164770ustar00rootroot00000000000000# Maven noise target/ # OSX noise .DS_Store # IntelliJ Idea noise .idea *.iws *.ipr *.iml # Eclipse noise .settings/ .classpath .project # NetBeans noise nbproject/ # VS Code noise .vscode/ # Java noise *.class *err_pid*.log jsonp-api-2.1.3-RELEASE/CONTRIBUTING.md000066400000000000000000000056641451447132700167470ustar00rootroot00000000000000[//]: # " Copyright (c) 2018, 2020 Oracle and/or its affiliates. All rights reserved. " [//]: # " " [//]: # " This program and the accompanying materials are made available under the " [//]: # " terms of the Eclipse Public License v. 2.0, which is available at " [//]: # " http://www.eclipse.org/legal/epl-2.0. " [//]: # " " [//]: # " This Source Code may also be made available under the following Secondary " [//]: # " Licenses when the conditions for such availability set forth in the " [//]: # " Eclipse Public License v. 2.0 are satisfied: GNU General Public License, " [//]: # " version 2 with the GNU Classpath Exception, which is available at " [//]: # " https://www.gnu.org/software/classpath/license.html. " [//]: # " " [//]: # " SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 " # Contributing to Jakarta JSON Processing Thanks for your interest in this project. ## Project description Jakarta JSON Processing is a Java API to process (e.g. parse, generate, transform and query) JSON documents. It produces and consumes JSON in a streaming fashion (similar to StAX API for XML) and allows to build a Java object model for JSON using API classes (similar to DOM API for XML). * https://projects.eclipse.org/projects/ee4j.jsonp ## Developer resources Information regarding source code management, builds, coding standards, and more. * https://projects.eclipse.org/projects/ee4j.jsonp/developer The project maintains the following source code repositories * https://github.com/eclipse-ee4j/jsonp ## Eclipse Development Process This Eclipse Foundation open project is governed by the Eclipse Foundation Development Process and operates under the terms of the Eclipse IP Policy. The Jakarta EE Specification Committee has adopted the Jakarta EE Specification Process (JESP) in accordance with the Eclipse Foundation Specification Process v1.2 (EFSP) to ensure that the specification process is complied with by all Jakarta EE specification projects. * https://eclipse.org/projects/dev_process * https://www.eclipse.org/org/documents/Eclipse_IP_Policy.pdf * https://jakarta.ee/about/jesp/ * https://www.eclipse.org/legal/efsp_non_assert.php ## Eclipse Contributor Agreement Before your contribution can be accepted by the project team contributors must electronically sign the Eclipse Contributor Agreement (ECA). * http://www.eclipse.org/legal/ECA.php Commits that are provided by non-committers must have a Signed-off-by field in the footer indicating that the author is aware of the terms by which the contribution has been provided to the project. The non-committer must additionally have an Eclipse Foundation account and must have a signed Eclipse Contributor Agreement (ECA) on file. For more information, please see the Eclipse Committer Handbook: https://www.eclipse.org/projects/handbook/#resources-commit ## Contact Contact the project developers via the project's "dev" list. * https://dev.eclipse.org/mailman/listinfo/jsonp-devjsonp-api-2.1.3-RELEASE/LICENSE.md000066400000000000000000001044141451447132700161130ustar00rootroot00000000000000# Eclipse Public License - v 2.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution "originates" from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works. "Contributor" means any person or entity that Distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions Distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors. "Derivative Works" shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. "Modified Works" shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof. "Distribute" means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy. "Source Code" means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files. "Secondary License" means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3). 3. REQUIREMENTS 3.1 If a Contributor Distributes the Program in any form, then: a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license: i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3. 3.2 When the Program is Distributed as Source Code: a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and b) a copy of this Agreement must be included with each copy of the Program. 3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability ("notices") contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement. Exhibit A - Form of Secondary Licenses Notice "This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}." Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. --- ## The GNU General Public License (GPL) Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. One line to give the program's name and a brief idea of what it does. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. --- ## CLASSPATH EXCEPTION Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License version 2 cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. jsonp-api-2.1.3-RELEASE/NOTICE.md000066400000000000000000000064111451447132700160100ustar00rootroot00000000000000[//]: # " Copyright (c) 2018, 2020 Oracle and/or its affiliates. All rights reserved. " [//]: # " " [//]: # " This program and the accompanying materials are made available under the " [//]: # " terms of the Eclipse Public License v. 2.0, which is available at " [//]: # " http://www.eclipse.org/legal/epl-2.0. " [//]: # " " [//]: # " This Source Code may also be made available under the following Secondary " [//]: # " Licenses when the conditions for such availability set forth in the " [//]: # " Eclipse Public License v. 2.0 are satisfied: GNU General Public License, " [//]: # " version 2 with the GNU Classpath Exception, which is available at " [//]: # " https://www.gnu.org/software/classpath/license.html. " [//]: # " " [//]: # " SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 " # Notices for Jakarta JSON Processing This content is produced and maintained by the Jakarta JSON Processing project. * Project home: https://projects.eclipse.org/projects/ee4j.jsonp ## Trademarks Jakarta JSON Processing is a trademark of the Eclipse Foundation. ## Copyright All content is the property of the respective authors or their employers. For more information regarding authorship of content, please consult the listed source code repository logs. ## Declared Project Licenses This program and the accompanying materials are made available under the terms of the Eclipse Public License v. 2.0 which is available at http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU General Public License v2.0 w/Classpath exception which is available at https://www.gnu.org/software/classpath/license.html. SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 ## Source Code The project maintains the following source code repositories: * https://github.com/eclipse-ee4j/jsonp ## Third-party Content This project leverages the following third party content. javax.ws.rs-api:2.0.1 (2.0.1) * License: (CDDL-1.1 OR GPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0) AND Apache-2.0 * Project: https://github.com/jax-rs/api * Source: https://github.com/jax-rs/api javax.ws.rs:jsr311-api:jar:1.1.1 (1.1.1) * License: CDDL-1.0 AND Apache-2.0 * Project: https://github.com/jax-rs/api * Source: http://search.maven.org/remotecontent?filepath=javax/ws/rs/jsr311-api/1.1.1/jsr311-api-1.1.1-sources.jar javax:javaee-web-api:jar:7.0 (7.0) * License: (CDDL-1.0 OR GPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0) AND (EPL-1.0 OR BSD-3-Clause) AND Apache-2.0 AND LicenseRef-Public Domain * Project: https://javaee.github.io * Source: http://search.maven.org/remotecontent?filepath=javax/javaee-web-api/7.0/javaee-web-api-7.0-sources.jar JUnit (4.12) * License: Eclipse Public License ## Cryptography Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.jsonp-api-2.1.3-RELEASE/README.md000066400000000000000000000052421451447132700157650ustar00rootroot00000000000000[//]: # " Copyright (c) 2018, 2021 Oracle and/or its affiliates. All rights reserved. " [//]: # " " [//]: # " This program and the accompanying materials are made available under the " [//]: # " terms of the Eclipse Public License v. 2.0, which is available at " [//]: # " http://www.eclipse.org/legal/epl-2.0. " [//]: # " " [//]: # " This Source Code may also be made available under the following Secondary " [//]: # " Licenses when the conditions for such availability set forth in the " [//]: # " Eclipse Public License v. 2.0 are satisfied: GNU General Public License, " [//]: # " version 2 with the GNU Classpath Exception, which is available at " [//]: # " https://www.gnu.org/software/classpath/license.html. " [//]: # " " [//]: # " SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 " # Jakarta JSON Processing [![Build Status](https://github.com/eclipse-ee4j/jsonp/actions/workflows/maven.yml/badge.svg?branch=master)](https://github.com/eclipse-ee4j/jsonp/actions/workflows/maven.yml?branch=master) [![Jakarta Staging (Snapshots)](https://img.shields.io/nexus/s/https/jakarta.oss.sonatype.org/jakarta.json/jakarta.json-api.svg)](https://jakarta.oss.sonatype.org/content/repositories/staging/jakarta/json/jakarta.json-api/) Jakarta JSON Processing provides portable APIs to parse, generate, transform, and query JSON documents. This project contains Jakarta JSON Processing specification, API and TCK. ## Build Use the following command: ```bash mvn -U -C clean install ``` ## License * Most of the Jakarta JSON Processing project source code is licensed under the [Eclipse Public License (EPL) v2.0](https://projects.eclipse.org/license/epl-2.0) and [GNU General Public License (GPL) v2 with Classpath Exception](https://www.gnu.org/software/classpath/license.html); see the license information at the top of each source file. * The binary jar files published to the Maven repository are licensed under the same licenses as the corresponding source code; see the file `META-INF/LICENSE.txt` in each jar file. You’ll find the text of the licenses in the workspace in various `LICENSE.txt` or `LICENSE.md` files. Don’t let the presence of these license files in the workspace confuse you into thinking that they apply to all files in the workspace. You should always read the license file included with every download, and read the license text included in every source file. ## Links - [Jakarta JSON Processing @ Eclipse](https://projects.eclipse.org/projects/ee4j.jsonp) ## Contributing We use [contribution policy](CONTRIBUTING.md), which means we can only accept contributions under the terms of [Eclipse Contributor Agreement](http://www.eclipse.org/legal/ECA.php). jsonp-api-2.1.3-RELEASE/api/000077500000000000000000000000001451447132700152545ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/pom.xml000066400000000000000000000443371451447132700166040ustar00rootroot00000000000000 4.0.0 org.eclipse.ee4j project 1.0.8 jakarta.json jakarta.json-api 2.1.3 Jakarta JSON Processing API Jakarta JSON Processing defines a Java(R) based framework for parsing, generating, transforming, and querying JSON documents. https://github.com/eclipse-ee4j/jsonp scm:git:git://github.com/eclipse-ee4j/jsonp.git scm:git:git@github.com:eclipse-ee4j/jsonp.git https://github.com/eclipse-ee4j/jsonp HEAD Eclipse Public License 2.0 https://projects.eclipse.org/license/epl-2.0 repo GNU General Public License, version 2 with the GNU Classpath Exception https://projects.eclipse.org/license/secondary-gpl-2.0-cp repo m0mus Dmitry Kornilov Oracle project lead lukasj Lukas Jungmann Oracle dev lead ${project.basedir}/../etc/copyright-exclude ${project.basedir}/../etc/copyright.txt true true false ${project.basedir}/../etc/spotbugs-exclude.xml false Low 4.7.3.5 false jakarta.json 2.1 ${project.basedir}/.. Eclipse Foundation org.codehaus.mojo buildnumber-maven-plugin 3.2.0 org.codehaus.mojo build-helper-maven-plugin 3.4.0 org.glassfish.copyright glassfish-copyright-maven-plugin 2.4 org.apache.maven.plugins maven-compiler-plugin 3.11.0 org.glassfish.build spec-version-maven-plugin 2.1 org.apache.felix maven-bundle-plugin 5.1.9 <_noextraheaders>true org.apache.maven.plugins maven-jar-plugin 3.3.0 org.apache.maven.plugins maven-source-plugin 3.3.0 org.apache.maven.plugins maven-javadoc-plugin 3.5.0 org.apache.maven.plugins maven-enforcer-plugin 3.4.0 com.github.spotbugs spotbugs-maven-plugin ${spotbugs.version} ${spotbugs.skip} ${spotbugs.threshold} org.apache.maven.plugins maven-enforcer-plugin enforce-maven enforce [11,) [3.6.0,) org.glassfish.copyright glassfish-copyright-maven-plugin ${copyright.exclude} ${copyright.scmonly} ${copyright.update} ${copyright.ignoreyear} false verify check org.codehaus.mojo buildnumber-maven-plugin validate validate create true 7 false org.codehaus.mojo build-helper-maven-plugin add-legal-resource generate-resources add-resource ${legal.doc.source} NOTICE.md LICENSE.md META-INF currentyear-property timestamp-property validate current.year en,US yyyy org.apache.maven.plugins maven-compiler-plugin 9 false -Xlint:all -Xdoclint:all true base-compile compile 8 module-info.java org.glassfish.build spec-version-maven-plugin ${non.final} api ${spec.version} ${project.version} ${extension.name} set-spec-properties org.apache.felix maven-bundle-plugin ${spec.bundle.version} ${spec.bundle.symbolic-name} ${spec.extension.name} ${spec.implementation.version} ${spec.specification.version} Jakarta JSON Processing API ${spec.version} ${vendor.name} ${buildNumber} * !org.glassfish.hk2.osgiresourcelocator, !org.eclipse.parsson, * =1.0.0)(!(version>=2.0.0)))";resolution:=optional, osgi.serviceloader; filter:="(osgi.serviceloader=jakarta.json.spi.JsonProvider)"; osgi.serviceloader="jakarta.json.spi.JsonProvider"; cardinality:=multiple;resolution:=optional ]]> bundle-manifest process-classes manifest org.apache.maven.plugins maven-jar-plugin ${project.build.outputDirectory}/META-INF/MANIFEST.MF org.apache.maven.plugins maven-source-plugin false true ${buildNumber} org.apache.maven.plugins maven-javadoc-plugin false 11 true true JSON Processing API documentation JSON Processing API documentation JSON Processing API documentation
JSON Processing API v${project.version}]]>
jsonp-dev@eclipse.org.
Copyright © 2019, ${current.year} Eclipse Foundation. All rights reserved.
Use is subject to license terms.]]>
true true
com.github.spotbugs spotbugs-maven-plugin true ${spotbugs.exclude} High
jsonp-api-2.1.3-RELEASE/api/src/000077500000000000000000000000001451447132700160435ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/000077500000000000000000000000001451447132700167675ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/java/000077500000000000000000000000001451447132700177105ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/000077500000000000000000000000001451447132700213255ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/000077500000000000000000000000001451447132700222765ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/EmptyArray.java000066400000000000000000000057201451447132700252420ustar00rootroot00000000000000/* * Copyright (c) 2017, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.Serializable; import java.util.AbstractList; import java.util.Collections; import java.util.List; import java.util.RandomAccess; /** * Private implementation of immutable {@link JsonArray}. * * @author Lukas Jungmann */ final class EmptyArray extends AbstractList implements JsonArray, Serializable, RandomAccess { /** for serialization */ private static final long serialVersionUID = 7295439472061642859L; /** Default constructor. */ EmptyArray() {} @Override public JsonValue get(int index) { throw new IndexOutOfBoundsException("Index: " + index); } @Override public int size() { return 0; } @Override public JsonObject getJsonObject(int index) { return (JsonObject) get(index); } @Override public JsonArray getJsonArray(int index) { return (JsonArray) get(index); } @Override public JsonNumber getJsonNumber(int index) { return (JsonNumber) get(index); } @Override public JsonString getJsonString(int index) { return (JsonString) get(index); } @Override public List getValuesAs(Class clazz) { return Collections.emptyList(); } @Override public String getString(int index) { return getJsonString(index).getString(); } @Override public String getString(int index, String defaultValue) { return defaultValue; } @Override public int getInt(int index) { return getJsonNumber(index).intValue(); } @Override public int getInt(int index, int defaultValue) { return defaultValue; } @Override public boolean getBoolean(int index) { return get(index) == JsonValue.TRUE; } @Override public boolean getBoolean(int index, boolean defaultValue) { return defaultValue; } @Override public boolean isNull(int index) { return get(index) == JsonValue.NULL; } @Override public ValueType getValueType() { return ValueType.ARRAY; } /** * Preserves singleton property * @return {@link JsonValue#EMPTY_JSON_ARRAY} */ private Object readResolve() { return JsonValue.EMPTY_JSON_ARRAY; } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/EmptyObject.java000066400000000000000000000054101451447132700253660ustar00rootroot00000000000000/* * Copyright (c) 2017, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.Serializable; import java.util.AbstractMap; import java.util.Collections; import java.util.Set; /** * Private implementation of immutable {@link JsonObject}. * * @author Lukas Jungmann */ final class EmptyObject extends AbstractMap implements JsonObject, Serializable { /** for serialization */ private static final long serialVersionUID = -1461653546889072583L; /** Default constructor. */ EmptyObject() {} @Override public Set> entrySet() { return Collections.>emptySet(); } @Override public JsonArray getJsonArray(String name) { return (JsonArray) get(name); } @Override public JsonObject getJsonObject(String name) { return (JsonObject) get(name); } @Override public JsonNumber getJsonNumber(String name) { return (JsonNumber) get(name); } @Override public JsonString getJsonString(String name) { return (JsonString) get(name); } @Override public String getString(String name) { return getJsonString(name).getString(); } @Override public String getString(String name, String defaultValue) { return defaultValue; } @Override public int getInt(String name) { return getJsonNumber(name).intValue(); } @Override public int getInt(String name, int defaultValue) { return defaultValue; } @Override public boolean getBoolean(String name) { throw new NullPointerException(); } @Override public boolean getBoolean(String name, boolean defaultValue) { return defaultValue; } @Override public boolean isNull(String name) { throw new NullPointerException(); } @Override public ValueType getValueType() { return ValueType.OBJECT; } /** * Preserves singleton property * @return {@link JsonValue#EMPTY_JSON_OBJECT} */ private Object readResolve() { return JsonValue.EMPTY_JSON_OBJECT; } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/Json.java000066400000000000000000000430671451447132700240640ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Map; import java.util.Optional; import jakarta.json.spi.JsonProvider; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonGeneratorFactory; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParserFactory; /** * Factory class for creating JSON processing objects. * This class provides the most commonly used methods for creating these * objects and their corresponding factories. The factory classes provide * all the various ways to create these objects. * *

* The methods in this class locate a provider instance using the method * {@link JsonProvider#provider()}. This class uses the provider instance * to create JSON processing objects. * *

* The following example shows how to create a JSON parser to parse * an empty array: *

 * 
 * StringReader reader = new StringReader("[]");
 * JsonParser parser = Json.createParser(reader);
 * 
 * 
* *

* All the methods in this class are safe for use by multiple concurrent * threads. */ public final class Json { /** * No instantiation. */ private Json() { } /** * Creates a JSON parser from a character stream. * * @param reader i/o reader from which JSON is to be read * @return a JSON parser */ public static JsonParser createParser(Reader reader) { return JsonProvider.provider().createParser(reader); } /** * Creates a JSON parser from a byte stream. * The character encoding of the stream is determined as specified in * RFC 7159. * * @param in i/o stream from which JSON is to be read * @throws JsonException if encoding cannot be determined * or i/o error (IOException would be cause of JsonException) * @return a JSON parser */ public static JsonParser createParser(InputStream in) { return JsonProvider.provider().createParser(in); } /** * Creates a JSON generator for writing JSON to a character stream. * * @param writer a i/o writer to which JSON is written * @return a JSON generator */ public static JsonGenerator createGenerator(Writer writer) { return JsonProvider.provider().createGenerator(writer); } /** * Creates a JSON generator for writing JSON to a byte stream. * * @param out i/o stream to which JSON is written * @return a JSON generator */ public static JsonGenerator createGenerator(OutputStream out) { return JsonProvider.provider().createGenerator(out); } /** * Creates a parser factory for creating {@link JsonParser} objects. * * @return JSON parser factory. * public static JsonParserFactory createParserFactory() { return JsonProvider.provider().createParserFactory(); } */ /** * Creates a parser factory for creating {@link JsonParser} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON parsers. The map may be empty or null * @return JSON parser factory */ public static JsonParserFactory createParserFactory(Map config) { return JsonProvider.provider().createParserFactory(config); } /** * Creates a generator factory for creating {@link JsonGenerator} objects. * * @return JSON generator factory * public static JsonGeneratorFactory createGeneratorFactory() { return JsonProvider.provider().createGeneratorFactory(); } */ /** * Creates a generator factory for creating {@link JsonGenerator} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON generators. The map may be empty or null * @return JSON generator factory */ public static JsonGeneratorFactory createGeneratorFactory( Map config) { return JsonProvider.provider().createGeneratorFactory(config); } /** * Creates a JSON writer to write a * JSON {@link JsonObject object} or {@link JsonArray array} * structure to the specified character stream. * * @param writer to which JSON object or array is written * @return a JSON writer */ public static JsonWriter createWriter(Writer writer) { return JsonProvider.provider().createWriter(writer); } /** * Creates a JSON writer to write a * JSON {@link JsonObject object} or {@link JsonArray array} * structure to the specified byte stream. Characters written to * the stream are encoded into bytes using UTF-8 encoding. * * @param out to which JSON object or array is written * @return a JSON writer */ public static JsonWriter createWriter(OutputStream out) { return JsonProvider.provider().createWriter(out); } /** * Creates a JSON reader from a character stream. * * @param reader a reader from which JSON is to be read * @return a JSON reader */ public static JsonReader createReader(Reader reader) { return JsonProvider.provider().createReader(reader); } /** * Creates a JSON reader from a byte stream. The character encoding of * the stream is determined as described in * RFC 7159. * * @param in a byte stream from which JSON is to be read * @return a JSON reader */ public static JsonReader createReader(InputStream in) { return JsonProvider.provider().createReader(in); } /** * Creates a reader factory for creating {@link JsonReader} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON readers. The map may be empty or null * @return a JSON reader factory */ public static JsonReaderFactory createReaderFactory(Map config) { return JsonProvider.provider().createReaderFactory(config); } /** * Creates a writer factory for creating {@link JsonWriter} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON writers. The map may be empty or null * @return a JSON writer factory */ public static JsonWriterFactory createWriterFactory(Map config) { return JsonProvider.provider().createWriterFactory(config); } /** * Creates a JSON array builder * * @return a JSON array builder */ public static JsonArrayBuilder createArrayBuilder() { return JsonProvider.provider().createArrayBuilder(); } /** * Creates a JSON array builder, initialized with the specified array * * @param array the initial array in the builder * @return a JSON array builder * * @since 1.1 */ public static JsonArrayBuilder createArrayBuilder(JsonArray array) { return JsonProvider.provider().createArrayBuilder(array); } /** * Creates a JSON array builder, initialized with the content of specified {@code collection}. * If the @{code collection} contains {@link Optional}s then resulting JSON array builder * contains the value from the {@code collection} only if the {@link Optional} is not empty. * * @param collection the initial data for the builder * @return a JSON array builder * @exception IllegalArgumentException if the value from the {@code collection} cannot be converted * to the corresponding {@link JsonValue} * * @since 1.1 */ public static JsonArrayBuilder createArrayBuilder(Collection collection) { return JsonProvider.provider().createArrayBuilder(collection); } /** * Creates a JSON object builder * * @return a JSON object builder */ public static JsonObjectBuilder createObjectBuilder() { return JsonProvider.provider().createObjectBuilder(); } /** * Creates a JSON object builder, initialized with the specified object. * * @param object the initial object in the builder * @return a JSON object builder * * @since 1.1 */ public static JsonObjectBuilder createObjectBuilder(JsonObject object) { return JsonProvider.provider().createObjectBuilder(object); } /** * Creates a JSON object builder, initialized with the data from specified {@code map}. * If the @{code map} contains {@link Optional}s then resulting JSON object builder * contains the key from the {@code map} only if the {@link Optional} is not empty. * * @param map the initial object in the builder * @return a JSON object builder * @exception IllegalArgumentException if the value from the {@code map} cannot be converted * to the corresponding {@link JsonValue} * * @since 1.1 */ public static JsonObjectBuilder createObjectBuilder(Map map) { return JsonProvider.provider().createObjectBuilder(map); } /** * Creates JSON Pointer (RFC 6901) * from given {@code jsonPointer} string. *

    *
  • An empty {@code jsonPointer} string defines a reference to the target itself.
  • *
  • If the {@code jsonPointer} string is non-empty, it must be a sequence of '{@code /}' prefixed tokens.
  • *
* * @param jsonPointer the valid escaped JSON Pointer string * @throws NullPointerException if {@code jsonPointer} is {@code null} * @throws JsonException if {@code jsonPointer} is not a valid JSON Pointer * @return a JSON Pointer * * @since 1.1 */ public static JsonPointer createPointer(String jsonPointer) { return JsonProvider.provider().createPointer(jsonPointer); } /** * Creates a JSON Patch builder (RFC 6902). * * @return a JSON Patch builder * * @since 1.1 */ public static JsonPatchBuilder createPatchBuilder() { return JsonProvider.provider().createPatchBuilder(); } /** * Creates a JSON Patch builder * (RFC 6902), * initialized with the specified operations. * * @param array the initial patch operations * @return a JSON Patch builder * * @since 1.1 */ public static JsonPatchBuilder createPatchBuilder(JsonArray array) { return JsonProvider.provider().createPatchBuilder(array); } /** * Creates a JSON Patch (RFC 6902) * from the specified operations. * * @param array patch operations * @return a JSON Patch * * @since 1.1 */ public static JsonPatch createPatch(JsonArray array) { return JsonProvider.provider().createPatch(array); } /** * Generates a JSON Patch (RFC 6902) * from the source and target {@code JsonStructure}. * The generated JSON Patch need not be unique. * * @param source the source * @param target the target, must be the same type as the source * @return a JSON Patch which when applied to the source, yields the target * * @since 1.1 */ public static JsonPatch createDiff(JsonStructure source, JsonStructure target) { return JsonProvider.provider().createDiff(source, target); } /** * Creates JSON Merge Patch (RFC 7396) * from specified {@code JsonValue}. * * @param patch the patch * @return a JSON Merge Patch * * @since 1.1 */ public static JsonMergePatch createMergePatch(JsonValue patch) { return JsonProvider.provider().createMergePatch(patch); } /** * Generates a JSON Merge Patch (RFC 7396) * from the source and target {@code JsonValue}s * which when applied to the {@code source}, yields the {@code target}. * * @param source the source * @param target the target * @return a JSON Merge Patch * * @since 1.1 */ public static JsonMergePatch createMergeDiff(JsonValue source, JsonValue target) { return JsonProvider.provider().createMergeDiff(source, target); } /** * Creates a builder factory for creating {@link JsonArrayBuilder} * and {@link JsonObjectBuilder} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON builders. The map may be empty or null * @return a JSON builder factory */ public static JsonBuilderFactory createBuilderFactory( Map config) { return JsonProvider.provider().createBuilderFactory(config); } /** * Creates a JsonString. * * @param value a JSON string * @return the JsonString for the string * * @since 1.1 */ public static JsonString createValue(String value) { return JsonProvider.provider().createValue(value); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public static JsonNumber createValue(int value) { return JsonProvider.provider().createValue(value); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public static JsonNumber createValue(long value) { return JsonProvider.provider().createValue(value); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public static JsonNumber createValue(double value) { return JsonProvider.provider().createValue(value); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public static JsonNumber createValue(BigDecimal value) { return JsonProvider.provider().createValue(value); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public static JsonNumber createValue(BigInteger value) { return JsonProvider.provider().createValue(value); } /** * Encodes (escapes) a passed string as defined by RFC 6901. * This method doesn't validate the passed JSON-pointer string. * * @param pointer the JSON-pointer string to encode * @return encoded JSON-pointer string * * @since 1.1 */ public static String encodePointer(String pointer) { return pointer.replace("~", "~0").replace("/", "~1"); } /** * Decodes a passed JSON-pointer string as defined by RFC 6901. * This method doesn't validate the passed JSON-pointer string. * * @param escaped the JSON-pointer string to decode * @return decoded JSON-pointer string * * @since 1.1 */ public static String decodePointer(String escaped) { return escaped.replace("~1", "/").replace("~0", "~"); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 2.1 */ public static JsonNumber createValue(Number value) { return JsonProvider.provider().createValue(value); } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonArray.java000066400000000000000000000262051451447132700250560ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * {@code JsonArray} represents an immutable JSON array * (an ordered sequence of zero or more values). * It also provides an unmodifiable list view of the values in the array. * *

A {@code JsonArray} object can be created by reading JSON data from * an input source or it can be built from scratch using an array builder * object. * *

The following example demonstrates how to create a {@code JsonArray} * object from an input source using the method {@link JsonReader#readArray()}: *


 * JsonReader jsonReader = Json.createReader(...);
 * JsonArray array = jsonReader.readArray();
 * jsonReader.close();
 * 
* *

The following example demonstrates how to build an empty JSON array * using the class {@link JsonArrayBuilder}: *


 * JsonArray array = Json.createArrayBuilder().build();
 * 
* *

The example code below demonstrates how to create the following JSON array: *


 * [
 *     { "type": "home", "number": "212 555-1234" },
 *     { "type": "fax", "number": "646 555-4567" }
 * ]
 * 
*

 * JsonArray value = Json.createArrayBuilder()
 *     .add(Json.createObjectBuilder()
 *         .add("type", "home")
 *         .add("number", "212 555-1234"))
 *     .add(Json.createObjectBuilder()
 *         .add("type", "fax")
 *         .add("number", "646 555-4567"))
 *     .build();
 * 
* *

The following example demonstrates how to write a {@code JsonArray} object * as JSON data: *


 * JsonArray arr = ...;
 * JsonWriter writer = Json.createWriter(...)
 * writer.writeArray(arr);
 * writer.close();
 * 
* *

The values in a {@code JsonArray} can be of the following types: * {@link JsonObject}, {@link JsonArray}, * {@link JsonString}, {@link JsonNumber}, {@link JsonValue#TRUE}, * {@link JsonValue#FALSE}, and {@link JsonValue#NULL}. * {@code JsonArray} provides various accessor methods to access the values * in an array. * *

The following example shows how to obtain the home phone number * "212 555-1234" from the array built in the previous example: *


 * JsonObject home = array.getJsonObject(0);
 * String number = home.getString("number");
 * 
* *

{@code JsonArray} instances are list objects that provide read-only * access to the values in the JSON array. Any attempt to modify the list, * whether directly or using its collection views, results in an * {@code UnsupportedOperationException}. */ public interface JsonArray extends JsonStructure, List { /** * Returns the object value at the specified position in this array. * This is a convenience method for {@code (JsonObject)get(index)}. * * @param index index of the value to be returned * @return the value at the specified position in this array * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * assignable to the JsonObject type */ JsonObject getJsonObject(int index); /** * Returns the array value at the specified position in this array. * This is a convenience method for {@code (JsonArray)get(index)}. * * @param index index of the value to be returned * @return the value at the specified position in this array * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * assignable to the JsonArray type */ JsonArray getJsonArray(int index); /** * Returns the number value at the specified position in this array. * This is a convenience method for {@code (JsonNumber)get(index)}. * * @param index index of the value to be returned * @return the value at the specified position in this array * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * assignable to the JsonNumber type */ JsonNumber getJsonNumber(int index); /** * Returns the string value at ths specified position in this array. * This is a convenience method for {@code (JsonString)get(index)}. * * @param index index of the value to be returned * @return the value at the specified position in this array * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * assignable to the JsonString type */ JsonString getJsonString(int index); /** * Returns a list view of the specified type for the array. This method * does not verify if there is a value of wrong type in the array. Providing * this typesafe view dynamically may cause a program fail with a * {@code ClassCastException}, if there is a value of wrong type in this * array. Unfortunately, the exception can occur at any time after this * method returns. * * @param The type of the List for the array * @param clazz a JsonValue type * @return a list view of the specified type */ List getValuesAs(Class clazz); /** * Returns a list view for the array. The value and the type of the elements * in the list is specified by the {@code func} argument. *

This method can be used to obtain a list of the unwrapped types, such as *

{@code
     *     List strings = ary1.getValuesAs(JsonString::getString);
     *     List ints = ary2.getValuesAs(JsonNumber::intValue);
     * } 
* or a list of simple projections, such as *
 {@code
     *     List stringsizes = ary1.getValueAs((JsonString v)->v.getString().length();
     * } 
* @param The element type (must be a subtype of JsonValue) of this JsonArray. * @param The element type of the returned List * @param func The function that maps the elements of this JsonArray to the target elements. * @return A List of the specified values and type. * @throws ClassCastException if the {@code JsonArray} contains a value of wrong type * * @since 1.1 */ default List getValuesAs(Function func) { @SuppressWarnings("unchecked") Stream stream = (Stream) stream(); return stream.map(func).collect(Collectors.toList()); } /** * A convenience method for * {@code getJsonString(index).getString()}. * * @param index index of the {@code JsonString} value * @return the String value at the specified position * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * assignable to {@code JsonString} */ String getString(int index); /** * Returns the {@code String} value of {@code JsonString} at the specified * position in this JSON array values. If {@code JsonString} is found, * its {@link jakarta.json.JsonString#getString()} is returned. Otherwise, * the specified default value is returned. * * @param index index of the {@code JsonString} value * @param defaultValue the String to return if the {@code JsonValue} at the * specified position is not a {@code JsonString} * @return the String value at the specified position in this array, * or the specified default value */ String getString(int index, String defaultValue); /** * A convenience method for * {@code getJsonNumber(index).intValue()}. * * @param index index of the {@code JsonNumber} value * @return the int value at the specified position * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * assignable to {@code JsonNumber} */ int getInt(int index); /** * Returns the int value of the {@code JsonNumber} at the specified position. * If the value at that position is a {@code JsonNumber}, * this method returns {@link jakarta.json.JsonNumber#intValue()}. Otherwise * this method returns the specified default value. * * @param index index of the {@code JsonNumber} value * @param defaultValue the int value to return if the {@code JsonValue} at * the specified position is not a {@code JsonNumber} * @return the int value at the specified position in this array, * or the specified default value */ int getInt(int index, int defaultValue); /** * Returns the boolean value at the specified position. * If the value at the specified position is {@code JsonValue.TRUE} * this method returns {@code true}. If the value at the specified position * is {@code JsonValue.FALSE} this method returns {@code false}. * * @param index index of the JSON boolean value * @return the boolean value at the specified position * @throws IndexOutOfBoundsException if the index is out of range * @throws ClassCastException if the value at the specified position is not * {@code JsonValue.TRUE} or {@code JsonValue.FALSE} */ boolean getBoolean(int index); /** * Returns the boolean value at the specified position. * If the value at the specified position is {@code JsonValue.TRUE} * this method returns {@code true}. If the value at the specified position * is {@code JsonValue.FALSE} this method returns {@code false}. * Otherwise this method returns the specified default value. * * @param index index of the JSON boolean value * @param defaultValue the boolean value to return if the {@code JsonValue} * at the specified position is neither TRUE nor FALSE * @return the boolean value at the specified position, * or the specified default value */ boolean getBoolean(int index, boolean defaultValue); /** * Returns {@code true} if the value at the specified location in this * array is {@code JsonValue.NULL}. * * @param index index of the JSON null value * @return return true if the value at the specified location is * {@code JsonValue.NULL}, otherwise false * @throws IndexOutOfBoundsException if the index is out of range */ boolean isNull(int index); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonArrayBuilder.java000066400000000000000000000503411451447132700263630ustar00rootroot00000000000000/* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.math.BigDecimal; import java.math.BigInteger; /** * A builder for creating {@link JsonArray} models from scratch, and for * modifying a existing {@code JsonArray}. *

A {@code JsonArrayBuilder} can start with an empty or a non-empty * JSON array model. This interface provides methods to add, insert, remove * and replace values in the JSON array model.

*

Methods in this class can be chained to perform multiple values to * the array.

* *

The class {@link jakarta.json.Json} contains methods to create the builder * object. The example code below shows how to build an empty {@code JsonArray} * instance. *

 * 
 * JsonArray array = Json.createArrayBuilder().build();
 * 
 * 
* *

The class {@link JsonBuilderFactory} also contains methods to create * {@code JsonArrayBuilder} instances. A factory instance can be used to create * multiple builder instances with the same configuration. This the preferred * way to create multiple instances. * * The example code below shows how to build a {@code JsonArray} object * that represents the following JSON array: * *

 * 
 * [
 *     { "type": "home", "number": "212 555-1234" },
 *     { "type": "fax", "number": "646 555-4567" }
 * ]
 * 
 * 
* *

The following code creates the JSON array above: * *

 * 
 * JsonBuilderFactory factory = Json.createBuilderFactory(config);
 * JsonArray value = factory.createArrayBuilder()
 *     .add(factory.createObjectBuilder()
 *         .add("type", "home")
 *         .add("number", "212 555-1234"))
 *     .add(factory.createObjectBuilder()
 *         .add("type", "fax")
 *         .add("number", "646 555-4567"))
 *     .build();
 * 
 * 
* *

This class does not allow null to be used as a * value while building the JSON array * * @see JsonObjectBuilder */ public interface JsonArrayBuilder { /** * Adds a value to the array. * * @param value the JSON value * @return this array builder * @throws NullPointerException if the specified value is null */ JsonArrayBuilder add(JsonValue value); /** * Adds a value to the array as a {@link JsonString}. * * @param value the string value * @return this array builder * @throws NullPointerException if the specified value is null */ JsonArrayBuilder add(String value); /** * Adds a value to the array as a {@link JsonNumber}. * * @param value the number value * @return this array builder * @throws NullPointerException if the specified value is null * * @see JsonNumber */ JsonArrayBuilder add(BigDecimal value); /** * Adds a value to the array as a {@link JsonNumber}. * * @param value the number value * @return this array builder * @throws NullPointerException if the specified value is null * * @see JsonNumber */ JsonArrayBuilder add(BigInteger value); /** * Adds a value to the array as a {@link JsonNumber}. * * @param value the number value * @return this array builder * * @see JsonNumber */ JsonArrayBuilder add(int value); /** * Adds a value to the array as a {@link JsonNumber}. * * @param value the number value * @return this array builder * * @see JsonNumber */ JsonArrayBuilder add(long value); /** * Adds a value to the array as a {@link JsonNumber}. * * @param value the number value * @return this array builder * @throws NumberFormatException if the value is Not-a-Number (NaN) or * infinity * * @see JsonNumber */ JsonArrayBuilder add(double value); /** * Adds a {@link JsonValue#TRUE} or {@link JsonValue#FALSE} value to the * array. * * @param value the boolean value * @return this array builder */ JsonArrayBuilder add(boolean value); /** * Adds a {@link JsonValue#NULL} value to the array. * * @return this array builder */ JsonArrayBuilder addNull(); /** * Adds a {@link JsonObject} from an object builder to the array. * * @param builder the object builder * @return this array builder * @throws NullPointerException if the specified builder is null */ JsonArrayBuilder add(JsonObjectBuilder builder); /** * Adds a {@link JsonArray} from an array builder to the array. * * @param builder the array builder * @return this array builder * @throws NullPointerException if the specified builder is null */ JsonArrayBuilder add(JsonArrayBuilder builder); /** * Adds all elements of the array in the specified array builder to the array. * * @param builder the array builder * @return this array builder * @throws NullPointerException if the specified builder is null * @since 1.1 */ default JsonArrayBuilder addAll(JsonArrayBuilder builder) { throw new UnsupportedOperationException(); } /** * Inserts a value to the array at the specified position. Shifts the value * currently at that position (if any) and any subsequent values to the right * (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the JSON value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @since 1.1 */ default JsonArrayBuilder add(int index, JsonValue value) { throw new UnsupportedOperationException(); } /** * Adds a value to the array as a {@link JsonString} at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the string value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @since 1.1 */ default JsonArrayBuilder add(int index, String value) { throw new UnsupportedOperationException(); } /** * Adds a value to the array as a {@link JsonNumber} at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the number value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder add(int index, BigDecimal value) { throw new UnsupportedOperationException(); } /** * Adds a value to the array as a {@link JsonNumber} at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the number value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder add(int index, BigInteger value) { throw new UnsupportedOperationException(); } /** * Adds a value to the array as a {@link JsonNumber} at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the number value * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder add(int index, int value) { throw new UnsupportedOperationException(); } /** * Adds a value to the array as a {@link JsonNumber} at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the number value * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder add(int index, long value) { throw new UnsupportedOperationException(); } /** * Adds a value to the array as a {@link JsonNumber} at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the number value * @return this array builder * @throws NumberFormatException if the value is Not-a-Number (NaN) or * infinity * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder add(int index, double value) { throw new UnsupportedOperationException(); } /** * Adds a {@link JsonValue#TRUE} or {@link JsonValue#FALSE} value to the * array at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param value the boolean value * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @since 1.1 */ default JsonArrayBuilder add(int index, boolean value) { throw new UnsupportedOperationException(); } /** * Adds a {@link JsonValue#NULL} value to the array at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @since 1.1 */ default JsonArrayBuilder addNull(int index) { return add(index, JsonValue.NULL); } /** * Adds a {@link JsonObject} from an object builder to the array at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param builder the object builder * @return this array builder * @throws NullPointerException if the specified builder is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @since 1.1 */ default JsonArrayBuilder add(int index, JsonObjectBuilder builder) { throw new UnsupportedOperationException(); } /** * Adds a {@link JsonArray} from an array builder to the array at the specified position. * Shifts the value currently at that position (if any) and any subsequent values * to the right (adds one to their indices). Index starts with 0. * * @param index the position in the array * @param builder the array builder * @return this array builder * @throws NullPointerException if the specified builder is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index > array size)} * * @since 1.1 */ default JsonArrayBuilder add(int index, JsonArrayBuilder builder) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value at the * specified position. * * @param index the position in the array * @param value the JSON value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder set(int index, JsonValue value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonString} at the specified position. * * @param index the position in the array * @param value the string value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder set(int index, String value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonNumber} at the specified position. * * @param index the position in the array * @param value the number value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder set(int index, BigDecimal value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonNumber} at the specified position. * * @param index the position in the array * @param value the number value * @return this array builder * @throws NullPointerException if the specified value is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder set(int index, BigInteger value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonNumber} at the specified position. * * @param index the position in the array * @param value the number value * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder set(int index, int value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonNumber} at the specified position. * * @param index the position in the array * @param value the number value * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder set(int index, long value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonNumber} at the specified position. * * @param index the position in the array * @param value the number value * @return this array builder * @throws NumberFormatException if the value is Not-a-Number (NaN) or * infinity * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @see JsonNumber * * @since 1.1 */ default JsonArrayBuilder set(int index, double value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with * a {@link JsonValue#TRUE} or {@link JsonValue#FALSE} value * at the specified position. * * @param index the position in the array * @param value the boolean value * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder set(int index, boolean value) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with * a {@link JsonValue#NULL} value at the specified position. * * @param index the position in the array * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder setNull(int index) { return set(index, JsonValue.NULL); } /** * Replaces a value in the array with the specified value as a * {@link JsonObject} from an object builder at the specified position. * * @param index the position in the array * @param builder the object builder * @return this array builder * @throws NullPointerException if the specified builder is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder set(int index, JsonObjectBuilder builder) { throw new UnsupportedOperationException(); } /** * Replaces a value in the array with the specified value as a * {@link JsonArray} from an array builder at the specified position. * * @param index the position in the array * @param builder the array builder * @return this array builder * @throws NullPointerException if the specified builder is null * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder set(int index, JsonArrayBuilder builder) { throw new UnsupportedOperationException(); } /** * Remove the value in the array at the specified position. * Shift any subsequent values to the left (subtracts one from their * indices. * * @param index the position in the array * @return this array builder * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= array size)} * * @since 1.1 */ default JsonArrayBuilder remove(int index) { throw new UnsupportedOperationException(); } /** * Returns the current array. * * @return the current JSON array */ JsonArray build(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonBuilderFactory.java000066400000000000000000000105351451447132700267150ustar00rootroot00000000000000/* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.util.Collection; import java.util.Map; /** * Factory to create {@link JsonObjectBuilder} and {@link JsonArrayBuilder} * instances. If a factory instance is configured with some configuration, * that would be used to configure the created builder instances. * *

* {@code JsonObjectBuilder} and {@code JsonArrayBuilder} can also be created * using {@link Json}'s methods. If multiple builder instances are created, * then creating them using a builder factory is preferred. * *

* For example: *

 * 
 * JsonBuilderFactory factory = Json.createBuilderFactory(...);
 * JsonArray value = factory.createArrayBuilder()
 *     .add(factory.createObjectBuilder()
 *         .add("type", "home")
 *         .add("number", "212 555-1234"))
 *     .add(factory.createObjectBuilder()
 *         .add("type", "fax")
 *         .add("number", "646 555-4567"))
 *     .build();
 * 
 * 
* *

All the methods in this class are safe for use by multiple concurrent * threads. */ public interface JsonBuilderFactory { /** * Creates a {@code JsonObjectBuilder} instance that is used to build * {@link JsonObject}. * * @return a JSON object builder */ JsonObjectBuilder createObjectBuilder(); /** * Creates a {@code JsonObjectBuilder} instance, initialized with an object. * * @param object the initial object in the builder * @return a JSON object builder * @throws NullPointerException if specified object is {@code null} * * @since 1.1 */ default JsonObjectBuilder createObjectBuilder(JsonObject object) { throw new UnsupportedOperationException(); } /** * Creates a {@code JsonObjectBuilder} instance, initialized with the specified object. * * @param object the initial object in the builder * @return a JSON object builder * @throws NullPointerException if specified object is {@code null} * * @since 1.1 */ default JsonObjectBuilder createObjectBuilder(Map object) { throw new UnsupportedOperationException(); } /** * Creates a {@code JsonArrayBuilder} instance that is used to build * {@link JsonArray} * * @return a JSON array builder */ JsonArrayBuilder createArrayBuilder(); /** * Creates a {@code JsonArrayBuilder} instance, initialized with an array. * * @param array the initial array in the builder * @return a JSON array builder * @throws NullPointerException if specified array is {@code null} * * @since 1.1 */ default JsonArrayBuilder createArrayBuilder(JsonArray array) { throw new UnsupportedOperationException(); } /** * Creates a {@code JsonArrayBuilder} instance, * initialized with the content of specified collection. * * @param collection the initial data for the builder * @return a JSON array builder * @throws NullPointerException if specified collection is {@code null} * * @since 1.1 */ default JsonArrayBuilder createArrayBuilder(Collection collection) { throw new UnsupportedOperationException(); } /** * Returns read-only map of supported provider specific configuration * properties that are used to configure the created JSON builders. * If there are any specified configuration properties that are not * supported by the provider, they won't be part of the returned map. * * @return a map of supported provider specific properties that are used * to configure the builders. The map be empty but not null. */ Map getConfigInUse(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonConfig.java000066400000000000000000000032341451447132700252020ustar00rootroot00000000000000/* * Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** * This class contains the Json properties and values. * * @since 2.1 */ public final class JsonConfig { /** * Configuration property to define the strategy for handling duplicate keys. * * See {@link KeyStrategy} */ public static final String KEY_STRATEGY = "jakarta.json.JsonConfig.keyStrategy" ; /** * It avoids new instances of this class. */ private JsonConfig() {} /** * Contains the different values allowed for {@link #KEY_STRATEGY}. * * See {@link #KEY_STRATEGY} */ public static enum KeyStrategy { /** * Configuration value that will take the value of the first match. */ FIRST, /** * Configuration value that will take the value of the last match. */ LAST, /** * Configuration value that will throw {@link JsonException} when duplicate key is found. */ NONE; } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonException.java000066400000000000000000000041761451447132700257410ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** * JsonException indicates that some exception happened during * JSON processing. */ public class JsonException extends RuntimeException { /** for serialization */ private static final long serialVersionUID = 359810709545392112L; /** * Constructs a new runtime exception with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public JsonException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause.

Note that the detail message associated with * {@code cause} is not automatically incorporated in * this runtime exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public JsonException(String message, Throwable cause) { super(message, cause); } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonMergePatch.java000066400000000000000000000047321451447132700260200ustar00rootroot00000000000000/* * Copyright (c) 2015, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** *

This interface represents an implementation of a JSON Merge Patch * as defined by RFC 7396. *

*

A {@code JsonMergePatch} can be instantiated with {@link Json#createMergePatch(JsonValue)} * by specifying the patch operations in a JSON Merge Patch or using {@link Json#createMergeDiff(JsonValue, JsonValue)} * to create a JSON Merge Patch based on the difference between two {@code JsonValue}s. *

* The following illustrates both approaches. *

1. Construct a JsonMergePatch with an existing JSON Merge Patch. *

{@code
 *   JsonValue contacts = ... ; // The target to be patched
 *   JsonValue patch = ...  ; // JSON Merge Patch
 *   JsonMergePatch mergePatch = Json.createMergePatch(patch);
 *   JsonValue result = mergePatch.apply(contacts);
 * } 
* 2. Construct a JsonMergePatch from a difference between two {@code JsonValue}s. *
{@code
 *   JsonValue source = ... ; // The source object
 *   JsonValue target = ... ; // The modified object
 *   JsonMergePatch mergePatch = Json.createMergeDiff(source, target); // The diff between source and target in a Json Merge Patch format
 * } 
* * @see RFC 7396 * * @since 1.1 */ public interface JsonMergePatch { /** * Applies the JSON Merge Patch to the specified {@code target}. * The target is not modified by the patch. * * @param target the target to apply the merge patch * @return the transformed target after the patch */ JsonValue apply(JsonValue target); /** * Returns the {@code JsonMergePatch} as {@code JsonValue}. * * @return this {@code JsonMergePatch} as {@code JsonValue} */ JsonValue toJsonValue(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonNumber.java000066400000000000000000000150501451447132700252240ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.math.BigDecimal; import java.math.BigInteger; /** * An immutable JSON number value. * *

* Implementations may use a {@link BigDecimal} object to store the numeric * value internally. * The {@code BigDecimal} object can be constructed from the following types: * int {@link BigDecimal#BigDecimal(int)}, * long {@link BigDecimal#BigDecimal(long)}, * BigInteger {@link BigDecimal#BigDecimal(BigInteger)}, * double {@link BigDecimal#valueOf(double)}, and * String {@link BigDecimal#BigDecimal(String)}. * Some of the method semantics in this class are defined using the * {@code BigDecimal} semantics. */ public interface JsonNumber extends JsonValue { /** * Returns true if this JSON number is a integral number. This method * semantics are defined using {@code bigDecimalValue().scale()}. If the * scale is zero, then it is considered integral type. This integral type * information can be used to invoke an appropriate accessor method to * obtain a numeric value as in the following example: * *

     * 
     * JsonNumber num = ...
     * if (num.isIntegral()) {
     *     num.longValue();     // or other methods to get integral value
     * } else {
     *     num.doubleValue();   // or other methods to get decimal number value
     * }
     * 
     * 
* * @return true if this number is a integral number, otherwise false */ boolean isIntegral(); /** * Returns this JSON number as an {@code int}. Note that this conversion * can lose information about the overall magnitude and precision of the * number value as well as return a result with the opposite sign. * * @return an {@code int} representation of the JSON number * @see java.math.BigDecimal#intValue() */ int intValue(); /** * Returns this JSON number as an {@code int}. * * @return an {@code int} representation of the JSON number * @throws ArithmeticException if the number has a nonzero fractional * part or if it does not fit in an {@code int} * @see java.math.BigDecimal#intValueExact() */ int intValueExact(); /** * Returns this JSON number as a {@code long}. Note that this conversion * can lose information about the overall magnitude and precision of the * number value as well as return a result with the opposite sign. * * @return a {@code long} representation of the JSON number. * @see java.math.BigDecimal#longValue() */ long longValue(); /** * Returns this JSON number as a {@code long}. * * @return a {@code long} representation of the JSON number * @throws ArithmeticException if the number has a non-zero fractional * part or if it does not fit in a {@code long} * @see java.math.BigDecimal#longValueExact() */ long longValueExact(); /** * Returns this JSON number as a {@link BigInteger} object. This is a * a convenience method for {@code bigDecimalValue().toBigInteger()}. * Note that this conversion can lose information about the overall * magnitude and precision of the number value as well as return a result * with the opposite sign. * * @return a {@code BigInteger} representation of the JSON number. * @see java.math.BigDecimal#toBigInteger() */ BigInteger bigIntegerValue(); /** * Returns this JSON number as a {@link BigInteger} object. This is a * convenience method for {@code bigDecimalValue().toBigIntegerExact()}. * * @return a {@link BigInteger} representation of the JSON number * @throws ArithmeticException if the number has a nonzero fractional part * @see java.math.BigDecimal#toBigIntegerExact() */ BigInteger bigIntegerValueExact(); /** * Returns this JSON number as a {@code double}. This is a * a convenience method for {@code bigDecimalValue().doubleValue()}. * Note that this conversion can lose information about the overall * magnitude and precision of the number value as well as return a result * with the opposite sign. * * @return a {@code double} representation of the JSON number * @see java.math.BigDecimal#doubleValue() */ double doubleValue(); /** * Returns this JSON number as a {@link BigDecimal} object. * * @return a {@link BigDecimal} representation of the JSON number */ BigDecimal bigDecimalValue(); /** * Returns this JSON number as a {@link Number} object. * * @return a {@link Number} representation of the JSON number * * @since 1.1 */ default Number numberValue() { throw new UnsupportedOperationException(); } /** * Returns a JSON text representation of the JSON number. The * representation is equivalent to {@link BigDecimal#toString()}. * * @return JSON text representation of the number */ @Override String toString(); /** * Compares the specified object with this {@code JsonNumber} object for * equality. Returns {@code true} if and only if the type of the specified * object is also {@code JsonNumber} and their {@link #bigDecimalValue()} * objects are equal * * @param obj the object to be compared for equality with * this {@code JsonNumber} * @return {@code true} if the specified object is equal to this * {@code JsonNumber} */ @Override boolean equals(Object obj); /** * Returns the hash code value for this {@code JsonNumber} object. The * hash code of a {@code JsonNumber} object is defined as the hash code of * its {@link #bigDecimalValue()} object. * * @return the hash code value for this {@code JsonNumber} object */ @Override int hashCode(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonObject.java000066400000000000000000000231271451447132700252060ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.util.Map; /** * {@code JsonObject} class represents an immutable JSON object value * (an unordered collection of zero or more name/value pairs). * It also provides unmodifiable map view to the JSON object * name/value mappings. * *

A JsonObject instance can be created from an input source using * {@link JsonReader#readObject()}. For example: *


 * JsonReader jsonReader = Json.createReader(...);
 * JsonObject object = jsonReader.readObject();
 * jsonReader.close();
 * 
* * It can also be built from scratch using a {@link JsonObjectBuilder}. * *

For example 1: An empty JSON object can be built as follows: *


 * JsonObject object = Json.createObjectBuilder().build();
 * 
* * For example 2: The following JSON *

 * {
 *     "firstName": "John", "lastName": "Smith", "age": 25,
 *     "address" : {
 *         "streetAddress": "21 2nd Street",
 *         "city": "New York",
 *         "state": "NY",
 *         "postalCode": "10021"
 *     },
 *     "phoneNumber": [
 *         { "type": "home", "number": "212 555-1234" },
 *         { "type": "fax", "number": "646 555-4567" }
 *     ]
 * }
 * 
* can be built using : *

 * JsonObject value = Json.createObjectBuilder()
 *     .add("firstName", "John")
 *     .add("lastName", "Smith")
 *     .add("age", 25)
 *     .add("address", Json.createObjectBuilder()
 *         .add("streetAddress", "21 2nd Street")
 *         .add("city", "New York")
 *         .add("state", "NY")
 *         .add("postalCode", "10021"))
 *     .add("phoneNumber", Json.createArrayBuilder()
 *         .add(Json.createObjectBuilder()
 *             .add("type", "home")
 *             .add("number", "212 555-1234"))
 *         .add(Json.createObjectBuilder()
 *             .add("type", "fax")
 *             .add("number", "646 555-4567")))
 *     .build();
 * 
* * {@code JsonObject} can be written to JSON as follows: *

 * JsonWriter writer = ...
 * JsonObject obj = ...;
 * writer.writeObject(obj);
 * 
* * {@code JsonObject} values can be {@link JsonObject}, {@link JsonArray}, * {@link JsonString}, {@link JsonNumber}, {@link JsonValue#TRUE}, * {@link JsonValue#FALSE}, {@link JsonValue#NULL}. These values can be * accessed using various accessor methods. * *

In the above example 2, "John" can be got using *


 * String firstName = object.getString("firstName");
 * 
* * This map object provides read-only access to the JSON object data, * and attempts to modify the map, whether direct or via its collection * views, result in an {@code UnsupportedOperationException}. * *

The map object's iteration ordering is based on the order in which * name/value pairs are added to the corresponding builder or the order * in which name/value pairs appear in the corresponding stream. */ public interface JsonObject extends JsonStructure, Map { /** * Returns the array value to which the specified name is mapped. * This is a convenience method for {@code (JsonArray)get(name)} to * get the value. * * @param name the name whose associated value is to be returned * @return the array value to which the specified name is mapped, or * {@code null} if this object contains no mapping for the name * @throws ClassCastException if the value to which the specified name * is mapped is not assignable to JsonArray type */ JsonArray getJsonArray(String name); /** * Returns the object value to which the specified name is mapped. * This is a convenience method for {@code (JsonObject)get(name)} to * get the value. * * @param name the name whose associated value is to be returned * @return the object value to which the specified name is mapped, or * {@code null} if this object contains no mapping for the name * @throws ClassCastException if the value to which the specified name * is mapped is not assignable to JsonObject type */ JsonObject getJsonObject(String name); /** * Returns the number value to which the specified name is mapped. * This is a convenience method for {@code (JsonNumber)get(name)} to * get the value. * * @param name the name whose associated value is to be returned * @return the number value to which the specified name is mapped, or * {@code null} if this object contains no mapping for the name * @throws ClassCastException if the value to which the specified name * is mapped is not assignable to JsonNumber type */ JsonNumber getJsonNumber(String name); /** * Returns the string value to which the specified name is mapped. * This is a convenience method for {@code (JsonString)get(name)} to * get the value. * * @param name the name whose associated value is to be returned * @return the string value to which the specified name is mapped, or * {@code null} if this object contains no mapping for the name * @throws ClassCastException if the value to which the specified name * is mapped is not assignable to JsonString type */ JsonString getJsonString(String name); /** * A convenience method for * {@code getJsonString(name).getString()} * * @param name whose associated value is to be returned as String * @return the String value to which the specified name is mapped * @throws NullPointerException if the specified name doesn't have any * mapping * @throws ClassCastException if the value for specified name mapping * is not assignable to JsonString */ String getString(String name); /** * Returns the string value of the associated {@code JsonString} mapping * for the specified name. If {@code JsonString} is found, then its * {@link jakarta.json.JsonString#getString()} is returned. Otherwise, * the specified default value is returned. * * @param name whose associated value is to be returned as String * @param defaultValue a default value to be returned * @return the string value of the associated mapping for the name, * or the default value */ String getString(String name, String defaultValue); /** * A convenience method for * {@code getJsonNumber(name).intValue()} * * @param name whose associated value is to be returned as int * @return the int value to which the specified name is mapped * @throws NullPointerException if the specified name doesn't have any * mapping * @throws ClassCastException if the value for specified name mapping * is not assignable to JsonNumber */ int getInt(String name); /** * Returns the int value of the associated {@code JsonNumber} mapping * for the specified name. If {@code JsonNumber} is found, then its * {@link jakarta.json.JsonNumber#intValue()} is returned. Otherwise, * the specified default value is returned. * * @param name whose associated value is to be returned as int * @param defaultValue a default value to be returned * @return the int value of the associated mapping for the name, * or the default value */ int getInt(String name, int defaultValue); /** * Returns the boolean value of the associated mapping for the specified * name. If the associated mapping is JsonValue.TRUE, then returns true. * If the associated mapping is JsonValue.FALSE, then returns false. * * @param name whose associated value is to be returned as boolean * @return the boolean value to which the specified name is mapped * @throws NullPointerException if the specified name doesn't have any * mapping * @throws ClassCastException if the value for specified name mapping * is not assignable to JsonValue.TRUE or JsonValue.FALSE */ boolean getBoolean(String name); /** * Returns the boolean value of the associated mapping for the specified * name. If the associated mapping is JsonValue.TRUE, then returns true. * If the associated mapping is JsonValue.FALSE, then returns false. * Otherwise, the specified default value is returned. * * @param name whose associated value is to be returned as int * @param defaultValue a default value to be returned * @return the boolean value of the associated mapping for the name, * or the default value */ boolean getBoolean(String name, boolean defaultValue); /** * Returns {@code true} if the associated value for the specified name is * {@code JsonValue.NULL}. * * @param name name whose associated value is checked * @return return true if the associated value is {@code JsonValue.NULL}, * otherwise false * @throws NullPointerException if the specified name doesn't have any * mapping */ boolean isNull(String name); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonObjectBuilder.java000066400000000000000000000251701451447132700265150ustar00rootroot00000000000000/* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.math.BigDecimal; import java.math.BigInteger; /** * A builder for creating {@link JsonObject} models from scratch. This * interface initializes an empty JSON object model and provides methods to add * name/value pairs to the object model and to return the resulting object. * The methods in this class can be chained to add multiple name/value pairs * to the object. * *

The class {@link jakarta.json.Json} contains methods to create the builder * object. The example code below shows how to build an empty {@code JsonObject} * instance. *

 * 
 * JsonObject object = Json.createObjectBuilder().build();
 * 
 * 
* *

The class {@link JsonBuilderFactory} also contains methods to create * {@code JsonObjectBuilder} instances. A factory instance can be used to create * multiple builder instances with the same configuration. This the preferred * way to create multiple instances. * * The example code below shows how to build a {@code JsonObject} model that * represents the following JSON object: * *

 * 
 * {
 *     "firstName": "John", "lastName": "Smith", "age": 25,
 *     "address" : {
 *         "streetAddress": "21 2nd Street",
 *         "city": "New York",
 *         "state": "NY",
 *         "postalCode": "10021"
 *     },
 *     "phoneNumber": [
 *         { "type": "home", "number": "212 555-1234" },
 *         { "type": "fax", "number": "646 555-4567" }
 *     ]
 * }
 * 
 * 
* *

The code to create the object shown above is the following: * *

 * 
 * JsonBuilderFactory factory = Json.createBuilderFactory(config);
 * JsonObject value = factory.createObjectBuilder()
 *     .add("firstName", "John")
 *     .add("lastName", "Smith")
 *     .add("age", 25)
 *     .add("address", factory.createObjectBuilder()
 *         .add("streetAddress", "21 2nd Street")
 *         .add("city", "New York")
 *         .add("state", "NY")
 *         .add("postalCode", "10021"))
 *     .add("phoneNumber", factory.createArrayBuilder()
 *         .add(factory.createObjectBuilder()
 *             .add("type", "home")
 *             .add("number", "212 555-1234"))
 *         .add(factory.createObjectBuilder()
 *             .add("type", "fax")
 *             .add("number", "646 555-4567")))
 *     .build();
 * 
 * 
* *

This class does not allow null to be used as a name or * value while building the JSON object * * @see JsonArrayBuilder */ public interface JsonObjectBuilder { /** * Adds a name/{@code JsonValue} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name or value is null */ JsonObjectBuilder add(String name, JsonValue value); /** * Adds a name/{@code JsonString} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name or value is null */ JsonObjectBuilder add(String name, String value); /** * Adds a name/{@code JsonNumber} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name or value is null * * @see JsonNumber */ JsonObjectBuilder add(String name, BigInteger value); /** * Adds a name/{@code JsonNumber} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name or value is null * * @see JsonNumber */ JsonObjectBuilder add(String name, BigDecimal value); /** * Adds a name/{@code JsonNumber} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name is null * * @see JsonNumber */ JsonObjectBuilder add(String name, int value); /** * Adds a name/{@code JsonNumber} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name is null * * @see JsonNumber */ JsonObjectBuilder add(String name, long value); /** * Adds a name/{@code JsonNumber} pair to the JSON object associated with * this object builder. If the object contains a mapping for the specified * name, this method replaces the old value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NumberFormatException if the value is Not-a-Number (NaN) or * infinity * @throws NullPointerException if the specified name is null * * @see JsonNumber */ JsonObjectBuilder add(String name, double value); /** * Adds a name/{@code JsonValue#TRUE} or name/{@code JsonValue#FALSE} pair * to the JSON object associated with this object builder. If the object * contains a mapping for the specified name, this method replaces the old * value with the specified value. * * @param name name in the name/value pair * @param value value in the name/value pair * @return this object builder * @throws NullPointerException if the specified name is null */ JsonObjectBuilder add(String name, boolean value); /** * Adds a name/{@code JsonValue#NULL} pair to the JSON object associated * with this object builder where the value is {@code null}. * If the object contains a mapping for the specified name, this method * replaces the old value with {@code null}. * * @param name name in the name/value pair * @return this object builder * @throws NullPointerException if the specified name is null */ JsonObjectBuilder addNull(String name); /** * Adds a name/{@code JsonObject} pair to the JSON object associated * with this object builder. The value {@code JsonObject} is built from the * specified object builder. If the object contains a mapping for the * specified name, this method replaces the old value with the * {@code JsonObject} from the specified object builder. * * @param name name in the name/value pair * @param builder the value is the object associated with this builder * @return this object builder * @throws NullPointerException if the specified name or builder is null */ JsonObjectBuilder add(String name, JsonObjectBuilder builder); /** * Adds a name/{@code JsonArray} pair to the JSON object associated with * this object builder. The value {@code JsonArray} is built from the * specified array builder. If the object contains a mapping for the * specified name, this method replaces the old value with the * {@code JsonArray} from the specified array builder. * * @param name the name in the name/value pair * @param builder the value is the object array with this builder * @return this object builder * @throws NullPointerException if the specified name or builder is null */ JsonObjectBuilder add(String name, JsonArrayBuilder builder); /** * Adds all name/value pairs in the JSON object associated with the specified * object builder to the JSON object associated with this object builder. * The newly added name/value pair will replace any existing name/value pair with * the same name. * * @param builder the specified object builder * @return this object builder * @throws NullPointerException if the specified builder is null * @since 1.1 */ default JsonObjectBuilder addAll(JsonObjectBuilder builder) { throw new UnsupportedOperationException(); } /** * Remove the name/value pair from the JSON object associated with this * object builder if it is present. * * @param name the name in the name/value pair to be removed * @return this object builder * @throws NullPointerException if the specified name is null * @since 1.1 */ default JsonObjectBuilder remove(String name) { throw new UnsupportedOperationException(); } /** * Returns the JSON object associated with this object builder. * The iteration order for the {@code JsonObject} is based * on the order in which name/value pairs are added to the object using * this builder. * * This method clears the builder. * * @return JSON object that is being built */ JsonObject build(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonPatch.java000066400000000000000000000110531451447132700250320ustar00rootroot00000000000000/* * Copyright (c) 2015, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** *

This interface represents an immutable implementation of a JSON Patch * as defined by RFC 6902. *

*

A {@code JsonPatch} can be instantiated with {@link Json#createPatch(JsonArray)} * by specifying the patch operations in a JSON Patch. Alternately, it * can also be constructed with a {@link JsonPatchBuilder}. *

* The following illustrates both approaches. *

1. Construct a JsonPatch with a JSON Patch. *

{@code
 *   JsonArray contacts = ... // The target to be patched
 *   JsonArray patch = ...  ; // JSON Patch
 *   JsonPatch jsonpatch = Json.createPatch(patch);
 *   JsonArray result = jsonpatch.apply(contacts);
 * } 
* 2. Construct a JsonPatch with JsonPatchBuilder. *
{@code
 *   JsonPatchBuilder builder = Json.createPatchBuilder();
 *   JsonArray result = builder.add("/John/phones/office", "1234-567")
 *                             .remove("/Amy/age")
 *                             .build()
 *                             .apply(contacts);
 * } 
* * @see RFC 6902 * * @since 1.1 */ public interface JsonPatch { /** * This enum represents the list of valid JSON Patch operations * as defined by RFC 6902. * * @see RFC 6902 */ enum Operation { /** * "add" operation. */ ADD("add"), /** * "remove" operation. */ REMOVE("remove"), /** * "replace" operation. */ REPLACE("replace"), /** * "move" operation. */ MOVE("move"), /** * "copy" operation. */ COPY("copy"), /** * "test" operation. */ TEST("test"); /** Operation name */ private final String operationName; /** * Create an enum constant with given {@code operationName}. * @param operationName the operation name for the enum constant */ private Operation(String operationName) { this.operationName = operationName; } /** * Returns enum constant name as lower case string. * * @return lower case name of the enum constant */ public String operationName() { return operationName; } /** * Returns the enum constant with the specified name. * * @param operationName {@code operationName} to convert to the enum constant. * @return the enum constant for given {@code operationName} * @throws JsonException if given {@code operationName} is not recognized */ public static Operation fromOperationName(String operationName) { for (Operation op : values()) { if (op.operationName().equalsIgnoreCase(operationName)) { return op; } } throw new JsonException("Illegal value for the operationName of the JSON patch operation: " + operationName); } } /** * Applies the patch operations to the specified {@code target}. * The target is not modified by the patch. * * @param the target type, must be a subtype of {@link JsonStructure} * @param target the target to apply the patch operations * @return the transformed target after the patch * @throws JsonException if the supplied JSON Patch is malformed or if * it contains references to non-existing members */ T apply(T target); /** * Returns the {@code JsonPatch} as {@code JsonArray}. * * @return this {@code JsonPatch} as {@code JsonArray} */ JsonArray toJsonArray(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonPatchBuilder.java000066400000000000000000000141511451447132700263430ustar00rootroot00000000000000/* * Copyright (c) 2015, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** * A builder for constructing a JSON Patch as defined by * RFC 6902 by adding * JSON Patch operations incrementally. *

* The following illustrates the approach. *

 *   JsonPatchBuilder builder = Json.createPatchBuilder();
 *   JsonPatch patch = builder.add("/John/phones/office", "1234-567")
 *                            .remove("/Amy/age")
 *                            .build();
 * 
* The result is equivalent to the following JSON Patch. *
 * [
 *    {"op" = "add", "path" = "/John/phones/office", "value" = "1234-567"},
 *    {"op" = "remove", "path" = "/Amy/age"}
 * ] 
* * @see RFC 6902 * * @since 1.1 */ public interface JsonPatchBuilder { /** * Adds an "add" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder add(String path, JsonValue value); /** * Adds an "add" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder add(String path, String value); /** * Adds an "add" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder add(String path, int value); /** * Adds an "add" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder add(String path, boolean value); /** * Adds a "remove" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer. * @return this JsonPatchBuilder */ JsonPatchBuilder remove(String path); /** * Adds a "replace" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder replace(String path, JsonValue value); /** * Adds a "replace" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder replace(String path, String value); /** * Adds a "replace" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder replace(String path, int value); /** * Adds a "replace" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder replace(String path, boolean value); /** * Adds a "move" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param from the "from" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder move(String path, String from); /** * Adds a "copy" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param from the "from" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder copy(String path, String from); /** * Adds a "test" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder test(String path, JsonValue value); /** * Adds a "test" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder test(String path, String value); /** * Adds a "test" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder test(String path, int value); /** * Adds a "test" JSON Patch operation. * * @param path the "path" member of the operation. Must be a valid escaped JSON-Pointer string. * @param value the "value" member of the operation * @return this JsonPatchBuilder */ JsonPatchBuilder test(String path, boolean value); /** * Returns the JSON Patch. * * @return a JSON Patch */ JsonPatch build(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonPointer.java000066400000000000000000000135071451447132700254210ustar00rootroot00000000000000/* * Copyright (c) 2015, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** *

This interface represents an immutable implementation of a JSON Pointer * as defined by RFC 6901. *

*

A JSON Pointer, when applied to a target {@link JsonValue}, * defines a reference location in the target.

*

An empty JSON Pointer string defines a reference to the target itself.

*

If the JSON Pointer string is non-empty, it must be a sequence * of '/' prefixed tokens, and the target must either be a {@link JsonArray} * or {@link JsonObject}. If the target is a {@code JsonArray}, the pointer * defines a reference to an array element, and the last token specifies the index. * If the target is a {@link JsonObject}, the pointer defines a reference to a * name/value pair, and the last token specifies the name. *

*

The method {@link #getValue getValue()} returns the referenced value. * Methods {@link #add add()}, {@link #replace replace()}, * and {@link #remove remove()} execute operations specified in * RFC 6902.

* * @see RFC 6901 * @see RFC 6902 * * @since 1.1 */ public interface JsonPointer { /** * Adds or replaces a value at the referenced location in the specified * {@code target} with the specified {@code value}. *
    *
  1. If the reference is the target (empty JSON Pointer string), * the specified {@code value}, which must be the same type as * specified {@code target}, is returned.
  2. *
  3. If the reference is an array element, the specified {@code value} is inserted * into the array, at the referenced index. The value currently at that location, and * any subsequent values, are shifted to the right (adds one to the indices). * Index starts with 0. If the reference is specified with a "-", or if the * index is equal to the size of the array, the value is appended to the array.
  4. *
  5. If the reference is a name/value pair of a {@code JsonObject}, and the * referenced value exists, the value is replaced by the specified {@code value}. * If the value does not exist, a new name/value pair is added to the object.
  6. *
* * @param the target type, must be a subtype of {@link JsonValue} * @param target the target referenced by this {@code JsonPointer} * @param value the value to be added * @return the transformed {@code target} after the value is added. * @throws NullPointerException if {@code target} is {@code null} * @throws JsonException if the reference is an array element and * the index is out of range ({@code index < 0 || index > array size}), * or if the pointer contains references to non-existing objects or arrays. */ T add(T target, JsonValue value); /** * Removes the value at the reference location in the specified {@code target}. * * @param the target type, must be a subtype of {@link JsonValue} * @param target the target referenced by this {@code JsonPointer} * @return the transformed {@code target} after the value is removed. * @throws NullPointerException if {@code target} is {@code null} * @throws JsonException if the referenced value does not exist, * or if the reference is the target. */ T remove(T target); /** * Replaces the value at the referenced location in the specified * {@code target} with the specified {@code value}. * * @param the target type, must be a subtype of {@link JsonValue} * @param target the target referenced by this {@code JsonPointer} * @param value the value to be stored at the referenced location * @return the transformed {@code target} after the value is replaced. * @throws NullPointerException if {@code target} is {@code null} * @throws JsonException if the referenced value does not exist, * or if the reference is the target. */ T replace(T target, JsonValue value); /** * Returns {@code true} if there is a value at the referenced location in the specified {@code target}. * * @param target the target referenced by this {@code JsonPointer} * @return {@code true} if this pointer points to a value in a specified {@code target}. */ boolean containsValue(JsonStructure target); /** * Returns the value at the referenced location in the specified {@code target}. * * @param target the target referenced by this {@code JsonPointer} * @return the referenced value in the target. * @throws NullPointerException if {@code target} is null * @throws JsonException if the referenced value does not exist */ JsonValue getValue(JsonStructure target); /** * Returns the string representation of this JSON Pointer. * The value to be returned is an empty string or a sequence of '{@code /}' prefixed tokens. * * @return the valid escaped JSON Pointer string. */ @Override String toString(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonReader.java000066400000000000000000000113501451447132700251750ustar00rootroot00000000000000/* * Copyright (c) 2012, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.Closeable; /** * Reads a JSON {@link JsonObject object} or an {@link JsonArray array} * structure from an input source. * *

The class {@link jakarta.json.Json} contains methods to create readers from * input sources ({@link java.io.InputStream} and {@link java.io.Reader}). * *

* The following example demonstrates how to read an empty JSON array from * a string: *

 * 
 * JsonReader jsonReader = Json.createReader(new StringReader("[]"));
 * JsonArray array = jsonReader.readArray();
 * jsonReader.close();
 * 
 * 
* *

* The class {@link JsonReaderFactory} also contains methods to create * {@code JsonReader} instances. A factory instance can be used to create * multiple reader instances with the same configuration. This the preferred * way to create multiple instances. A sample usage is shown in the following * example: *

 * 
 * JsonReaderFactory factory = Json.createReaderFactory(config);
 * JsonReader reader1 = factory.createReader(...);
 * JsonReader reader2 = factory.createReader(...);
 * 
 * 
*/ public interface JsonReader extends /*Auto*/Closeable { /** * Returns a JSON array or object that is represented in * the input source. This method needs to be called * only once for a reader instance. * * @return a JSON object or array * @throws JsonException if a JSON object or array cannot * be created due to i/o error (IOException would be * cause of JsonException) * @throws jakarta.json.stream.JsonParsingException if a JSON object or array * cannot be created due to incorrect representation * @throws IllegalStateException if read, readObject, readArray, * readValue or close method is already called */ JsonStructure read(); /** * Returns a JSON object that is represented in * the input source. This method needs to be called * only once for a reader instance. * * @return a JSON object * @throws JsonException if a JSON object cannot * be created due to i/o error (IOException would be * cause of JsonException) * @throws jakarta.json.stream.JsonParsingException if a JSON object cannot * be created due to incorrect representation * @throws IllegalStateException if read, readObject, readArray, * readValue or close method is already called */ JsonObject readObject(); /** * Returns a JSON array that is represented in * the input source. This method needs to be called * only once for a reader instance. * * @return a JSON array * @throws JsonException if a JSON array cannot * be created due to i/o error (IOException would be * cause of JsonException) * @throws jakarta.json.stream.JsonParsingException if a JSON array cannot * be created due to incorrect representation * @throws IllegalStateException if read, readObject, readArray, * readValue or close method is already called */ JsonArray readArray(); /** * Returns a JSON value that is represented in * the input source. This method needs to be called * only once for a reader instance. * * @return a JSON value * @throws JsonException if a JSON value * be created due to i/o error (IOException would be * cause of JsonException) * @throws jakarta.json.stream.JsonParsingException if a JSON value * cannot be created due to incorrect representation * @throws IllegalStateException if read, readObject, readArray, * readValue or close method is already called * * @since 1.1 */ default JsonValue readValue() { throw new UnsupportedOperationException(); } /** * Closes this reader and frees any resources associated with the * reader. This method closes the underlying input source. * * @throws JsonException if an i/o error occurs (IOException would be * cause of JsonException) */ @Override void close(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonReaderFactory.java000066400000000000000000000062211451447132700265260ustar00rootroot00000000000000/* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.InputStream; import java.io.Reader; import java.nio.charset.Charset; import java.util.Map; /** * Factory to create {@link jakarta.json.JsonReader} instances. If a factory * instance is configured with some configuration, that would be * used to configure the created reader instances. * *

* {@link jakarta.json.JsonReader} can also be created using {@link Json}'s * {@code createReader} methods. If multiple reader instances are created, * then creating them using a reader factory is preferred. * *

* For example: *

 * 
 * JsonReaderFactory factory = Json.createReaderFactory(...);
 * JsonReader reader1 = factory.createReader(...);
 * JsonReader reader2 = factory.createReader(...);
 * 
 * 
* *

All the methods in this class are safe for use by multiple concurrent * threads. */ public interface JsonReaderFactory { /** * Creates a JSON reader from a character stream. The reader is configured * with the factory configuration. * * @param reader a reader from which JSON is to be read * @return a JSON reader */ JsonReader createReader(Reader reader); /** * Creates a JSON reader from a byte stream. The character encoding of * the stream is determined as described in * RFC 7159. * The reader is configured with the factory configuration. * * @param in a byte stream from which JSON is to be read * @return a JSON reader */ JsonReader createReader(InputStream in); /** * Creates a JSON reader from a byte stream. The bytes of the stream * are decoded to characters using the specified charset. The reader is * configured with the factory configuration. * * @param in a byte stream from which JSON is to be read * @param charset a charset * @return a JSON reader */ JsonReader createReader(InputStream in, Charset charset); /** * Returns read-only map of supported provider specific configuration * properties that are used to configure the created JSON readers. * If there are any specified configuration properties that are not * supported by the provider, they won't be part of the returned map. * * @return a map of supported provider specific properties that are used * to configure the readers. The map be empty but not null. */ Map getConfigInUse(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonString.java000066400000000000000000000036411451447132700252450ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** * An immutable JSON string value. */ public interface JsonString extends JsonValue { /** * Returns the JSON string value. * * @return a JSON string value */ String getString(); /** * Returns the char sequence for the JSON String value * * @return a char sequence for the JSON String value */ CharSequence getChars(); /** * Compares the specified object with this {@code JsonString} for equality. * Returns {@code true} if and only if the specified object is also a * {@code JsonString}, and their {@link #getString()} objects are * equal. * * @param obj the object to be compared for equality with this * {@code JsonString} * @return {@code true} if the specified object is equal to this * {@code JsonString} */ @Override boolean equals(Object obj); /** * Returns the hash code value for this {@code JsonString} object. * The hash code of a {@code JsonString} object is defined to be its * {@link #getString()} object's hash code. * * @return the hash code value for this {@code JsonString} object */ @Override int hashCode(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonStructure.java000066400000000000000000000025661451447132700260040ustar00rootroot00000000000000/* * Copyright (c) 2012, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** * Super type for the two structured types in JSON ({@link JsonObject object}s * and {@link JsonArray array}s). */ public interface JsonStructure extends JsonValue { /** * Get the value referenced by the provided JSON Pointer in the JsonStructure. * * @param jsonPointer the JSON Pointer * @return the {@code JsonValue} at the referenced location * @throws JsonException if the JSON Pointer is malformed, or if it references * a non-existing member or value. * * @since 1.1 */ default public JsonValue getValue(String jsonPointer) { return Json.createPointer(jsonPointer).getValue(this); } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonValue.java000066400000000000000000000061751451447132700250600ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; /** * JsonValue represents an immutable JSON value. * * *

A JSON value is one of the following: * an object ({@link JsonObject}), an array ({@link JsonArray}), * a number ({@link JsonNumber}), a string ({@link JsonString}), * {@code true} ({@link JsonValue#TRUE JsonValue.TRUE}), {@code false} * ({@link JsonValue#FALSE JsonValue.FALSE}), * or {@code null} ({@link JsonValue#NULL JsonValue.NULL}). */ public interface JsonValue { /** * The empty JSON object. * * @since 1.1 */ static final JsonObject EMPTY_JSON_OBJECT = new EmptyObject(); /** * The empty JSON array. * * @since 1.1 */ static final JsonArray EMPTY_JSON_ARRAY = new EmptyArray(); /** * Indicates the type of a {@link JsonValue} object. */ enum ValueType { /** * JSON array. */ ARRAY, /** * JSON object. */ OBJECT, /** * JSON string. */ STRING, /** * JSON number. */ NUMBER, /** * JSON true. */ TRUE, /** * JSON false. */ FALSE, /** * JSON null. */ NULL } /** * JSON null value. */ static final JsonValue NULL = new JsonValueImpl(ValueType.NULL); /** * JSON true value. */ static final JsonValue TRUE = new JsonValueImpl(ValueType.TRUE); /** * JSON false value. */ static final JsonValue FALSE = new JsonValueImpl(ValueType.FALSE); /** * Returns the value type of this JSON value. * * @return JSON value type */ ValueType getValueType(); /** * Return the JsonValue as a JsonObject * * @return the JsonValue as a JsonObject * @throws ClassCastException if the JsonValue is not a JsonObject * * @since 1.1 */ default JsonObject asJsonObject() { return JsonObject.class.cast(this); } /** * Return the JsonValue as a JsonArray * * @return the JsonValue as a JsonArray * @throws ClassCastException if the JsonValue is not a JsonArray * * @since 1.1 */ default JsonArray asJsonArray() { return JsonArray.class.cast(this); } /** * Returns JSON text for this JSON value. * * @return JSON text */ @Override String toString(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonValueImpl.java000066400000000000000000000052651451447132700257010ustar00rootroot00000000000000/* * Copyright (c) 2016, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.Serializable; /** * Private implementation of {@link JsonValue} for simple {@link ValueType}s * allowing their usage in constants which are better to implement {@link Serializable}. * * @author Lukas Jungmann */ final class JsonValueImpl implements JsonValue, Serializable { /** for serialization */ private static final long serialVersionUID = 83723433120886104L; /** Type of this JsonValue. */ private final ValueType valueType; /** * Default constructor. * @param valueType Type of this JsonValue */ JsonValueImpl(ValueType valueType) { this.valueType = valueType; } /** * Returns the value type of this JSON value. * * @return JSON value type */ @Override public ValueType getValueType() { return valueType; } /** * Compares the specified object with this {@link JsonValue} * object for equality. Returns {@code true} if and only if the * specified object is also a JsonValue, and their * {@link #getValueType()} objects are equal. * * @param obj the object to be compared for equality with this JsonValue * @return {@code true} if the specified object is equal to this * JsonValue */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof JsonValue) { return getValueType().equals(((JsonValue) obj).getValueType()); } return false; } /** * Returns the hash code value for this {@link JsonValue} object. * The hash code of the {@link JsonValue} object is defined to be * its {@link #getValueType()} object's hash code. * * @return the hash code value for this {@link JsonValue} object */ @Override public int hashCode() { return valueType.hashCode(); } @Override public String toString() { return valueType.name().toLowerCase(); } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonWriter.java000066400000000000000000000107451451447132700252560ustar00rootroot00000000000000/* * Copyright (c) 2012, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.Closeable; /** * Writes a JSON {@link JsonObject object} or {@link JsonArray array} structure * to an output source. * *

The class {@link jakarta.json.Json} contains methods to create writers from * output sources ({@link java.io.OutputStream} and {@link java.io.Writer}). * *

* The following example demonstrates how write an empty JSON object: *

 * 
 * JsonWriter jsonWriter = Json.createWriter(...);
 * jsonWriter.writeObject(Json.createObjectBuilder().build());
 * jsonWriter.close();
 * 
 * 
* *

* The class {@link JsonWriterFactory} also contains methods to create * {@code JsonWriter} instances. A factory instance can be used to create * multiple writer instances with the same configuration. This the preferred * way to create multiple instances. A sample usage is shown in the following * example: *

 * 
 * JsonWriterFactory factory = Json.createWriterFactory(config);
 * JsonWriter writer1 = factory.createWriter(...);
 * JsonWriter writer2 = factory.createWriter(...);
 * 
 * 
*/ public interface JsonWriter extends /*Auto*/Closeable { /** * Writes the specified JSON {@link JsonArray array} to the output * source. This method needs to be called only once for a writer instance. * * @param array JSON array that is to be written to the output source * @throws JsonException if the specified JSON object cannot be * written due to i/o error (IOException would be cause of * JsonException) * @throws IllegalStateException if writeArray, writeObject, write or close * method is already called */ void writeArray(JsonArray array); /** * Writes the specified JSON {@link JsonObject object} to the output * source. This method needs to be called only once for a writer instance. * * @param object JSON object that is to be written to the output source * @throws JsonException if the specified JSON object cannot be * written due to i/o error (IOException would be cause of JsonException) * @throws IllegalStateException if writeArray, writeObject, write or close * method is already called */ void writeObject(JsonObject object); /** * Writes the specified JSON {@link JsonObject object} or * {@link JsonArray array} to the output source. This method needs * to be called only once for a writer instance. * * @param value JSON array or object that is to be written to the output * source * @throws JsonException if the specified JSON object cannot be * written due to i/o error (IOException would be cause of * JsonException) * @throws IllegalStateException if writeArray, writeObject, write * or close method is already called */ void write(JsonStructure value); /** * Closes this JSON writer and frees any resources associated with the * writer. This method closes the underlying output source. * * @throws JsonException if an i/o error occurs (IOException would be * cause of JsonException) */ /** * Writes the specified {@link JsonValue} to the output source. * method needs to be called only once for a write instance. * * @param value a {@code JsonValue} to be written to the output * source * @throws JsonException if the specified JSON object cannot be * written due to i/o error (IOException would be cause of * JsonException) * @throws IllegalStateException if writeArray, writeObject, write * or close method is already called * * @since 1.1 */ default void write(JsonValue value) { throw new UnsupportedOperationException(); } @Override void close(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/JsonWriterFactory.java000066400000000000000000000066321451447132700266060ustar00rootroot00000000000000/* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.util.Map; /** * Factory to create {@link jakarta.json.JsonWriter} instances. If a factory * instance is configured with some configuration, that would be * used to configure the created writer instances. * *

* {@link jakarta.json.JsonWriter} can also be created using {@link Json}'s * {@code createWriter} methods. If multiple writer instances are created, * then creating them using a writer factory is preferred. * *

* For example: *

 * 
 * JsonWriterFactory factory = Json.createWriterFactory(...);
 * JsonWriter writer1 = factory.createWriter(...);
 * JsonWriter writer2 = factory.createWriter(...);
 * 
 * 
* *

All the methods in this class are safe for use by multiple concurrent * threads. */ public interface JsonWriterFactory { /** * Creates a JSON writer to write a JSON {@link JsonObject object} or * {@link JsonArray array} structure to the specified character stream. * The writer is configured with the factory configuration. * * @param writer to which JSON object or array is written * @return a JSON writer */ JsonWriter createWriter(Writer writer); /** * Creates a JSON writer to write a JSON {@link JsonObject object} or * {@link JsonArray array} structure to the specified byte stream. * Characters written to the stream are encoded into bytes using UTF-8 * encoding. The writer is configured with the factory configuration. * * @param out to which JSON object or array is written * @return a JSON writer */ JsonWriter createWriter(OutputStream out); /** * Creates a JSON writer to write a JSON {@link JsonObject object} or * {@link JsonArray array} structure to the specified byte stream. * Characters written to the stream are encoded into bytes using the * specified charset. The writer is configured with the factory * configuration. * * @param out to which JSON object or array is written * @param charset a charset * @return a JSON writer */ JsonWriter createWriter(OutputStream out, Charset charset); /** * Returns read-only map of supported provider specific configuration * properties that are used to configure the created JSON writer objects. * If there are any specified configuration properties that are not * supported by the provider, they won't be part of the returned map. * * @return a map of supported provider specific properties that are used * to configure the created writers. The map may be empty but not null. */ Map getConfigInUse(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/package-info.java000066400000000000000000000044641451447132700254750ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /** * Provides an object model API to process JSON. * *

The object model API is a high-level API that provides immutable object * models for JSON object and array structures. These JSON structures are * represented as object models using the Java types {@link jakarta.json.JsonObject} * and {@link jakarta.json.JsonArray}. The interface {@code jakarta.json.JsonObject} provides * a {@link java.util.Map} view to access the unordered collection of zero or * more name/value pairs from the model. Similarly, the interface * {@code JsonArray} provides a {@link java.util.List} view to access the * ordered sequence of zero or more values from the model. * *

The object model API uses builder patterns to create and modify * these object models. The classes {@link jakarta.json.JsonObjectBuilder} and * {@link jakarta.json.JsonArrayBuilder} provide methods to create and modify models * of type {@code JsonObject} and {@code JsonArray} respectively. * *

These object models can also be created from an input source using * the class {@link jakarta.json.JsonReader}. Similarly, these object models * can be written to an output source using the class {@link jakarta.json.JsonWriter}. *

* This package includes several classes that implement other JSON related * standards: JSON Pointer, * JSON Patch, and * JSON Merge Patch. * They can be used to retrieve, transform or manipulate values in an * object model. */ package jakarta.json; jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/spi/000077500000000000000000000000001451447132700230715ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/spi/JsonProvider.java000066400000000000000000000543111451447132700263640ustar00rootroot00000000000000/* * Copyright (c) 2011, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.spi; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import java.util.logging.Level; import java.util.logging.Logger; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonException; import jakarta.json.JsonMergePatch; import jakarta.json.JsonNumber; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonPatch; import jakarta.json.JsonPatchBuilder; import jakarta.json.JsonPointer; import jakarta.json.JsonReader; import jakarta.json.JsonReaderFactory; import jakarta.json.JsonString; import jakarta.json.JsonStructure; import jakarta.json.JsonValue; import jakarta.json.JsonWriter; import jakarta.json.JsonWriterFactory; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonGeneratorFactory; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParserFactory; /** * Service provider for JSON processing objects. * *

All the methods in this class are safe for use by multiple concurrent * threads. * * @see ServiceLoader */ public abstract class JsonProvider { /** * The name of the property that contains the name of the class capable of creating new JsonProvider objects. */ public static final String JSONP_PROVIDER_FACTORY = "jakarta.json.provider"; /** * A constant representing the name of the default * {@code JsonProvider} implementation class. */ private static final String DEFAULT_PROVIDER = "org.eclipse.parsson.JsonProviderImpl"; /** A logger */ private static final Logger LOG = Logger.getLogger(JsonProvider.class.getName()); /** * Default constructor. */ protected JsonProvider() { } /** * Creates a JSON provider object. * * Implementation discovery consists of following steps: *

    *
  1. If the system property {@value #JSONP_PROVIDER_FACTORY} exists, * then its value is assumed to be the provider factory class. * This phase of the look up enables per-JVM override of the JsonProvider implementation.
  2. *
  3. The provider is loaded using the {@link ServiceLoader#load(Class)} method.
  4. *
  5. If all the steps above fail, then the rest of the look up is unspecified. That said, * the recommended behavior is to simply look for some hard-coded platform default Jakarta * JSON Processing implementation. This phase of the look up is so that a platform can have * its own Jakarta JSON Processing implementation as the last resort.
  6. *
* Users are recommended to cache the result of this method. * * @see ServiceLoader * @return a JSON provider */ public static JsonProvider provider() { LOG.log(Level.FINE, "Checking system property {0}", JSONP_PROVIDER_FACTORY); final String factoryClassName = System.getSecurityManager() != null ? AccessController.doPrivileged((PrivilegedAction) () -> System.getProperty(JSONP_PROVIDER_FACTORY)) : System.getProperty(JSONP_PROVIDER_FACTORY); if (factoryClassName != null) { JsonProvider provider = newInstance(factoryClassName); LOG.log(Level.FINE, "System property used; returning object [{0}]", provider.getClass().getName()); return provider; } LOG.log(Level.FINE, "Checking ServiceLoader"); ServiceLoader loader = ServiceLoader.load(JsonProvider.class); Iterator it = loader.iterator(); if (it.hasNext()) { JsonProvider provider = it.next(); LOG.log(Level.FINE, "ServiceLoader loading Facility used; returning object [{0}]", provider.getClass().getName()); return provider; } // handling OSGi (specific default) if (isOsgi()) { LOG.log(Level.FINE, "Checking OSGi"); JsonProvider provider = lookupUsingOSGiServiceLoader(JsonProvider.class); if (provider != null) { LOG.log(Level.FINE, "OSGi loading facility used; returning object [{0}].", provider.getClass().getName()); return provider; } } // else no provider found LOG.fine("Trying to create the platform default provider"); return newInstance(DEFAULT_PROVIDER); } /** * Creates a new instance from the specified class * @param className name of the class to instantiate * @return the JsonProvider instance * @throws JsonException for issues during creation of an instance of the JsonProvider */ private static JsonProvider newInstance(String className) { try { checkPackageAccess(className); @SuppressWarnings({"unchecked"}) Class clazz = (Class) Class.forName(className); return clazz.getConstructor().newInstance(); } catch (ClassNotFoundException x) { throw new JsonException( "Provider " + className + " not found", x); } catch (Exception x) { throw new JsonException( "Provider " + className + " could not be instantiated: " + x, x); } } /** * Make sure that the current thread has an access to the package of the given name. * @param className The class name to check. */ private static void checkPackageAccess(String className) { SecurityManager s = System.getSecurityManager(); if (s != null) { int i = className.lastIndexOf('.'); if (i != -1) { s.checkPackageAccess(className.substring(0, i)); } } } /** * Creates a JSON parser from a character stream. * * @param reader i/o reader from which JSON is to be read * @return a JSON parser */ public abstract JsonParser createParser(Reader reader); /** * Creates a JSON parser from the specified byte stream. * The character encoding of the stream is determined * as defined in RFC 7159 * . * * @param in i/o stream from which JSON is to be read * @throws JsonException if encoding cannot be determined * or i/o error (IOException would be cause of JsonException) * @return a JSON parser */ public abstract JsonParser createParser(InputStream in); /** * Creates a parser factory for creating {@link JsonParser} instances. * * @return a JSON parser factory * public abstract JsonParserFactory createParserFactory(); */ /** * Creates a parser factory for creating {@link JsonParser} instances. * The factory is configured with the specified map of * provider specific configuration properties. Provider implementations * should ignore any unsupported configuration properties specified in * the map. * * @param config a map of provider specific properties to configure the * JSON parsers. The map may be empty or null * @return a JSON parser factory */ public abstract JsonParserFactory createParserFactory(Map config); /** * Creates a JSON generator for writing JSON text to a character stream. * * @param writer a i/o writer to which JSON is written * @return a JSON generator */ public abstract JsonGenerator createGenerator(Writer writer); /** * Creates a JSON generator for writing JSON text to a byte stream. * * @param out i/o stream to which JSON is written * @return a JSON generator */ public abstract JsonGenerator createGenerator(OutputStream out); /** * Creates a generator factory for creating {@link JsonGenerator} instances. * * @return a JSON generator factory * public abstract JsonGeneratorFactory createGeneratorFactory(); */ /** * Creates a generator factory for creating {@link JsonGenerator} instances. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should * ignore any unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON generators. The map may be empty or null * @return a JSON generator factory */ public abstract JsonGeneratorFactory createGeneratorFactory(Map config); /** * Creates a JSON reader from a character stream. * * @param reader a reader from which JSON is to be read * @return a JSON reader */ public abstract JsonReader createReader(Reader reader); /** * Creates a JSON reader from a byte stream. The character encoding of * the stream is determined as described in * RFC 7159. * * @param in a byte stream from which JSON is to be read * @return a JSON reader */ public abstract JsonReader createReader(InputStream in); /** * Creates a JSON writer to write a * JSON {@link JsonObject object} or {@link JsonArray array} * structure to the specified character stream. * * @param writer to which JSON object or array is written * @return a JSON writer */ public abstract JsonWriter createWriter(Writer writer); /** * Creates a JSON writer to write a * JSON {@link JsonObject object} or {@link JsonArray array} * structure to the specified byte stream. Characters written to * the stream are encoded into bytes using UTF-8 encoding. * * @param out to which JSON object or array is written * @return a JSON writer */ public abstract JsonWriter createWriter(OutputStream out); /** * Creates a writer factory for creating {@link JsonWriter} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON writers. The map may be empty or null * @return a JSON writer factory */ public abstract JsonWriterFactory createWriterFactory(Map config); /** * Creates a reader factory for creating {@link JsonReader} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON readers. The map may be empty or null * @return a JSON reader factory */ public abstract JsonReaderFactory createReaderFactory(Map config); /** * Creates a JSON object builder. * * @return a JSON object builder */ public abstract JsonObjectBuilder createObjectBuilder(); /** * Creates a JSON object builder, initialized with the specified object. * * @param object the initial JSON object in the builder * @return a JSON object builder * * @since 1.1 */ public JsonObjectBuilder createObjectBuilder(JsonObject object) { throw new UnsupportedOperationException(); } /** * Creates a JSON object builder, initialized with the data from specified {@code map}. * If the @{code map} contains {@link Optional}s then resulting JSON object builder * contains the key from the {@code map} only if the {@link Optional} is not empty. * * @param map the initial object in the builder * @return a JSON object builder * @exception IllegalArgumentException if the value from the {@code map} cannot be converted * to the corresponding {@link JsonValue} * * @since 1.1 */ public JsonObjectBuilder createObjectBuilder(Map map) { throw new UnsupportedOperationException(); } /** * Creates a JSON array builder. * * @return a JSON array builder */ public abstract JsonArrayBuilder createArrayBuilder(); /** * Creates a JSON array builder, initialized with the specified array. * * @param array the initial JSON array in the builder * @return a JSON array builder * * @since 1.1 */ public JsonArrayBuilder createArrayBuilder(JsonArray array) { throw new UnsupportedOperationException(); } /** * Creates JSON Pointer (RFC 6901) * from given {@code jsonPointer} string. *
    *
  • An empty {@code jsonPointer} string defines a reference to the target itself.
  • *
  • If the {@code jsonPointer} string is non-empty, it must be a sequence of '{@code /}' prefixed tokens.
  • *
* * @param jsonPointer the JSON Pointer string * @throws NullPointerException if {@code jsonPointer} is {@code null} * @throws JsonException if {@code jsonPointer} is not a valid JSON Pointer * @return a JSON Pointer * * @since 1.1 */ public JsonPointer createPointer(String jsonPointer) { throw new UnsupportedOperationException(); } /** * Creates a JSON Patch builder (RFC 6902). * * @return a JSON Patch builder * * @since 1.1 */ public JsonPatchBuilder createPatchBuilder() { throw new UnsupportedOperationException(); } /** * Creates a JSON Patch builder * (RFC 6902), * initialized with the specified operations. * * @param array the initial patch operations * @return a JSON Patch builder * * @since 1.1 */ public JsonPatchBuilder createPatchBuilder(JsonArray array) { throw new UnsupportedOperationException(); } /** * Creates a JSON Patch (RFC 6902) * from the specified operations. * * @param array patch operations * @return a JSON Patch * * @since 1.1 */ public JsonPatch createPatch(JsonArray array) { throw new UnsupportedOperationException(); } /** * Generates a JSON Patch (RFC 6902) * from the source and target {@code JsonStructure}. * The generated JSON Patch need not be unique. * * @param source the source * @param target the target, must be the same type as the source * @return a JSON Patch which when applied to the source, yields the target * * @since 1.1 */ public JsonPatch createDiff(JsonStructure source, JsonStructure target) { throw new UnsupportedOperationException(); } /** * Creates JSON Merge Patch (RFC 7396) * from specified {@code JsonValue}. * * @param patch the patch * @return a JSON Merge Patch * * @since 1.1 */ public JsonMergePatch createMergePatch(JsonValue patch) { throw new UnsupportedOperationException(); } /** * Generates a JSON Merge Patch (RFC 7396) * from the source and target {@code JsonValue}s * which when applied to the {@code source}, yields the {@code target}. * * @param source the source * @param target the target * @return a JSON Merge Patch * * @since 1.1 */ public JsonMergePatch createMergeDiff(JsonValue source, JsonValue target) { throw new UnsupportedOperationException(); } /** * Creates a JSON array builder, initialized with the content of specified {@code collection}. * If the @{code collection} contains {@link Optional}s then resulting JSON array builder * contains the value from the {@code collection} only if the {@link Optional} is not empty. * * @param collection the initial data for the builder * @return a JSON array builder * @exception IllegalArgumentException if the value from the {@code collection} cannot be converted * to the corresponding {@link JsonValue} * * @since 1.1 */ public JsonArrayBuilder createArrayBuilder(Collection collection) { throw new UnsupportedOperationException(); } /** * Creates a builder factory for creating {@link JsonArrayBuilder} * and {@link JsonObjectBuilder} objects. * The factory is configured with the specified map of provider specific * configuration properties. Provider implementations should ignore any * unsupported configuration properties specified in the map. * * @param config a map of provider specific properties to configure the * JSON builders. The map may be empty or null * @return a JSON builder factory */ public abstract JsonBuilderFactory createBuilderFactory(Map config); /** * Creates a JsonString. * * @param value a JSON string * @return the JsonString for the string * * @since 1.1 */ public JsonString createValue(String value) { throw new UnsupportedOperationException(); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public JsonNumber createValue(int value) { throw new UnsupportedOperationException(); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public JsonNumber createValue(long value) { throw new UnsupportedOperationException(); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public JsonNumber createValue(double value) { throw new UnsupportedOperationException(); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public JsonNumber createValue(BigDecimal value) { throw new UnsupportedOperationException(); } /** * Creates a JsonNumber. * * @param value a JSON number * @return the JsonNumber for the number * * @since 1.1 */ public JsonNumber createValue(BigInteger value) { throw new UnsupportedOperationException(); } /** * Creates a JsonNumber. * * When it is not implemented it checks the type and delegates * to an existing method that already handles that type. It throws * UnsupportedOperationException in case the type is not known. * * @param number a JSON number * @return the JsonNumber for the number * * @since 2.1 */ public JsonNumber createValue(Number number) { if (number instanceof Integer) { return createValue(number.intValue()); } else if (number instanceof Long) { return createValue(number.longValue()); } else if (number instanceof Double) { return createValue(number.doubleValue()); } else if (number instanceof BigInteger) { return createValue((BigInteger) number); } else if (number instanceof BigDecimal) { return createValue((BigDecimal) number); } else { throw new UnsupportedOperationException(number + " type is not known"); } } /** OSGI aware service loader by HK2 */ private static final String OSGI_SERVICE_LOADER_CLASS_NAME = "org.glassfish.hk2.osgiresourcelocator.ServiceLoader"; /** * Check availability of HK2 service loader. * * @return true if HK2 service locator is available */ private static boolean isOsgi() { try { Class.forName(OSGI_SERVICE_LOADER_CLASS_NAME); return true; } catch (ClassNotFoundException ignored) { } return false; } /** * Lookup the service class by the HK2 service locator. * * @param serviceClass service class * @param type of the service * @return a provider */ private static T lookupUsingOSGiServiceLoader(Class serviceClass) { try { // Use reflection to avoid having any dependendcy on HK2 ServiceLoader class Class[] args = new Class[]{serviceClass}; Class target = Class.forName(OSGI_SERVICE_LOADER_CLASS_NAME); Method m = target.getMethod("lookupProviderInstances", Class.class); @SuppressWarnings({"unchecked"}) Iterator iter = ((Iterable) m.invoke(null, (Object[]) args)).iterator(); return iter.hasNext() ? iter.next() : null; } catch (Exception ex) { LOG.log(Level.FINE, "Unable to find from OSGi: [" + serviceClass.getName() + "]", ex); return null; } } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/spi/package-info.java000066400000000000000000000030531451447132700262610ustar00rootroot00000000000000/* * Copyright (c) 2012, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /** * Service Provider Interface (SPI) to plug in implementations for * JSON processing objects. * *

{@link jakarta.json.spi.JsonProvider JsonProvider} is an abstract class * that provides a service for creating JSON processing instances. * A service provider for {@code JsonProvider} provides an * specific implementation by subclassing and implementing the methods in * {@code JsonProvider}. This enables using custom, efficient JSON processing * implementations (for e.g. parser and generator) other than the default ones. * *

The API locates and loads providers using {@link java.util.ServiceLoader}. * * Unless otherwise noted, passing a null argument to a constructor or method * in any class or interface in this package will cause a NullPointerException * to be thrown. * * @since JSON Processing 1.0 */ package jakarta.json.spi; jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/000077500000000000000000000000001451447132700235715ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonCollectors.java000066400000000000000000000157431451447132700274110ustar00rootroot00000000000000/* * Copyright (c) 2015, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import java.util.Map; import java.util.HashMap; import java.util.stream.Collector; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.BiConsumer; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; import jakarta.json.JsonException; /** * This class contains some implementations of {@code java.util.stream.Collector} for accumulating * {@link JsonValue}s into {@link JsonArray} and {@link JsonObject}. * * @since 1.1 */ public final class JsonCollectors { /** * No instantiation. */ private JsonCollectors() { } /** * Constructs a {@code java.util.stream.Collector} that accumulates the input {@code JsonValue} * elements into a {@code JsonArray}. * * @return the constructed Collector */ public static Collector toJsonArray() { return Collector.of( Json::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::addAll, JsonArrayBuilder::build); } /** * Constructs a {@code java.util.stream.Collector} that accumulates the input {@code Map.Entry} * elements into a {@code JsonObject}. * * @return the constructed Collector */ public static Collector, JsonObjectBuilder, JsonObject> toJsonObject() { return Collector.of( Json::createObjectBuilder, (JsonObjectBuilder b, Map.Entry v) -> b.add(v.getKey(), v.getValue()), JsonObjectBuilder::addAll, JsonObjectBuilder::build); } /** * Constructs a {@code java.util.stream.Collector} that accumulates the input {@code JsonValue} * elements into a {@code JsonObject}. The name/value pairs of the {@code JsonObject} are computed * by applying the provided mapping functions. * * @param keyMapper a mapping function to produce names. * @param valueMapper a mapping function to produce values * @return the constructed Collector */ public static Collector toJsonObject(Function keyMapper, Function valueMapper) { return Collector.of( Json::createObjectBuilder, (b, v) -> b.add(keyMapper.apply(v), valueMapper.apply(v)), JsonObjectBuilder::addAll, JsonObjectBuilder::build, Collector.Characteristics.UNORDERED); } /** * Constructs a {@code java.util.stream.Collector} that implements a "group by" operation on the * input {@code JsonValue} elements. A classifier function maps the input {@code JsonValue}s to keys, and * the {@code JsonValue}s are partitioned into groups according to the value of the key. * A reduction operation is performed on the {@code JsonValue}s in each group, using the * downstream {@code Collector}. For each group, the key and the results of the reduction operation * become the name/value pairs of the resultant {@code JsonObject}. * * @param the intermediate accumulation {@code JsonArrayBuilder} of the downstream collector * @param classifier a function mapping the input {@code JsonValue}s to a String, producing keys * @param downstream a {@code Collector} that implements a reduction operation on the * {@code JsonValue}s in each group. * @return the constructed {@code Collector} */ public static Collector, JsonObject> groupingBy(Function classifier, Collector downstream) { BiConsumer, JsonValue> accumulator = (map, value) -> { String key = classifier.apply(value); if (key == null) { throw new JsonException("element cannot be mapped to a null key"); } // Build a map of key to JsonArrayBuilder T arrayBuilder = map.computeIfAbsent(key, v->downstream.supplier().get()); // Add elements from downstream Collector to the arrayBuilder. downstream.accumulator().accept(arrayBuilder, value); }; Function, JsonObject> finisher = map -> { // transform the map of name: JsonArrayBuilder to // name: JsonArray // using the downstream collector for reducing the JsonArray JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); map.forEach((k, v) -> { JsonArray array = downstream.finisher().apply(v); objectBuilder.add(k, array); }); return objectBuilder.build(); }; BinaryOperator> combiner = (map1, map2) -> { map1.putAll(map2); return map1; }; return Collector.of(HashMap::new, accumulator, combiner, finisher, Collector.Characteristics.UNORDERED); } /** * Constructs a {@code java.util.stream.Collector} that implements a "group by" operation on the * input {@code JsonValue} elements. A classifier function maps the input {@code JsonValue}s to keys, and * the {@code JsonValue}s are partitioned into groups according to the value of the key. * The {@code JsonValue}s in each group are added to a {@code JsonArray}. The key and the * {@code JsonArray} in each group becomes the name/value pair of the resultant {@code JsonObject}. * * @param classifier a function mapping the input {@code JsonValue}s to a String, producing keys * @return the constructed {@code Collector} */ public static Collector, JsonObject> groupingBy(Function classifier) { return groupingBy(classifier, toJsonArray()); } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonGenerationException.java000066400000000000000000000043271451447132700312460ustar00rootroot00000000000000/* * Copyright (c) 2012, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import jakarta.json.JsonException; /** * {@code JsonGenerationException} indicates an incorrect JSON is * being generated. */ public class JsonGenerationException extends JsonException { /** for serialization */ private static final long serialVersionUID = -207609100806940680L; /** * Constructs a new runtime exception with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public JsonGenerationException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause.

Note that the detail message associated with * {@code cause} is not automatically incorporated in * this runtime exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public JsonGenerationException(String message, Throwable cause) { super(message, cause); } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonGenerator.java000066400000000000000000000520041451447132700272150ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import jakarta.json.JsonValue; import java.io.Closeable; import java.io.Flushable; import java.math.BigDecimal; import java.math.BigInteger; /** * Writes JSON data to an output source in a streaming way. The class * {@link jakarta.json.Json} contains methods to create generators for character * or output streams ({@link java.io.Writer} and {@link java.io.OutputStream}). * *

* The following example shows how to create a JSON generator: *

 * 
 * JsonGenerator generator = Json.createGenerator(...);
 * 
 * 
* *

* The class {@link JsonGeneratorFactory} also contains methods to create * {@code JsonGenerator} instances. {@link JsonGeneratorFactory} should be used * when creating multiple generator instances, as in the following example: *

 * 
 * JsonGeneratorFactory factory = Json.createGeneratorFactory();
 * JsonGenerator generator1 = factory.createGenerator(...);
 * JsonGenerator generator2 = factory.createGenerator(...);
 * 
 * 
* *

* JSON objects can be created using {@code JsonGenerator} by calling the * {@link #writeStartObject()} method and then adding name/value pairs with the * {@code write} method. *

* The following example shows how to generate an empty JSON object: *

 * 
 * JsonGenerator generator = ...;
 * generator.writeStartObject().writeEnd().close();
 * 
 * 
* * JSON arrays can be created using {@code JsonGenerator} by calling the * {@link #writeStartArray()} method and then adding values with the * {@code write} method. * *

* The following example shows how to generate an empty JSON array: *

 * 
 * JsonGenerator generator = ...;
 * generator.writeStartArray().writeEnd().close();
 * 
 * 
* *

* Other JSON values (that are not JSON objects or arrays) can be created * by calling the appropiate {@code write} methods. *

* The following example shows how to generate a JSON string: *


 * JsonGenerator generator = ...;
 * generator.write("message").close();
 * 
* * {@code JsonGenerator} methods can be chained as in the following example: *
 * 
 * generator
 *     .writeStartObject()
 *         .write("firstName", "John")
 *         .write("lastName", "Smith")
 *         .write("age", 25)
 *         .writeStartObject("address")
 *             .write("streetAddress", "21 2nd Street")
 *             .write("city", "New York")
 *             .write("state", "NY")
 *             .write("postalCode", "10021")
 *         .writeEnd()
 *         .writeStartArray("phoneNumber")
 *             .writeStartObject()
 *                 .write("type", "home")
 *                 .write("number", "212 555-1234")
 *             .writeEnd()
 *             .writeStartObject()
 *                 .write("type", "fax")
 *                 .write("number", "646 555-4567")
 *             .writeEnd()
 *         .writeEnd()
 *     .writeEnd();
 * generator.close();
 * 
 * 
* * The example code above generates the following JSON (or equivalent): *
 * 
 * {
 *   "firstName": "John", "lastName": "Smith", "age": 25,
 *   "address" : {
 *       "streetAddress": "21 2nd Street",
 *       "city": "New York",
 *       "state": "NY",
 *       "postalCode": "10021"
 *   },
 *   "phoneNumber": [
 *       {"type": "home", "number": "212 555-1234"},
 *       {"type": "fax", "number": "646 555-4567"}
 *    ]
 * }
 * 
 * 
* * The generated JSON text must strictly conform to the grammar defined in * RFC 7159. * * @see jakarta.json.Json * @see JsonGeneratorFactory */ public interface JsonGenerator extends Flushable, /*Auto*/Closeable { /** * Configuration property to generate JSON prettily. All providers * must support this property. The value of the property could be * be anything. */ String PRETTY_PRINTING = "jakarta.json.stream.JsonGenerator.prettyPrinting" ; /** * Writes the JSON start object character. It starts a new child object * context within which JSON name/value pairs can be written to the object. * This method is valid only in an array context, field context or in no context (when a * context is not yet started). This method can only be called once in * no context. * * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is called within an * object context or if it is called more than once in no context. */ JsonGenerator writeStartObject(); /** * Writes the JSON name/start object character pair in the current * object context. It starts a new child object context within which JSON * name/value pairs can be written to the object. * * @param name a name within the JSON name/object pair to be written * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context */ JsonGenerator writeStartObject(String name); /** * Writes the JSON name with a colon. It starts a field context, in which valid * options are writing a value, starting an object or an array. * * Writing value closes field context, if object or array is started after field name, * field context will be closed after object/array close. * * @param name name of json field * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context * * @since 1.1 */ JsonGenerator writeKey(String name); /** * Writes the JSON start array character. It starts a new child array * context within which JSON values can be written to the array. This * method is valid only in an array context, field context or in no context (when a * context is not yet started). This method can only be called once in * no context. * * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is called within an * object context or if called more than once in no context */ JsonGenerator writeStartArray(); /** * Writes the JSON name/start array character pair with in the current * object context. It starts a new child array context within which JSON * values can be written to the array. * * @param name a name within the JSON name/array pair to be written * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within * an object context */ JsonGenerator writeStartArray(String name); /** * Writes a JSON name/value pair in the current object context. * * @param name a name in the JSON name/value pair to be written in * current JSON object * @param value a value in the JSON name/value pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context */ JsonGenerator write(String name, JsonValue value); /** * Writes a JSON name/string value pair in the current object context. * The specified value is written as JSON string value. * * @param name a name in the JSON name/string pair to be written in * current JSON object * @param value a value in the JSON name/string pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context */ JsonGenerator write(String name, String value); /** * Writes a JSON name/number value pair in the current object context. * The specified value is written as a JSON number value. The string * {@code new BigDecimal(value).toString()} * is used as the text value for writing. * * @param name a name in the JSON name/number pair to be written in * current JSON object * @param value a value in the JSON name/number pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context. */ JsonGenerator write(String name, BigInteger value); /** * Writes a JSON name/number value pair in the current object context. * The specified value is written as a JSON number value. The specified * value's {@code toString()} is used as the text value for writing. * * @param name a name in the JSON name/number pair to be written in * current JSON object * @param value a value in the JSON name/number pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context. */ JsonGenerator write(String name, BigDecimal value); /** * Writes a JSON name/number value pair in the current object context. * The specified value is written as a JSON number value. The string * {@code new BigDecimal(value).toString()} is used as the text value * for writing. * * @param name a name in the JSON name/number pair to be written in * current JSON object * @param value a value in the JSON name/number pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context. */ JsonGenerator write(String name, int value); /** * Writes a JSON name/number value pair in the current object context. * The specified value is written as a JSON number value. The string * {@code new BigDecimal(value).toString()} is used as the text * value for writing. * * @param name a name in the JSON name/number pair to be written in * current JSON object * @param value a value in the JSON name/number pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context. */ JsonGenerator write(String name, long value); /** * Writes a JSON name/number value pair in the current object context. * The specified value is written as a JSON number value. The string * {@code BigDecimal.valueOf(double).toString()} * is used as the text value for writing. * * @param name a name in the JSON name/number pair to be written in * current JSON object * @param value a value in the JSON name/number pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws NumberFormatException if the value is Not-a-Number (NaN) or infinity. * @throws JsonGenerationException if this method is not called within an * object context */ JsonGenerator write(String name, double value); /** * Writes a JSON name/boolean value pair in the current object context. * If value is true, it writes the JSON {@code true} value, otherwise * it writes the JSON {@code false} value. * * @param name a name in the JSON name/boolean pair to be written in * current JSON object * @param value a value in the JSON name/boolean pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context. */ JsonGenerator write(String name, boolean value); /** * Writes a JSON name/null value pair in an current object context. * * @param name a name in the JSON name/null pair to be written in * current JSON object * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * object context */ JsonGenerator writeNull(String name); /** * Writes the end of the current context. If the current context is * an array context, this method writes the end-of-array character (']'). * If the current context is an object context, this method writes the * end-of-object character ('}'). After writing the end of the current * context, the parent context becomes the new current context. * If parent context is field context, it is closed. * * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is called in no context. */ JsonGenerator writeEnd(); /** * Writes the specified value as a JSON value within * the current array, field or root context. * * @param value a value to be written in current JSON array * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. */ JsonGenerator write(JsonValue value); /** * Writes the specified value as a JSON string value within * the current array, field or root context. * * @param value a value to be written in current JSON array * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. */ JsonGenerator write(String value); /** * Writes the specified value as a JSON number value within * the current array, field or root context. The specified value's {@code toString()} * is used as the the text value for writing. * * @param value a value to be written in current JSON array * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. * * @see jakarta.json.JsonNumber */ JsonGenerator write(BigDecimal value); /** * Writes the specified value as a JSON number value within * the current array, field or root context. The string {@code new BigDecimal(value).toString()} * is used as the text value for writing. * * @param value a value to be written in current JSON array * @return this generator. * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. * * @see jakarta.json.JsonNumber */ JsonGenerator write(BigInteger value); /** * Writes the specified value as a JSON number value within * the current array, field or root context. The string {@code new BigDecimal(value).toString()} * is used as the text value for writing. * * @param value a value to be written in current JSON array * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. */ JsonGenerator write(int value); /** * Writes the specified value as a JSON number value within * the current array, field or root context. The string {@code new BigDecimal(value).toString()} * is used as the text value for writing. * * @param value a value to be written in current JSON array * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. */ JsonGenerator write(long value); /** * Writes the specified value as a JSON number value within the current * array, field or root context. The string {@code BigDecimal.valueOf(value).toString()} * is used as the text value for writing. * * @param value a value to be written in current JSON array * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. * @throws NumberFormatException if the value is Not-a-Number (NaN) or infinity. */ JsonGenerator write(double value); /** * Writes a JSON true or false value within the current array, field or root context. * If value is true, this method writes the JSON {@code true} value, * otherwise it writes the JSON {@code false} value. * * @param value a {@code boolean} value * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. */ JsonGenerator write(boolean value); /** * Writes a JSON null value within the current array, field or root context. * * @return this generator * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if this method is not called within an * array, root or field context. */ JsonGenerator writeNull(); /** * Closes this generator and frees any resources associated with it. * This method closes the underlying output source. * * The underlying stream is closed only if complete JSON object is written. In case * of incomplete object JsonGenerationException is thrown and underlying stream is * not closed. * * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonGenerationException if an incomplete JSON is generated */ @Override void close(); /** * Flushes the underlying output source. If the generator has saved * any characters in a buffer, writes them immediately to the underlying * output source before flushing it. * * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) */ @Override void flush(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonGeneratorFactory.java000066400000000000000000000064331451447132700305520ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.util.Map; /** * Factory to create {@link JsonGenerator} instances. If a factory * instance is configured with some configuration, the configuration applies * to all generator instances created using that factory instance. * *

* The class {@link jakarta.json.Json Json} also provides methods to create * {@link JsonGenerator} instances, but using {@code JsonGeneratorFactory} is * preferred when creating multiple generator instances as shown in the * following example: * *

 * 
 * JsonGeneratorFactory factory = Json.createGeneratorFactory();
 * JsonGenerator generator1 = factory.createGenerator(...);
 * JsonGenerator generator2 = factory.createGenerator(...);
 * 
 * 
* *

All the methods in this class are safe for use by multiple concurrent * threads. */ public interface JsonGeneratorFactory { /** * Creates a JSON generator to write JSON text to a character stream. * The generator is configured with the factory configuration. * * @param writer i/o writer to which JSON is written * @return the created JSON generator */ JsonGenerator createGenerator(Writer writer); /** * Creates a JSON generator to write JSON text to a byte stream. Characters * written to the stream are encoded into bytes using UTF-8 encoding. * The generator is configured with the factory's configuration. * * @param out i/o stream to which JSON is written * @return the created JSON generator */ JsonGenerator createGenerator(OutputStream out); /** * Creates a JSON generator to write JSON text to a byte stream. Characters * written to the stream are encoded into bytes using the specified charset. * The generator is configured with the factory's configuration. * * @param out i/o stream to which JSON is written * @param charset a charset * @return the created JSON generator */ JsonGenerator createGenerator(OutputStream out, Charset charset); /** * Returns a read-only map of supported provider specific configuration * properties that are used to configure the JSON generators. * If there are any specified configuration properties that are not * supported by the provider, they won't be part of the returned map. * * @return a map of supported provider specific properties that are used * to configure the created generators. The map may be empty but not null */ Map getConfigInUse(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonLocation.java000066400000000000000000000045741451447132700270500ustar00rootroot00000000000000/* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; /** * Provides the location information of a JSON event in an input source. The * {@code JsonLocation} information can be used to identify incorrect JSON * or can be used by higher frameworks to know about the processing location. * *

All the information provided by a {@code JsonLocation} is optional. For * example, a provider may only report line numbers. Also, there may not be any * location information for an input source. For example, if a * {@code JsonParser} is created using * {@link jakarta.json.JsonArray JsonArray} input source, all the methods in * this class return -1. * @see JsonParser * @see JsonParsingException */ public interface JsonLocation { /** * Return the line number (starts with 1 for the first line) for the current JSON event in the input source. * * @return the line number (starts with 1 for the first line) or -1 if none is available */ long getLineNumber(); /** * Return the column number (starts with 1 for the first column) for the current JSON event in the input source. * * @return the column number (starts with 1 for the first column) or -1 if none is available */ long getColumnNumber(); /** * Return the stream offset into the input source this location * is pointing to. If the input source is a file or a byte stream then * this is the byte offset into that stream, but if the input source is * a character media then the offset is the character offset. * Returns -1 if there is no offset available. * * @return the offset of input source stream, or -1 if there is * no offset available */ long getStreamOffset(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonParser.java000066400000000000000000000452001451447132700265230ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import java.io.Closeable; import java.math.BigDecimal; import java.util.stream.Stream; import java.util.Map; import jakarta.json.JsonValue; import jakarta.json.JsonObject; import jakarta.json.JsonArray; /** * Provides forward, read-only access to JSON data in a streaming way. This * is the most efficient way for reading JSON data. * This is the only way to parse and process JSON data that are too big to be loaded in memory. *

The class * {@link jakarta.json.Json} contains methods to create parsers from input * sources ({@link java.io.InputStream} and {@link java.io.Reader}). * *

* The following example demonstrates how to create a parser from a string * that contains an empty JSON array: *

 * 
 * JsonParser parser = Json.createParser(new StringReader("[]"));
 * 
 * 
* *

* The class {@link JsonParserFactory} also contains methods to create * {@code JsonParser} instances. {@link JsonParserFactory} is preferred * when creating multiple parser instances. A sample usage is shown * in the following example: *

 * 
 * JsonParserFactory factory = Json.createParserFactory();
 * JsonParser parser1 = factory.createParser(...);
 * JsonParser parser2 = factory.createParser(...);
 * 
 * 
* *

* {@code JsonParser} parses JSON using the pull parsing programming model. * In this model the client code controls the thread and calls the method * {@code next()} to advance the parser to the next state after * processing each element. The parser can generate the following events: * {@code START_OBJECT}, {@code END_OBJECT}, {@code START_ARRAY}, * {@code END_ARRAY}, {@code KEY_NAME}, {@code VALUE_STRING}, * {@code VALUE_NUMBER}, {@code VALUE_TRUE}, {@code VALUE_FALSE}, * and {@code VALUE_NULL}. * *

* For example, for an empty JSON object ({ }), the parser generates the event * {@code START_OBJECT} with the first call to the method {@code next()} and the * event {@code END_OBJECT} with the second call to the method {@code next()}. * The following code demonstrates how to access these events: * *

 * 
 * Event event = parser.next(); // START_OBJECT
 * event = parser.next();       // END_OBJECT
 * 
 * 
* *

* For example, for the following JSON: *

 * {
 *   "firstName": "John", "lastName": "Smith", "age": 25,
 *   "phoneNumber": [
 *       { "type": "home", "number": "212 555-1234" },
 *       { "type": "fax", "number": "646 555-4567" }
 *    ]
 * }
 * 
* *

calls to the method {@code next()} result in parse events at the specified * locations below (marked in bold): * *

 * {START_OBJECT
 *   "firstName"KEY_NAME: "John"VALUE_STRING, "lastName"KEY_NAME: "Smith"VALUE_STRING, "age"KEY_NAME: 25VALUE_NUMBER,
 *   "phoneNumber"KEY_NAME : [START_ARRAY
 *       {START_OBJECT "type"KEY_NAME: "home"VALUE_STRING, "number"KEY_NAME: "212 555-1234"VALUE_STRING }END_OBJECT,
 *       {START_OBJECT "type"KEY_NAME: "fax"VALUE_STRING, "number"KEY_NAME: "646 555-4567"VALUE_STRING }END_OBJECT
 *    ]END_ARRAY
 * }END_OBJECT
 * 
* * The methods {@link #next()} and {@link #hasNext()} enable iteration over * parser events to process JSON data. {@code JsonParser} provides get methods * to obtain the value at the current state of the parser. For example, the * following code shows how to obtain the value "John" from the JSON above: * *
 * 
 * Event event = parser.next(); // START_OBJECT
 * event = parser.next();       // KEY_NAME
 * event = parser.next();       // VALUE_STRING
 * parser.getString();          // "John"
 * 
 * 
* * Starting in version 1.1, it is possible to build a partial JSON object * model from the stream, at the current parser position. * The methods {@link #getArray} and {@link #getObject} can be used to read in * a {@code JsonArray} or {@code JsonObject}. For example, the following code * shows how to obtain the phoneNumber in a JsonArray, from the JSON above: * *

 * while (parser.hasNext() {
 *     Event event = parser.next();
 *     if (event == JsonParser.Event.KEY_NAME ) {
 *         String key = parser.getString();
 *         event = parser.next();
 *         if (key.equals("phoneNumber") {
 *             JsonArray phones = parser.getArray();
 *         }
 *     }
 * }
 * 
* * The methods {@link #getArrayStream} and {@link #getObjectStream} can be used * to get a stream of the elements of a {@code JsonArray} or {@code JsonObject}. * For example, the following code shows another way to obtain John's phoneNumber * in a {@code JsonArray} : * *
{@code
 * Event event = parser.next(); // START_OBJECT
 * JsonArray phones = (JsonArray)
 *     parser.getObjectStream().filter(e->e.getKey().equals("phoneNumber"))
 *                             .map(e->e.getValue())
 *                             .findFirst()
 *                             .get();
 * }
* * The methods {@link #skipArray} and {@link #skipObject} can be used to * skip tokens and position the parser to {@code END_ARRAY} or * {@code END_OBJECT}. *

* {@code JsonParser} can be used to parse sequence of JSON values that are not * enclosed in a JSON array, e.g. { } { }. The following code demonstrates how * to parse such sequence. *


 * JsonParser parser = Json.createParser(...);
 * while (parser.hasNext) {
 *     parser.next(); // advance parser state
 *     JsonValue value = parser.getValue();
 * }
 * 
* * @see jakarta.json.Json * @see JsonParserFactory */ public interface JsonParser extends /*Auto*/Closeable { /** * An event from {@code JsonParser}. */ enum Event { /** * Start of a JSON array. The position of the parser is after '['. */ START_ARRAY, /** * Start of a JSON object. The position of the parser is after '{'. */ START_OBJECT, /** * Name in a name/value pair of a JSON object. The position of the parser * is after the key name. The method {@link #getString} returns the key * name. */ KEY_NAME, /** * String value in a JSON array or object. The position of the parser is * after the string value. The method {@link #getString} * returns the string value. */ VALUE_STRING, /** * Number value in a JSON array or object. The position of the parser is * after the number value. {@code JsonParser} provides the following * methods to access the number value: {@link #getInt}, * {@link #getLong}, and {@link #getBigDecimal}. */ VALUE_NUMBER, /** * {@code true} value in a JSON array or object. The position of the * parser is after the {@code true} value. */ VALUE_TRUE, /** * {@code false} value in a JSON array or object. The position of the * parser is after the {@code false} value. */ VALUE_FALSE, /** * {@code null} value in a JSON array or object. The position of the * parser is after the {@code null} value. */ VALUE_NULL, /** * End of a JSON object. The position of the parser is after '}'. */ END_OBJECT, /** * End of a JSON array. The position of the parser is after ']'. */ END_ARRAY } /** * Returns {@code true} if there are more parsing states. This method returns * {@code false} if the parser reaches the end of the JSON text. * * @return {@code true} if there are more parsing states. * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonParsingException if the parser encounters invalid JSON * when advancing to next state. */ boolean hasNext(); /** * Returns the event for the next parsing state. * * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws JsonParsingException if the parser encounters invalid JSON * when advancing to next state. * @throws java.util.NoSuchElementException if there are no more parsing * states. * @return the event for the next parsing state */ Event next(); /** * Returns the event for the current parsing state. * * @return the event for the current parsing state * * @since 2.1 */ default public Event currentEvent() { throw new UnsupportedOperationException(); } /** * Returns a {@code String} for the name in a name/value pair, * for a string value or a number value. This method should only be called * when the parser state is {@link Event#KEY_NAME}, {@link Event#VALUE_STRING}, * or {@link Event#VALUE_NUMBER}. * * @return a name when the parser state is {@link Event#KEY_NAME} * a string value when the parser state is {@link Event#VALUE_STRING} * a number value when the parser state is {@link Event#VALUE_NUMBER} * @throws IllegalStateException when the parser state is not * {@code KEY_NAME}, {@code VALUE_STRING}, or {@code VALUE_NUMBER} */ String getString(); /** * Returns true if the JSON number at the current parser state is a * integral number. A {@link BigDecimal} may be used to store the value * internally and this method semantics are defined using its * {@code scale()}. If the scale is zero, then it is considered integral * type. This integral type information can be used to invoke an * appropriate accessor method to obtain a numeric value as in the * following example: * *
     * 
     * JsonParser parser = ...
     * if (parser.isIntegralNumber()) {
     *     parser.getInt();     // or other methods to get integral value
     * } else {
     *     parser.getBigDecimal();
     * }
     * 
     * 
* * @return true if this number is a integral number, otherwise false * @throws IllegalStateException when the parser state is not * {@code VALUE_NUMBER} */ boolean isIntegralNumber(); /** * Returns a JSON number as an integer. The returned value is equal * to {@code new BigDecimal(getString()).intValue()}. Note that * this conversion can lose information about the overall magnitude * and precision of the number value as well as return a result with * the opposite sign. This method should only be called when the parser * state is {@link Event#VALUE_NUMBER}. * * @return an integer for a JSON number * @throws IllegalStateException when the parser state is not * {@code VALUE_NUMBER} * @see java.math.BigDecimal#intValue() */ int getInt(); /** * Returns a JSON number as a long. The returned value is equal * to {@code new BigDecimal(getString()).longValue()}. Note that this * conversion can lose information about the overall magnitude and * precision of the number value as well as return a result with * the opposite sign. This method is only called when the parser state is * {@link Event#VALUE_NUMBER}. * * @return a long for a JSON number * @throws IllegalStateException when the parser state is not * {@code VALUE_NUMBER} * @see java.math.BigDecimal#longValue() */ long getLong(); /** * Returns a JSON number as a {@code BigDecimal}. The {@code BigDecimal} * is created using {@code new BigDecimal(getString())}. This * method should only called when the parser state is * {@link Event#VALUE_NUMBER}. * * @return a {@code BigDecimal} for a JSON number * @throws IllegalStateException when the parser state is not * {@code VALUE_NUMBER} */ BigDecimal getBigDecimal(); /** * Return the location that corresponds to the parser's current state in * the JSON input source. The location information is only valid in the * current parser state (or until the parser is advanced to a next state). * * @return a non-null location corresponding to the current parser state * in JSON input source */ JsonLocation getLocation(); /** * Returns a {@code JsonObject} and advances the parser to the * corresponding {@code END_OBJECT}. * * @return the {@code JsonObject} at the current parser position * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws IllegalStateException when the parser state is not * {@code START_OBJECT} * @throws JsonParsingException if the parser encounters invalid JSON * when advancing to next state. * @throws java.util.NoSuchElementException if there are no more parsing * states. * * @since 1.1 */ default public JsonObject getObject() { throw new UnsupportedOperationException(); } /** * Returns a {@code JsonValue} at the current parser position. * If the parser state is {@code START_ARRAY}, the behavior is * the same as {@link #getArray}. If the parser state is * {@code START_OBJECT}, the behavior is the same as * {@link #getObject}. For all other cases, if applicable, the JSON value is * read and returned. * * @return the {@code JsonValue} at the current parser position. * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws IllegalStateException when the parser state is * {@code END_OBJECT} or {@code END_ARRAY} * @throws JsonParsingException if the parser encounters invalid JSON * when advancing to next state. * @throws java.util.NoSuchElementException if there are no more parsing * states. * * @since 1.1 */ default public JsonValue getValue() { throw new UnsupportedOperationException(); } /** * Returns a {@code JsonArray} and advance the parser to the * the corresponding {@code END_ARRAY}. * * @return the {@code JsonArray} at the current parser position * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) * @throws IllegalStateException when the parser state is not * {@code START_ARRAY} * @throws JsonParsingException if the parser encounters invalid JSON * when advancing to next state. * @throws java.util.NoSuchElementException if there are no more parsing * states. * * @since 1.1 */ default public JsonArray getArray() { throw new UnsupportedOperationException(); } /** * Returns a stream of the {@code JsonArray} elements. * The parser state must be {@code START_ARRAY}. * The elements are read lazily, on an as-needed basis, as * required by the stream operations. * If the stream operations do not consume * all of the array elements, {@link skipArray} can be used to * skip the unprocessed array elements. * * @return a stream of elements of the {@code JsonArray} * * @throws IllegalStateException when the parser state is not * {@code START_ARRAY} * * @since 1.1 */ default public Stream getArrayStream() { throw new UnsupportedOperationException(); } /** * Returns a stream of the {@code JsonObject}'s * name/value pairs. The parser state must be {@code START_OBJECT}. * The name/value pairs are read lazily, on an as-needed basis, as * required by the stream operations. * If the stream operations do not consume * all of the object's name/value pairs, {@link skipObject} can be * used to skip the unprocessed elements. * * @return a stream of name/value pairs of the {@code JsonObject} * * @throws IllegalStateException when the parser state is not * {@code START_OBJECT} * * @since 1.1 */ default public Stream> getObjectStream() { throw new UnsupportedOperationException(); } /** * Returns a stream of {@code JsonValue} from a sequence of * JSON values. The values are read lazily, on an as-needed basis, * as needed by the stream operations. * * @return a Stream of {@code JsonValue} * * @throws IllegalStateException if the parser is in an array or object. * * @since 1.1 */ default public Stream getValueStream() { throw new UnsupportedOperationException(); } /** * Advance the parser to {@code END_ARRAY}. * If the parser is in array context, i.e. it has previously * encountered a {@code START_ARRAY} without encountering the * corresponding {@code END_ARRAY}, the parser is advanced to * the corresponding {@code END_ARRAY}. * If the parser is not in any array context, nothing happens. * * @since 1.1 */ default public void skipArray() { throw new UnsupportedOperationException(); } /** * Advance the parser to {@code END_OBJECT}. * If the parser is in object context, i.e. it has previously * encountered a {@code START_OBJECT} without encountering the * corresponding {@code END_OBJECT}, the parser is advanced to * the corresponding {@code END_OBJECT}. * If the parser is not in any object context, nothing happens. * * @since 1.1 */ default public void skipObject() { throw new UnsupportedOperationException(); } /** * Closes this parser and frees any resources associated with the * parser. This method closes the underlying input source. * * @throws jakarta.json.JsonException if an i/o error occurs (IOException * would be cause of JsonException) */ @Override void close(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonParserFactory.java000066400000000000000000000072101451447132700300520ustar00rootroot00000000000000/* * Copyright (c) 2011, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import java.io.InputStream; import java.io.Reader; import java.nio.charset.Charset; import java.util.Map; /** * Factory for creating {@link JsonParser} instances. If a factory * instance is configured with a configuration, the configuration applies * to all parser instances created using that factory instance. * *

* The class {@link jakarta.json.Json Json} also provides methods to create * {@link JsonParser} instances, but using {@code JsonParserFactory} is * preferred when creating multiple parser instances as shown in the following * example: * *

 * 
 * JsonParserFactory factory = Json.createParserFactory();
 * JsonParser parser1 = factory.createParser(...);
 * JsonParser parser2 = factory.createParser(...);
 * 
 * 
* *

All the methods in this class are safe for use by multiple concurrent * threads. */ public interface JsonParserFactory { /** * Creates a JSON parser from a character stream. * * @param reader a i/o reader from which JSON is to be read * @return the created JSON parser */ JsonParser createParser(Reader reader); /** * Creates a JSON parser from the specified byte stream. * The character encoding of the stream is determined * as specified in RFC 7159. * * @param in i/o stream from which JSON is to be read * @return the created JSON parser * @throws jakarta.json.JsonException if encoding cannot be determined * or i/o error (IOException would be cause of JsonException) */ JsonParser createParser(InputStream in); /** * Creates a JSON parser from the specified byte stream. * The bytes of the stream are decoded to characters using the * specified charset. * * @param in i/o stream from which JSON is to be read * @param charset a charset * @return the created JSON parser */ JsonParser createParser(InputStream in, Charset charset); /** * Creates a JSON parser from the specified JSON object. * * @param obj a JSON object * @return the created JSON parser */ JsonParser createParser(JsonObject obj); /** * Creates a JSON parser from the specified JSON array. * * @param array a JSON array * @return the created JSON parser */ JsonParser createParser(JsonArray array); /** * Returns a read-only map of supported provider specific configuration * properties that are used to configure the JSON parsers. * If there are any specified configuration properties that are not * supported by the provider, they won't be part of the returned map. * * @return a map of supported provider specific properties that are used * to configure the created parsers. The map may be empty but not null */ Map getConfigInUse(); } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/JsonParsingException.java000066400000000000000000000053541451447132700305570ustar00rootroot00000000000000/* * Copyright (c) 2012, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package jakarta.json.stream; import jakarta.json.JsonException; /** * {@code JsonParsingException} is used when an incorrect JSON is * being parsed. */ public class JsonParsingException extends JsonException { /** for serialization */ private static final long serialVersionUID = 9073566598484238797L; /** * The location of the incorrect JSON. */ private transient final JsonLocation location; /** * Constructs a new runtime exception with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @param location the location of the incorrect JSON */ public JsonParsingException(String message, JsonLocation location) { super(message); this.location = location; } /** * Constructs a new runtime exception with the specified detail message and * cause.

Note that the detail message associated with * {@code cause} is not automatically incorporated in * this runtime exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @param location the location of the incorrect JSON */ public JsonParsingException(String message, Throwable cause, JsonLocation location) { super(message, cause); this.location = location; } /** * Return the location of the incorrect JSON. * * @return the non-null location of the incorrect JSON */ public JsonLocation getLocation() { return location; } } jsonp-api-2.1.3-RELEASE/api/src/main/java/jakarta/json/stream/package-info.java000066400000000000000000000035601451447132700267640ustar00rootroot00000000000000/* * Copyright (c) 2012, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /** * Provides a streaming API to parse and generate * JSON. * *

* The streaming API consists of the interfaces * {@link jakarta.json.stream.JsonParser} and * {@link jakarta.json.stream.JsonGenerator}. The interface {@code JsonParser} * contains methods to parse JSON in a streaming way. The interface * {@code JsonGenerator} contains methods to write JSON to an output source * in a streaming way. * *

* {@code JsonParser} provides forward, read-only access to JSON data using the * pull parsing programming model. In this model the application code controls * the thread and calls methods in the parser interface to move the parser * forward or to obtain JSON data from the current state of the parser. * *

* {@code JsonGenerator} provides methods to write JSON to an output source. * The generator writes name/value pairs in JSON objects and values in JSON * arrays. * *

* The streaming API is a low-level API designed to process large amounts of * JSON data efficiently. Other JSON frameworks (such as JSON binding) can be * implemented using this API. * * @since JSON Processing 1.0 */ package jakarta.json.stream; jsonp-api-2.1.3-RELEASE/api/src/main/java/module-info.java000066400000000000000000000016371451447132700230000ustar00rootroot00000000000000/* * Copyright (c) 2016, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /** * Jakarta JSON Processing API. */ module jakarta.json { requires java.logging; exports jakarta.json; exports jakarta.json.spi; exports jakarta.json.stream; uses jakarta.json.spi.JsonProvider; } jsonp-api-2.1.3-RELEASE/api/src/main/javadoc/000077500000000000000000000000001451447132700203765ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/javadoc/doc-files/000077500000000000000000000000001451447132700222435ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/api/src/main/javadoc/doc-files/speclicense.html000066400000000000000000000062621451447132700254340ustar00rootroot00000000000000 Eclipse Foundation Specification License - v1.0

Eclipse Foundation Specification License - v1.0

By using and/or copying this document, or the Eclipse Foundation document from which this statement is linked, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions:

Permission to copy, and distribute the contents of this document, or the Eclipse Foundation document from which this statement is linked, in any medium for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the document, or portions thereof, that you use:

  • link or URL to the original Eclipse Foundation document.
  • All existing copyright notices, or if one does not exist, a notice (hypertext is preferred, but a textual representation is permitted) of the form: "Copyright © [$date-of-document] “Eclipse Foundation, Inc. <<url to this license>> "

Inclusion of the full text of this NOTICE must be provided. We request that authorship attribution be provided in any software, documents, or other items or products that you create pursuant to the implementation of the contents of this document, or any portion thereof.

No right to create modifications or derivatives of Eclipse Foundation documents is granted pursuant to this license, except anyone may prepare and distribute derivative works and portions of this document in software that implements the specification, in supporting materials accompanying such software, and in documentation of such software, PROVIDED that all such works include the notice below. HOWEVER, the publication of derivative works of this document for use as a technical specification is expressly prohibited.

The notice is:

"Copyright © 2018 Eclipse Foundation. This software or document includes material copied from or derived from [title and URI of the Eclipse Foundation specification document]."

Disclaimers

THIS DOCUMENT IS PROVIDED "AS IS," AND THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.

THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.

The name and trademarks of the copyright holders or the Eclipse Foundation may NOT be used in advertising or publicity pertaining to this document or its contents without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.

jsonp-api-2.1.3-RELEASE/api/src/main/javadoc/overview.html000066400000000000000000000130631451447132700231350ustar00rootroot00000000000000 Jakarta JSON Processing provides portable APIs to parse, generate, transform, and query JSON using the streaming API or the object model API.

The Streaming API provides a way to parsing and generation of JSON in a streaming fashion. It hands over parsing and generation control to the programmer. The streaming API provides an event-based parser and allows an application developer to ask for the next event rather than handling the event in a callback. This gives a developer more procedural control over the processing of the JSON. Application code can process or discard the parser event, and ask for the next event(pull the event). The streaming model is adequate for local processing where random access of other parts of the data is not required. Similarly, the streaming API provides a way to generate well-formed JSON to a stream by writing one event at a time.

The object model API creates a random access tree-like structure that represents the JSON data in memory. The tree can then be navigated and queried. This programming model is the most flexible and enables processing that requires random access to the complete contents of the tree. However, it is often not as efficient as the streaming model and requires more memory. The object model generates JSON output by navigating the entire tree at once.

The Streaming API

The streaming API is similar to the StAX API for XML and consists of the interfaces {@link jakarta.json.stream.JsonParser} and {@link jakarta.json.stream.JsonGenerator}. {@code JsonParser} contains methods to parse JSON data using the streaming model. {@code JsonGenerator} contains methods to write JSON data to an ouptut source.

{@code JsonParser} provides forward, read-only access to JSON data using the pull parsing programming model. In this model the application code controls the thread and calls methods in the parser interface to move the parser forward or to obtain JSON data from the current state of the parser. Refer to this example for more details.

{@code JsonGenerator} provides methods to write JSON to a stream. The generator writes name/value pairs in JSON objects and values in JSON arrays. Refer to this example for more details.

The streaming API is a low-level API designed to process large amounts of JSON data efficiently. Other JSON frameworks (such as JSON binding) can be implemented using this API.

The Object Model API

The object model API is similar to the DOM API for XML. It is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures are represented as object models using the Java types {@link jakarta.json.JsonObject} and {@link jakarta.json.JsonArray}. {@code JsonObject} provides a {@link java.util.Map} view to access the unordered collection of zero or more name/value pairs from the model. Similarly, {@code JsonArray} provides a {@link java.util.List} view to access the ordered sequence of zero or more values from the model.

The object model API uses builder patterns to create these object models. Application code can use the interface {@link jakarta.json.JsonObjectBuilder} to create models that represent JSON objects. The resulting model is of type {@code JsonObject}. Refer to this example for more details. Application code can use the interface {@link jakarta.json.JsonArrayBuilder} to create models that represent JSON arrays. The resulting model is of type {@code JsonArray}. Refer to this example for more details.

These object models can also be created from an input source (such as {@link java.io.InputStream} or {@link java.io.Reader}) using the interface {@link jakarta.json.JsonReader}. This example shows how to read and create an empty {@code JsonArray} model using the interface {@code JsonReader}. Similarly, these object models can be written to an output source (such as {@link java.io.OutputStream} or {@link java.io.Writer}) using the class {@link jakarta.json.JsonWriter}. This example shows how to write an empty {@code JsonObject} model using the interface {@code JsonWriter}.

JSON Pointer, JSON Patch, and JSON Merge Patch

Jakarta JSON Processing supports the latest standard on JSON Pointer, JSON Patch, and JSON Merge Patch. jsonp-api-2.1.3-RELEASE/etc/000077500000000000000000000000001451447132700152565ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/etc/copyright-exclude000066400000000000000000000002351451447132700206400ustar00rootroot00000000000000.json .md speclicense.html MANIFEST.MF /META-INF/services/ /etc/config/copyright-exclude /etc/config/copyright.txt /bundles/ri/src/main/resources/README.txt jsonp-api-2.1.3-RELEASE/etc/copyright.txt000066400000000000000000000012741451447132700200330ustar00rootroot00000000000000/* * Copyright (c) YYYY Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ jsonp-api-2.1.3-RELEASE/etc/spotbugs-exclude.xml000066400000000000000000000005641451447132700213020ustar00rootroot00000000000000 jsonp-api-2.1.3-RELEASE/spec/000077500000000000000000000000001451447132700154355ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/.gitignore000066400000000000000000000000151451447132700174210ustar00rootroot00000000000000.m2/ target/ jsonp-api-2.1.3-RELEASE/spec/LICENSE000066400000000000000000000335671451447132700164600ustar00rootroot00000000000000Eclipse Public License - v 2.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution "originates" from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works. "Contributor" means any person or entity that Distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions Distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors. "Derivative Works" shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. "Modified Works" shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof. "Distribute" means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy. "Source Code" means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files. "Secondary License" means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3). 3. REQUIREMENTS 3.1 If a Contributor Distributes the Program in any form, then: a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license: i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3. 3.2 When the Program is Distributed as Source Code: a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and b) a copy of this Agreement must be included with each copy of the Program. 3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability ("notices") contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement. Exhibit A - Form of Secondary Licenses Notice "This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}." Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. jsonp-api-2.1.3-RELEASE/spec/README.md000066400000000000000000000010021451447132700167050ustar00rootroot00000000000000Jakarta JSON Processing Specification ====================================== This project generates the Jakarta JSON Processing Specification. Building -------- Prerequisites: * JDK8+ * Maven 3.0.3+ Run the full build with DRAFT status: `mvn install` Run the full build with custom status (ex. "Final Release"): `mvn install -Dstatus=“Final Release”` Locate the html files: - `target/generated-docs/jsonp-spec-.html` Locate the PDF files: - `target/generated-docs/jsonp-spec-.pdf` jsonp-api-2.1.3-RELEASE/spec/pom.xml000066400000000000000000000212031451447132700167500ustar00rootroot00000000000000 org.eclipse.ee4j project 1.0.6 4.0.0 jakarta.json jakarta.json-spec pom 2.0-SNAPSHOT Jakarta JSON Processing Specification ${project.build.directory}/staging true 2.0.0 1.5.3 DRAFT MMMM dd, yyyy ${maven.build.timestamp} scm:git:git@github.com:eclipse-ee4j/jsonp.git scm:git:git@github.com:eclipse-ee4j/jsonp.git https://github.com/eclipse-ee4j/jsonp HEAD scm:git:git@github.com:eclipse-ee4j/jsonp.git package org.apache.maven.plugins maven-enforcer-plugin 1.4.1 enforce-versions enforce [1.8.0,) You need JDK8 or higher org.asciidoctor asciidoctor-maven-plugin ${asciidoctor.maven.plugin.version} org.asciidoctor asciidoctorj-pdf ${asciidoctorj.pdf.version} asciidoc-to-html generate-resources process-asciidoc html5 ${project.build.directory}/generated-docs/jsonp-spec-${project.version}.html book ${status} font left font true - true asciidoc-to-pdf generate-resources process-asciidoc pdf ${project.build.directory}/generated-docs/jsonp-spec-${project.version}.pdf ${project.basedir}/src/theme jakartaee book ${status} font font true - true true jsonp-spec.adoc coderay ${project.version} ${status} ${revisiondate} org.apache.maven.plugins maven-release-plugin 2.5.2 forked-path false ${release.arguments} org.apache.maven.scm maven-scm-provider-gitexe 1.9.4 org.apache.maven.plugins maven-assembly-plugin 3.3.0 false package single false ${project.basedir}/src/assembly/assembly.xml jsonp-api-2.1.3-RELEASE/spec/src/000077500000000000000000000000001451447132700162245ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/src/assembly/000077500000000000000000000000001451447132700200435ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/src/assembly/assembly.xml000066400000000000000000000020621451447132700224040ustar00rootroot00000000000000 spec zip jsonp-spec target/generated-docs jsonp-api-2.1.3-RELEASE/spec/src/main/000077500000000000000000000000001451447132700171505ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/src/main/asciidoc/000077500000000000000000000000001451447132700207265ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/src/main/asciidoc/images/000077500000000000000000000000001451447132700221735ustar00rootroot00000000000000jakarta_ee_logo_schooner_color_stacked_default.png000066400000000000000000001336201451447132700342350ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/src/main/asciidoc/imagesPNG  IHDRX@ pHYs.#.#x?v IDATxMrWS26@N;@;w`Z9 ;螙 i0tťr(TyH:m˘}T9 p_s&1,GSh-#qZwX.!0r/aϻ(ayX.CYo @]ic+H M]!aKxG<0sv(_{?=0R<;o` !\??Q`N(4aFH9hcFy'aNˍ7'02<Bo:aN4Q>0><@w0+M]^aP_3#"14uB؞cq(ߞ2 0"<(mZ?Ȕ0GȀԥS0<CS[![ 0#![,)ʷA7hrcIQ>81!ktQgUM]~(ay8D3q<0.$0# Qu.`yF˵v(RS.ʷ'e2 vFQ>0|<V 0p0:]h杽 >N0:M]~qNð JS!272 Fo:1&0 M]$aM`(ӣy˵ ><v(ʯ{:5%0XݩFX.aA|{RJO0P<s(_wayhQ>xK`P !wrjH`0`ayˍE >0g<Eܤl`yz^ClOo yM]gF(BX]g#;M]^I蕦.B#yaEgHOG_BqdF)aD kM]~=(yal5uBʆya,uQt%̉0@v!Y7`ye{m˶l` yEª>pB<Yhr;)/ʿ0<uQ~#o%@$u(_Zf0@j[95 LSmLHLXyakrC?=+yMD3XQtjzN`)lG4Sy;!U>=0z< ]"Ϗs< Za[+azN`!(ߞfs>$(bv?zJ`ʩy1a-S](azL`nZ_ B ES!Ls)8.6ɥqbzLT!/ݕ}_ak경ReC<'Eª &6 plM]u'Et< =%p,]qyr<0L-9W@O ǖ(c04uFL+`zF(ˤy!ajrCձH(ۄ%C ( 7>#ah경|dW!a?Nadwm>]SWE~v0KM]עl#Cw\K<0@{MF-Q>a`ĺ(˯^[oyjrSc00BM]nazB.߶Aq<00"M]ɉya`$lOUo 91="@wB=HW>a`ງAEaGyGCPfǃwe>kK.6f"COE[::<00 M]~)ʏ0=! DS!osy a`(.GMz¦=0=!XwB8zW> aN(VfGJ`$"&= ula~,SS[U)\^!;]ͫ|PazFWkbrAmQ>~dF7(Ӄ+ XS[GyCQy aE_yb:#$嗢<=o@yEm5'e7co@yu({dd(0@6;鹦.EyzB~yl׹(39{yIo2lY,MȦ#2E>8 ord /<KEy2(H aU>'LD`(?G63 w(ʏaz@`abU8ʓmQ6dF`!(3&.DIr#0wvJ;.{pUꐱGyjKQнdB`n(ߞb̈́%j}p3?5dD`.Ey׷D]0YMQ\aSUM-V 2"p*;ޡ(ax3jAFyN,Vņ(OJM]EyDD(>o|{R-'<&}8=8 GyȈ0Īh)4#cScqo|{R-0v<v(^-VE{5ئ($.=8 (VUQ>/*n;z<ĪhI QsJ <tQ#$Ey"ʓTSv<@ĪI-K&.{p@X_pc_˫<0c*G6CRi}px[z$.{pz.@b<@Ū!ʓQG =b:irKz$.{pNHXk<5u(#(?7%l*&dPw7tQރ0<@a`ɺ(>o颼 a`bUlUQ$VE{M*M]o0]&tQރa`bUɀ((Vzwu$($.{p͚I@z<ĪXI˯Ey s&ʓ. ȏ00GIL Mj(y$VE?3ORi경;z o<tQ#$Eyo@KQ\Nʋ<)Īh II+ P=I2GyUiv$%@EylTSmycA=8 =%QQd߄y#袼G6IF')QCxX[<)5uپmi 0 <[tQ}$EyobS'%QX  !.Dy`΄yȀ0.{dd(a(aXd@:*ֻC .Dy6a(Mꢼ`y`bU( &ʓ. aCQ}$Eym QGF)VEu'.׻##EylLm#%KQ00FolTDy XtQ#a@/Vź(Oj< CE&ٽGq:_K0 ١(>oi|r{ż-%@z<0H*G6DyRj~ykrg0 N=IRçlx0 (O^F[:<04<)~IMy`0bUw߲QRi݇KD!VŦ(OJ+lދUB&Ifք??ykLXy("Ifքo܍#/ @oŪ\'?w}ə, }KybUlf)ba2 Eªޣf(0J5Qf?Ay0¡(H[p<ۢ<)5{/}(? 0Au"8LN/ @ֺ(˖HwNCl يU(OR< @bUli?Y0O<.߶|?l @VbUvOO:x0d;6BJ{vty0ty J国!<\¶(OJ/~e(ߞb<}>=|`)y CQ-('+S ~#)maQïgh7<D-'6}$;0&m K'ʓQ>ƅȈ0U!ʓԬ ~"tQ̬ >YG8?`)bU|.ʓQ?⇍UB2iR=x$d aX.VMTf6{/Dy`Vn!<0*6{I(?Y9aXXk!mQϧ}5&ka.ʷ'寙.Q~y r#-ʓRߢ<8 <0W*BMTt?2?3ȇ0Mo(Qi1]SU(OR_zLȅ0ZW&I2m9KxSmS$.˖F=|z/ \c#9寙τy6EyR ߍ!b+pˤHwNɥ\$rΞ-@>yDyR=C97U!ʓԬ Q "EۦC2m0kV{3Nɹ_2#sQ(.} 3@NyObULf"0;!~_B=m^*Ȍ0(OjCsc~ahZa['"i1 IDAT0r]oO_,Hnə >O2#ۢ<)5{/=(vՏ24; 7<LWN2&̾iwQMy.߶s5wQ,̙ >0r>ȑ0#(Ojd4Q >0r 0*CvMJ{vtKNNaծIދќi2S~!a,VZwR^'OF./| W@y.ʷ'14OOG{~0p0t(__Ri]3| dHaI)Nè|{͙22߭ &tQ~'{5=7Ypb2'䠍 'a?Vnqb2'ŪX !l<}>c"=ȟ0 E53&6<>oKG@8-= $%/de1}_yXX[<)~I%W ;`κ(\IwNC,ay&g;wNG9U)ʓR?-ʻf&>2/ ʉya$VF $Yf+'l`(,Ifքo܍-!.kYyljyaN)V QD 81y8X!m3$ٽG|bs\&y8.ʷ]| I Q>35=[~8Xk<~}&arf3<0$ʓihϯ\Gdy aPfnFك- > ,81=!l5 |Ξ<ܷa(VE?3/Rp?O- ?a;<0GE[fE*/݇죱?CwU(OR&|3Q>O; ,xzDUBƌHfͪ%i0ï#<AotQ>\Gdya^#VzalHGODM.^h3c <n]B2{v㿦@=7 ypbzDCDyrFf=1 ܼya:*B[<)5OOE;gdgy#ʷ'寙Q~y 3s57 aQUqC'._zf#<0hĪX!l8)=br{xzH`(BXqRi|BK}@Xk<<~"scazH`Dyr<}>m>Ly +70`lT(?{ > ϬI`ȶDyRQ~]i ~ )VE?]Rp?O-`&/|0Y桧ylT^F!FjcBO J/Ey5mU8ypbzJ`0bUlQi?Uہ@y)aAm$.˖0ls <ܼgO<b]'=Gr_7ZwlfM?qgdïc<u(ʯ"Q{L>t3 C R–(OJ/~Gï@A1a|kG*ç LVaȃc<"ʓQ1>g ,<[yGMQt?$ZH]\=3Y5@ FN[6F*m?pb` 49s<bS'CQ6#6x飱Ȃklyb#M̬ ~"36YpbzN k]mK$3k?O,a;?c azN [*>I- rΞM@ d)VzavHiv(&?lLȀayEªJ国<\iر?aĪXImQpL81  Q4OO=_LΞ3 ~¡(FH[;9XyGŶ(OJ_ FWX 0@r*BmTt?S M&zsȁ0<IuQ-(4ɴQwC,#2!@,]o7w\oJ@~Xyg"`y*Vź(OjD&^4, NÀ,MwLf'QM.^Ȱ 0 <Kq(ʯ8Q{2H ~8X!-$كǢā _NObUEyRj~y(O KkZ]?^1Ri>>&Gd‰y8aEk&B*/-&>:0x Vnay~)ʓRQ&> ȁ(# О !2 Ri݇S G~00<ȉ{Q%tr@ya`bUl$5k6'dU6{ۍ:}?$:X-R,G2etzwVojv@ >=V@ պ) HP`IFC.Y./vU͍rhER1fr+?ǀhпzgb9` @E>Qc$!;pM p 400EBXwbܾ/ʓ༅)p 40 U/Ob; n7$#۷mpbBh:)5QdoZ [y{"y(: <1 < <+zVDrU/Oʟkb)}@7 @(OLÍG_$=aM6@yha`JvL,Eo+ n1R<Է y*ha`JUQKBQ8-OG޵ ,EBEuV'b/S/$560<):3!+ ap޺(OffkO@ yha`TQ`W[Ö@겿ʒ0 #LZ剭ޚ(O]d, @坴"%tR!-)540Psۢ]K>/]@5VtZ! <1 oԍ偄81 $Tr! < W7|cq<+ya<<@ mX(?}ԒD8- %ӊ(OLEo+ԖtP<@V?7b)|ݞPW"CC 5REvF,FpZr<C 5QtZgDy CMQs<yy"2_9K/C']勭aˠ/$DVtZK!svDLEyD\r<40*ʗ'\B4ÍGD3)$ܡ5 <-a`(_~{߼eaoC4Jv+\ l[?eRF,}56w"S <ƞl^R;y1*:2lRF= 3$`3owy;y1i%o|Q8-O#eGq<Q <Qп~oS 00bU?oDSFw`8g 4U5<y剮Ved١#p%owoZ4a`DNk)p<5QB:z8-<00U/?x:h7V׋z?e{6~ @/<0N(Olenq ^Q\̐X(?}e$56s N'*QRv$‰yไyWPtZ+<10rc)7mxa`(܈kw{([|W6wO)pZx!a`N(OLVIioY5 +0CEu&"0 [3F$`3ow/["<TQY`W[Öϖ}])` /QtZ&Kdy/_x)aNkɩ'bX%Ckf$׎K QEӜKDyxf$RnX2<3ּ(Ol{뛢v@N(OLۢ+l 9Rb @tEu&k 0 ~5Qs [y{2q(f0 w֋3 Nc%'j0,7<+jg ݋L0Ei !MYEA²- N%#WE&K4U/-D a(aZ剭5QҗZ 36v)owo0I<02Uw7'Q n_/?z5 pZ8amQ~DÍGNC);{h@ty+'櫓F< (~{`]@.X0*ʗ'O$ < >kPٻ;.-1+I(>ˀycZҀekbqN'_{M+ny ax%EU~9mzRFP-%m?@]+:s<1mL6֗afڀ> [b]):3!_ a?PO'H@T<cU?obD3;V%@ );8os@lv-1 ')pZEK֒06}_ˎC |b n7Pcف_f{Z!y{؄y๊Nk^'k<_1oC)pZH0<(O yPwYˏg@d壯,H0mQK y0#j0,7 `c M \nX<P/̕X(?xuZ ( cg|yRK`f>\ <ѭ=iND5x(@ZNkE'7Y0*"+O˯X)U?m.RFPN#<`:+S偑O,:-xn0پ7W nyhmQK^1] M x>aY剩Dy`"t< 4FiQc'<ٹݰh*ʟmby텢pZ,y^ij0 6Ey`ܜ"iyjU?oDSFw`8g 89-Dv+owW,`gy(OtU/-7< <S贖oIl߯$d9-Dt)ow/X L*_ !:h7V׋zGl0TIA&";td5X>݋;<Sʟ_iaO&)brZL*ʗ'uN(Q~p> &i={y{vO`ZD%18-DB8gFNkE'_LR~C偈(|( kw{(&'{}afЁnIxuNP[EuN'b/QDy 3zyj= uQ,ߛ3x Ky{^0@TQ`W[ÖLZ~b1sZiyH'6Qfvv3?v‹@,ݛyj贖Bl7VEy D " !5|*ʗwYSh(?x$qg-?z̻@,gvwF#+(HZi͇n49\{få [y{FljyVEy'jaOb*y`Ąy-ʟ%b)}WGQ" `yR"SU/@l١#<$(K C<ov0@r(fqviy {ٞp+pc\!- ˟˻/k߹ن5E(OTa_c@\Yˏ" y(dEQ-$haq e΍(!S+.єQby ׏L`|y只w"%3mDy偔nX~M`|yU/Oo&SkET ?֊zGlHA^~w.~\MC YC8?_LpB}Vcݦρ($kfg!۳ׂI'M arYyrIb[i-UOcs n7@m'>$?R _-#ט(O Dy iyO~70i_'0\ y&R~di]YX\&zB}zFLe9-İ>$Bv-m^DWUB^( teyo~σ@ݳaxe5E Q{RxTh+ydiVm^D0 Epn9ow/<@Zy`$mLI\ xPpa_^l7}@< D##T]osj&ԉz>AB}@df>\:bgvw#ciu~Zd[~zZUOҗe_Ϝ7n˼ݽ`i恱㰻%׀P?7Vׇj@$_'.a3MP*׀P_?pP|"q @ D-,.RzB$ԧMO}MP|"q @M9=\B}8Dyv< QR4 @4NϿP8~V_u( LK3|z恨>qBhUQiy>< q)ow?2{$8=J< UߨTꗪ?(ԕ_\aPC< _PӚDP,a_Vl=Jv;L+ljHῢz?ܯ E7?ff $WԔ0$iaqdaC##'Nn@-ﵾɏk{Ƅy i ˟Ֆb{|gOLBp(ϞK?0i1aHRuz5uB}b9ԋ@!Ir @ @m,,.A~mc#'nZBჇzj)ZL+l0r/x6 >qu {%Kؽ٥y_ԛ0|uǶPC(-/v?aaسN' MHjR Wп ek3. ya'aؤm>u^OLP_B^( zʲgNl^ &y{0^uY&OO$B(L7<0I2<05?Nϻڦč<?oBQY@}gm6$WF.`TYX\>BjZZ~0 w֋ᆎ3?iN`9ow/8t恩|6SҶPHbvEy`JO|'I]~jGmP0 7֊Gᡦ ٥ͅY&J5+l0L5WL=>a V?{B=P+3.༥u#FpMc ꁺ>Cۼ=kK6tiۃ̏'Dj!ϿKyL7ahW4ޕmPH-R4p&\ƿjӶxB}„z ̇K&y{04*лچ' D/vshahj> IOPS^~>C&Vu7Bڦh,x'rl6 IDAT$s^4q* gC1vS'+ɲgNl^&y{ִEfaqqŽ">aB={oc'Ty`R.G <tHХmCĸ%0{/z !.Wc0OV{%0yT= B,!>QB=+lr<$GaOB*ֻ5B=+l r<%GaBW"ef>\r 0)ไy(,SNOP/{̬I^y^H*ίx%woX p</%I(Eq%d&Ƚ00f LC]ylo3q 0忩`'y XX\>BYSdL L¯vwŤ a`BτΛ7|P(i}l-&=c00Aգe3wx&>QB=ƞٿ#&Ju{1a`ª8!K Ȉ~ W_+<@ Uhl`ܮ)0*<@xʎ )B}ڳw}vg>`7jNzQ&C-< XC{ȲgNlަO?0r<@8.pڮ<9Q/ԧC>{c>`< X5"C- -;86ґ;06<@0$ԇy;MUtK? 3 0f{`yYX\.O휷7B}`_B׳B!id !,yqjHvCUi iȏ`sj{c0PS<4ƭN '/`mG?u<0n{`"y[X\.cЅӃB}1ofwy!0 <@-,./UNf$ԏ̇K!;8?MI@zOI8l=_s3w&P_ǿ*򷏭68]+#L qxͧN (:'gٳw}vgSwr)ow%L*W9D O̩{_goR,`8ow[ SFvIOTCWyb L!qx B}+LvS a`J< P`0޽}31 SLҶB}""ԻW+ߓya$L*Ηwg~l cw<0fO-M 6a!8ھ zw<0fIyoaAy >AIz]1gR!48$ғdXD _v9ay 1WDz> =cFh(qHPq{1A Ky"ay&nXO= ˕Wf$ay*7?03BXݛ @yyn=ꅘ(ԇzl© e e<-7' ?o 2ow/$8L)&z5*owW :qh&z`~u!yawn|^D s|g :x&qhͧN •]2FyDŽqvwaP_B=Lⓢ<u%R< 5!جNq`ǞUhtiꡖDy0ҶB}z_UPw<"P_B=$G`j80rB} ov0-y^80VB} 01`2q`b< U00<SI,,._&N^ە]2F0kYX\P_B=JGy30k#׀P%0yFBHP΍nZWzzxl3pR` 8P:Q/'H6-i'0R<@- 5 3DyE`3g$׀PhaP_B=5]@D`ly$_BS  QF+q6:Q/'H'A<%0v ˟ͤCDyM`"τΛ6@# 5 3A &qP_B=cy1\N`yaCUhHQ*<\'zxKB}ڄzvImy%>qB=/ Syx B}z*<<0@T ˗}P` $sD<_+OB}7L7-By>qBT)}s$aaqy%s6kKH8@DB}Z`yRVl{|g7-$-B}rDya,,.rB}bDy%a$$NOP?1<ad-,. !چ>qBXyB8mKԌP8y|!MPce-_̴"kH|2|@`Zl>u^OP\<0@-L9>qBc<0@m,,./UbrB} ?o\QFHVyJ)_Έ0:<Il-_l0R4%=0@--,.|KO\ C(c"P[ BAx&>qzQHWBm^JO\B^1S6 riۃÞEya[X\8ʶPQOB("0OBs6 #!'nġy{v KU<`ĽFU4rh0TYX\$o c''n^yry7qd9{h+ 7,p@ 4<'`zD-XZD@'!HXq2}UYUQG ;'w=[o+;M0@6O&Z~5 c3kB0@6OƪtjJ57Ӈ׫ܙ`_O^ܴ`%tms({QS˘USUJvн퓳a`f}w% pJ?`~p`(}|< p~9X;\#+6O<ʗO~5'G)ߝLwX`n}rR:tnV/-6O 64S N.y"oU@a*'r/  b=l e~(lnL)\|kG">yRs_ m gWx8gU mS1`3X`ž\ jwN0O0}RypuVA<tJ0K,@*,7К_`y6Foc',t}޿ŅXyx"B4]r)6漝xiU fmxUVf0/0^U<PyX!BxoTtb6Pln~rn+-j.\ <:PƟDgWXn9ǰgE0 Fy3?cX)mV`f'G)ߝgX0h` >CCl*Z<qR8p+]P1ln7po_N <}R9&?s*퓗)w:4nz>@Pزc׹6qP~4U"|K<T},OCx<T}rR5`ƾ\iU΅`*>C=ׁyR:ř 8z@}G)x˵ :FOboT`>+w=bRu<j  퓱"51CO^|v!VOy84q](UnWsy& ׆5՜@^B~1+@yJyM䵫HyKyValWzUT@`c\!ىC07#]x 7́1yRsݺ29;=`~RJRJ[] R135K 0<̔~Mt@03}rRu gO =`SJSJ, :bfnsyJ鿮:&lnL)Z'@0>yRqA-R Ў;yb}2!I) N0>9K)ռ 8<u+_wXyhɳҟm_r {`Ÿ \ڵ_RJ? x а퓱krryhz@SJcx:]x2и1u~kY1oR>τV6Ї))ޤ`մNln 3'c%WJscQz@RJRJ5b:}Rk?9@gЩ퓳aMXV6Яq#)Ne_8:]|S7[JPmn}n,}]cΏNcgV6@-m4r&ަDbjsd O^8`EJiwgm%1~pz+SJc1Jcۧ/>~s0V?07Z>yR zfT0k*Uό*yfO<p):;>}xqR-yR<24VT:I}%Zw>yRY}hV6>}x.K&o*I*>y6_RJǟ>8sEhyࡎx*y<S1<ɸ+>c6x+yQ6O+8k_]z XG9T)H<h'c_oV9DɊCn#SpuX\N!}JI3WXy@X,٭r;XB^2ksv=h{8\2hqDRi뿇qX5/׆~` .alXMKl 'y?`}v}A6/К.3\9ӄ0pS-mv_ OM`h.1knK?'^,fhqCpSO+f_H}~?Ψu86.fΛݨ9oU\{ @p9~8тnjOGo<Bߌy ~x<4͵֜pn/ Z5|uL)YGF|ΆUm~]`tϻnZmr+8A7Cl +ntJl0kyzW66ҁЮݬR^ Ƥ:8cpV DK8x<+l5ml&a-9_sfK0O*-|jZml[7 K_Ф_}םU٘0[yzVJ66ҁV~HK a87Q5:kA/b(P66-,ϯ*QqK {ȳQ:fb >0\B00WyTicnRKкe)A7{=k|B8腍+٘0KyzU:yhI@h#? ^g$:8,XEmc3њ@0Ow/R<m_B(S+|hq?fo!fG0Oj,\ a~h a88x\nޞq|Jx66Jl<`v(zIJ7+fX3qX;ZVąO );669y2_Uj NA7{ݷ|Lðr?:|Vzevyz3*U/;A7{C*eiXyoiEGTjg%"7ofmc3Pnmù#Lyd}ml&ZstcfK?W/C w7{]zr%xqx66Jl 4'W _X?t `̭JЭp<՘,"(,pbXZiC'A΃h lLlD5!M/nn|x,0>$^^qR;eEm-t!WްrU7nf"Om5J[ॗ?D;xJD<-0ysfA0O/ZYF~A*ͱ fmvw=8 hEPqwy.3Zy`4/WiVx+jT;7{ t~6TXPaZUޏAq_z{UԸ , A`c%t&fojrwjٕÕJm&ta`{Cx @xyz0 $7 aZwG;ojyZ\F;9O0O Q uf?W5"b|3w`~?nc3o( i] ml&5p>DfM1)^8\͎q9O|gaf_-_kp&u5RS;)fTR6X`^W^U VVp$s"Ӭipױڹj%+khm*0+aoVWyˬsuhgc.@XyZL+jL2Cp6dxpv68kR=3wTo%a iYkj6fbP53^.hVlg74)WkBI^ ډ|봳!_yi%,\fml&52$U5RY5FuUG[Zl'Uv68,X ٌ_<\5'! iN^yX}ɬF0߈NmJˡBך '?=P[4ZQ딃guUӊ7NVx}Dďx9+rsϧ`f䥟5̎!bq„w>ozi#XJO*Rw!BUtX \V;N0O zn0QIjdیiCP!u,op0VcfR;5' 晵\A[=Dic3u^ﲗ7%\]8 7i?A3r EB7^ ;Uu(j/R_E|<&*f+;a:^FFK83wU$l!jX =ZV}t66Z2T#gϭ D ԙ\^RuS P%L< Ӥ\&b(e`9SyE6 [! 6]/^WjMfC< iWTlg%3Tt"s9PBVC(O?mlWP3KygQL.*6 _y÷lEsXc ~66li\LP>y @o̕*T\fymIU)>wU՚Ćb;q,Ђ߆|_(OenPq.5'U晝V 9+f_Fnjo]p=ME{c66Zsc 晣ZC66Z7{ҵmL8-revDL8c쳙TlMkN!glzK@ڵ/@Ϲrj}CTlg^b~g3yPkx?JǼZsP`YncS%P~8 rm[HȮ?lm,"a8<ыǼG @QyVۙmBVfvGr xyAI\Lp7?Jo o\ZrNji @QyVEzVngҤMG7(Z}mNP;>[KD[Ja8ʉ^/$9(I0l䥟zlq3Z!`=gC U[Ł@rr%%W똅 D3=U2WKP`9>qjn(a |ȓC( Ul~-K#Bskc3Ud%r;&m7]%Wmvj skzZ{5y{tmlr;!gύJ:˛٬V=8"$Ъؖ?v6blW?yS3-k2˩uy3OԺS,ʏM)AޱNl95a%MYN"#9(J9 1Z,Wڬh:z5 O 6F8wc(n@d8Ux?feo\YYW^7 ^||طX\VZwr5{; _3yfu rPf&3OjWA޸`W$W^[Z8Li&y=sfgOxfJZs>_r/Vv=vbO3ÿWz#VDj}&;2soc3?Uxݯ9 `F<奟@9Z+qqVO(AyaIV1yS-Dnuz YS^djd^Ykl Z ըnE[i( U ?MIiKpbKPk|p4I0Ot*[i0yc$k (+&DOj^DyD/Zic3NyF0OXygSk}+4~V瀨:{,!WZZ8<$o+P/wr{؟\x ժrm,5/TIe23~=~ׯq{ڲjzCZrp4G0Od'6 ¡]TXG*WOr_"R5O66Us% R^QؚlyQ6 1 寈2rvb+d pW`# IDAT52-Vng#`-Dez 6깬Oa PKNl=jÂN^-+D(iw"Pal`G)QmMOe֫{ԚJ^[Zo0yîbhT [H5V"TCYNz4`jV!hSȱjy_:yRSP~2 gqIU?/g>ߩ94q?9՞j2V͟vү; RiL8扦f5aMg{rd͵; ^u<~8ReP5C=9V܏1@Z,^ǙвEF??~PV6~֨,K@p0_87gX hN?n.>X<l°zc(? HwUO0ÖR}ɭ^y*i}U`¿՛S(-$CJA_ ۟(ܡPo(+!'dcZ 8Λw8|%堨B V5P2њ'`O{y1oF ]ErZRqn&4\O;O&_/Ft.P>Vi K5=rnd,}B+BU#WK%PS1wWWm8bܚ+R\+cKPogA} BiHn.}`NCliup~3x#XEbv]J'-ĸCh W(o Xb/j-+ʫ"=|T5Ouq2A+o"LBnE+%W4!"؈'5'JڢULvsVs.sJn75'ZI0_mYbqp4o.u4–6 &}o}^kOY X5oCiJP-9I|n]3Ŀ>KXB S%vȢ}>"FBvH[`"]9l`>o4V=p>t{879K#W|u3ܹ0 Vɹw-NWm'&_ <=7֜T0}+yrM*͆hxY3z]`Zfu8\s I Vju2iK & \=>V޿aFɏ\%?f~4!\i< bG*Y\,U᫠ ig@T毄aT!X|̽k.(7f-j=mik˿ډvPg;γj2جso0N_{]-,{;sSj̦ &.A`ZA9& X5=+V{.u7wZsw\%_-,s|\2"Xs%nðs}jh+ Y=Es@UwM0>ڊA* Jg_o乳yBᶃүv# _Æ`ඐzWge4.oZIagpg|mQߛ?jجWqھUp'jGo{kr֜*c c.s0. s@7wpZvŒ0h f8fo%``4@>.@oUKkhV@AyL&d&4FM7#k |t+E3+yI BwjwQNXƻS<ܞS>l16spVy^`F؄Ov^SNVT<lBXVabC`vs3}0 sʊQ3bg^_f(X7(f]DX^w' (, 5wFB4֪c^o{6;釶u͝/(ppvI\7:قl y$rΝ(Ds2)| s^f];'FMwnxjօ(t&Cks&Т)8.h''aTԺ. 16>9̽( TrpaGҬ4vF4(p>óvd첝#[{۽ePT*!d8cY1rQt;aq21_&]]P7 /x1 hAxEQ.u汋3g+9~+̇1yeLiw2[?}),ЭFlVnqbyS(0kn2c.㊹ |8%v'`ea$R6,c{ >lNJ}Gb6e.7hN2W |.'xCbДhۘY0Oa8bwϢE`| *Wη'geL=CNaMsbFY.B?nڢ؊Kl&qbj;myW\¼9^*̇D4so5)\ޫlԤBԺ ;6P3E<%gg ќt@f.̇6_/뒟a˿u/b &h::o׷{ >qbDa x&5I|bF7&{WabS↧81KO+-ޟ͈Z-x#TԺLB?)65wE12e:xa[2* _O4]=RXkR($Qק0S3{?tI]v%2l%ќ0_O㻯؍vBAA]gg"ACke.Y8.*cylR .H,{\;9cs@&^XM,E|1I?YY.?r m|@&˜ނ8q of9P-hN2 ;${Y.OJ<*) p]]c'. Q>l|W[[Q^!NL~f(,` u eq; pn`?묋~aQ7c;p#M >׊H͝}blҢIؗ@q8-@]`c?sOOO?m]9 UYEpL ~o_<s!\>ˢIENDB`jsonp-api-2.1.3-RELEASE/spec/src/main/asciidoc/jsonp-spec.adoc000066400000000000000000000012601451447132700236360ustar00rootroot00000000000000// // Copyright (c) 2017, 2020 Contributors to the Eclipse Foundation // = Jakarta JSON Processing :authors: Jakarta JSON Processing Team, https://projects.eclipse.org/projects/ee4j.jsonp :email: https://dev.eclipse.org/mailman/listinfo/jsonp-dev :version-label!: :doctype: book :license: Eclipse Foundation Specification License v1.0 :source-highlighter: coderay :toc: left :toclevels: 4 :sectnumlevels: 4 :sectanchors: ifdef::backend-pdf[] :pagenums: :numbered: :title-logo-image: image:images/jakarta_ee_logo_schooner_color_stacked_default.png[pdfwidth=4.25in,align=right] endif::[] // == License :sectnums!: include::license-efsl.adoc[] // == Spec :sectnums: include::jsonp.adoc[] jsonp-api-2.1.3-RELEASE/spec/src/main/asciidoc/jsonp.adoc000066400000000000000000000003311451447132700227040ustar00rootroot00000000000000// // Copyright (c) 2018, 2020 Contributors to the Eclipse Foundation // == Introduction Jakarta JSON Processing defines a Java(R) based framework for parsing, generating, transforming, and querying JSON documents. jsonp-api-2.1.3-RELEASE/spec/src/main/asciidoc/license-efsl.adoc000066400000000000000000000061231451447132700241310ustar00rootroot00000000000000[subs="normal"] .... Specification: {doctitle} Version: {revnumber} ifeval::["{revremark}" != ""] Status: {revremark} endif::[] ifeval::["{revremark}" == ""] Status: Final Release endif::[] Release: {revdate} .... Copyright (c) 2019 Eclipse Foundation. === Eclipse Foundation Specification License By using and/or copying this document, or the Eclipse Foundation document from which this statement is linked, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions: Permission to copy, and distribute the contents of this document, or the Eclipse Foundation document from which this statement is linked, in any medium for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the document, or portions thereof, that you use: * link or URL to the original Eclipse Foundation document. * All existing copyright notices, or if one does not exist, a notice (hypertext is preferred, but a textual representation is permitted) of the form: "Copyright (c) [$date-of-document] Eclipse Foundation, Inc. <>" Inclusion of the full text of this NOTICE must be provided. We request that authorship attribution be provided in any software, documents, or other items or products that you create pursuant to the implementation of the contents of this document, or any portion thereof. No right to create modifications or derivatives of Eclipse Foundation documents is granted pursuant to this license, except anyone may prepare and distribute derivative works and portions of this document in software that implements the specification, in supporting materials accompanying such software, and in documentation of such software, PROVIDED that all such works include the notice below. HOWEVER, the publication of derivative works of this document for use as a technical specification is expressly prohibited. The notice is: "Copyright (c) 2018 Eclipse Foundation. This software or document includes material copied from or derived from [title and URI of the Eclipse Foundation specification document]." ==== Disclaimers THIS DOCUMENT IS PROVIDED "AS IS," AND THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF. The name and trademarks of the copyright holders or the Eclipse Foundation may NOT be used in advertising or publicity pertaining to this document or its contents without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.jsonp-api-2.1.3-RELEASE/spec/src/theme/000077500000000000000000000000001451447132700173265ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/spec/src/theme/jakartaee-theme.yml000066400000000000000000000241571451447132700231110ustar00rootroot00000000000000# # Following is the asciidoctor-pdf default theme [1], with small # customizations, mostly for header and footer, marked "EE". # # [1] https://github.com/asciidoctor/asciidoctor-pdf/blob/master/data/themes/default-theme.yml # font: catalog: # Noto Serif supports Latin, Latin-1 Supplement, Latin Extended-A, Greek, Cyrillic, Vietnamese & an assortment of symbols Noto Serif: normal: notoserif-regular-subset.ttf bold: notoserif-bold-subset.ttf italic: notoserif-italic-subset.ttf bold_italic: notoserif-bold_italic-subset.ttf # M+ 1mn supports ASCII and the circled numbers used for conums M+ 1mn: normal: mplus1mn-regular-ascii-conums.ttf bold: mplus1mn-bold-ascii.ttf italic: mplus1mn-italic-ascii.ttf bold_italic: mplus1mn-bold_italic-ascii.ttf # M+ 1p supports Latin, Latin-1 Supplement, Latin Extended, Greek, Cyrillic, Vietnamese, Japanese & an assortment of symbols # It also provides arrows for ->, <-, => and <= replacements in case these glyphs are missing from font M+ 1p Fallback: normal: mplus1p-regular-fallback.ttf bold: mplus1p-regular-fallback.ttf italic: mplus1p-regular-fallback.ttf bold_italic: mplus1p-regular-fallback.ttf fallbacks: - M+ 1p Fallback page: background_color: ffffff layout: portrait margin: [0.5in, 0.67in, 0.67in, 0.67in] # margin_inner and margin_outer keys are used for recto/verso print margins when media=prepress margin_inner: 0.75in margin_outer: 0.59in #size: A4 # EE size: Letter # EE base: align: justify # color as hex string (leading # is optional) font_color: 333333 # color as RGB array #font_color: [51, 51, 51] # color as CMYK array (approximated) #font_color: [0, 0, 0, 0.92] #font_color: [0, 0, 0, 92%] font_family: Noto Serif # choose one of these font_size/line_height_length combinations #font_size: 14 #line_height_length: 20 #font_size: 11.25 #line_height_length: 18 #font_size: 11.2 #line_height_length: 16 font_size: 10.5 #line_height_length: 15 # correct line height for Noto Serif metrics line_height_length: 12 #font_size: 11.25 #line_height_length: 18 line_height: $base_line_height_length / $base_font_size font_size_large: round($base_font_size * 1.25) font_size_small: round($base_font_size * 0.85) font_size_min: $base_font_size * 0.75 font_style: normal border_color: eeeeee border_radius: 4 border_width: 0.5 # FIXME vertical_rhythm is weird; we should think in terms of ems #vertical_rhythm: $base_line_height_length * 2 / 3 # correct line height for Noto Serif metrics (comes with built-in line height) vertical_rhythm: $base_line_height_length horizontal_rhythm: $base_line_height_length # QUESTION should vertical_spacing be block_spacing instead? vertical_spacing: $vertical_rhythm link: font_color: 428bca # literal is currently used for inline monospaced in prose and table cells literal: font_color: b12146 font_family: M+ 1mn menu_caret_content: " \u203a " heading: align: left #font_color: 181818 font_color: $base_font_color font_family: $base_font_family font_style: bold # h1 is used for part titles (book doctype) or the doctitle (article doctype) #h1_font_size: floor($base_font_size * 2.6) # EE h1_font_size: floor($base_font_size * 2.5) # EE, squeeze title onto one line # h2 is used for chapter titles (book doctype only) h2_font_size: floor($base_font_size * 2.15) h3_font_size: round($base_font_size * 1.7) h4_font_size: $base_font_size_large h5_font_size: $base_font_size h6_font_size: $base_font_size_small #line_height: 1.4 # correct line height for Noto Serif metrics (comes with built-in line height) line_height: 1 margin_top: $vertical_rhythm * 0.4 margin_bottom: $vertical_rhythm * 0.9 title_page: align: right logo: top: 10% title: top: 55% font_size: $heading_h1_font_size font_color: 999999 line_height: 0.9 subtitle: font_size: $heading_h3_font_size font_style: bold_italic line_height: 1 authors: margin_top: $base_font_size * 1.25 font_size: $base_font_size_large font_color: 181818 revision: margin_top: $base_font_size * 1.25 block: margin_top: 0 margin_bottom: $vertical_rhythm caption: align: left font_size: $base_font_size * 0.95 font_style: italic # FIXME perhaps set line_height instead of / in addition to margins? margin_inside: $vertical_rhythm / 3 #margin_inside: $vertical_rhythm / 4 margin_outside: 0 lead: font_size: $base_font_size_large line_height: 1.4 abstract: font_color: 5c6266 font_size: $lead_font_size line_height: $lead_line_height font_style: italic first_line_font_style: bold title: align: center font_color: $heading_font_color font_family: $heading_font_family font_size: $heading_h4_font_size font_style: $heading_font_style admonition: column_rule_color: $base_border_color column_rule_width: $base_border_width padding: [0, $horizontal_rhythm, 0, $horizontal_rhythm] #icon: # tip: # name: fa-lightbulb-o # stroke_color: 111111 # size: 24 label: text_transform: uppercase font_style: bold blockquote: font_color: $base_font_color font_size: $base_font_size_large border_color: $base_border_color border_width: 5 # FIXME disable negative padding bottom once margin collapsing is implemented padding: [0, $horizontal_rhythm, $block_margin_bottom * -0.75, $horizontal_rhythm + $blockquote_border_width / 2] cite_font_size: $base_font_size_small cite_font_color: 999999 # code is used for source blocks (perhaps change to source or listing?) code: font_color: $base_font_color font_family: $literal_font_family font_size: ceil($base_font_size) padding: $code_font_size line_height: 1.25 # line_gap is an experimental property to control how a background color is applied to an inline block element line_gap: 3.8 background_color: f5f5f5 border_color: cccccc border_radius: $base_border_radius border_width: 0.75 conum: font_family: M+ 1mn font_color: $literal_font_color font_size: $base_font_size line_height: 4 / 3 example: border_color: $base_border_color border_radius: $base_border_radius border_width: 0.75 background_color: ffffff # FIXME reenable padding bottom once margin collapsing is implemented padding: [$vertical_rhythm, $horizontal_rhythm, 0, $horizontal_rhythm] image: align: left prose: margin_top: $block_margin_top margin_bottom: $block_margin_bottom sidebar: background_color: eeeeee border_color: e1e1e1 border_radius: $base_border_radius border_width: $base_border_width # FIXME reenable padding bottom once margin collapsing is implemented padding: [$vertical_rhythm, $vertical_rhythm * 1.25, 0, $vertical_rhythm * 1.25] title: align: center font_color: $heading_font_color font_family: $heading_font_family font_size: $heading_h4_font_size font_style: $heading_font_style thematic_break: border_color: $base_border_color border_style: solid border_width: $base_border_width margin_top: $vertical_rhythm * 0.5 margin_bottom: $vertical_rhythm * 1.5 description_list: term_font_style: bold term_spacing: $vertical_rhythm / 4 description_indent: $horizontal_rhythm * 1.25 outline_list: indent: $horizontal_rhythm * 1.5 #marker_font_color: 404040 # NOTE outline_list_item_spacing applies to list items that do not have complex content item_spacing: $vertical_rhythm / 2 table: background_color: $page_background_color #head_background_color: #head_font_color: $base_font_color head_font_style: bold #body_background_color: body_stripe_background_color: f9f9f9 foot_background_color: f0f0f0 border_color: dddddd border_width: $base_border_width cell_padding: 3 toc: indent: $horizontal_rhythm line_height: 1.4 dot_leader: #content: ". " font_color: a9a9a9 #levels: 2 3 # NOTE in addition to footer, header is also supported footer: font_size: $base_font_size_small # NOTE if background_color is set, background and border will span width of page #border_color: dddddd # EE #border_width: 0.25 # EE height: $base_line_height_length * 2.5 line_height: 1 padding: [$base_line_height_length / 2, 1, 0, 1] vertical_align: top #image_vertical_align: or # additional attributes for content: # * {page-count} # * {page-number} # * {document-title} # * {document-subtitle} # * {chapter-title} # * {section-title} # * {section-or-chapter-title} recto: #columns: "<50% =0% >50%" right: #content: '{page-number}' # EE #content: '{section-or-chapter-title} | {page-number}' #content: '{document-title} | {page-number}' content: '{document-title}{nbsp}{nbsp}{nbsp} *{page-number}*' # EE #center: # content: '{page-number}' left: # EE content: '{status}' # EE verso: #columns: $footer_recto_columns left: #content: $footer_recto_right_content # EE #content: '{page-number} | {chapter-title}' content: '*{page-number}* {nbsp}{nbsp}{nbsp}{document-title}' # EE #center: # content: '{page-number}' right: # EE content: '{status}' # EE header: # EE font_size: $base_font_size_small # EE border_color: dddddd # EE border_width: 0.25 # EE height: $base_line_height_length * 2.5 # EE line_height: 1 # EE padding: [$base_line_height_length / 2, 1, 0, 1] # EE vertical_align: top # EE recto: # EE right: # EE content: '{section-or-chapter-title}' # EE verso: # EE left: # EE content: '{section-or-chapter-title}' # EE jsonp-api-2.1.3-RELEASE/tck/000077500000000000000000000000001451447132700152645ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/pom.xml000066400000000000000000000126021451447132700166020ustar00rootroot00000000000000 4.0.0 org.eclipse.ee4j project 1.0.7 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT pom Jakarta JSON Processing TCK Jakarta JSON Processing TCK tck-common tck-tests tck-tests-pluggability tck-docs/userguide tck-dist-eftl tck-dist-epl Eclipse Public License 2.0 https://projects.eclipse.org/license/epl-2.0 repo GNU General Public License, version 2 with the GNU Classpath Exception https://projects.eclipse.org/license/secondary-gpl-2.0-cp repo UTF-8 11 11 5.7.2 2.1.0 jakarta.json jakarta.json-tck-common ${project.version} jakarta.json jakarta.json-tck-tests ${project.version} jakarta.json jakarta.json-tck-tests-pluggability ${project.version} jakarta.json jakarta.json-tck-ug ${project.version} org.netbeans.tools sigtest-maven-plugin 1.6 jakarta.json jakarta.json-api ${jakarta.json-api.version} org.junit.jupiter junit-jupiter-api ${junit.jupiter.version} org.junit.jupiter junit-jupiter-engine ${junit.jupiter.version} jakarta.json jakarta.json-api provided org.junit.jupiter junit-jupiter-api org.junit.jupiter junit-jupiter-engine org.apache.maven.plugins maven-assembly-plugin 3.3.0 org.apache.maven.plugins maven-javadoc-plugin 3.3.1 jsonp-api-2.1.3-RELEASE/tck/tck-common/000077500000000000000000000000001451447132700173335ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/pom.xml000066400000000000000000000040141451447132700206470ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT ../pom.xml jakarta.json-tck-common org.apache.maven.plugins maven-javadoc-plugin none org.apache.maven.plugins maven-source-plugin attach-sources jar-no-fork jsonp-api-2.1.3-RELEASE/tck/tck-common/src/000077500000000000000000000000001451447132700201225ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/000077500000000000000000000000001451447132700210465ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/000077500000000000000000000000001451447132700217675ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/000077500000000000000000000000001451447132700223605ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/000077500000000000000000000000001451447132700237755ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/000077500000000000000000000000001451447132700245565ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/000077500000000000000000000000001451447132700257075ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/000077500000000000000000000000001451447132700271775ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/JSONP_Data.java000066400000000000000000000225701451447132700316720ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.common; import java.util.*; public final class JSONP_Data { public static final String unicodeControlCharsEscaped = "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\u0008\\u0009" + "\\u000a\\u000b\\u000c\\u000d\\u000e\\u000f" + "\\u000A\\u000B\\u000C\\u000D\\u000E\\u000F" + "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019" + "\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\\u007f" + "\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F\\u007F" + "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087\\u0088\\u0089" + "\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" + "\\u008A\\u008B\\u008C\\u008D\\u008E\\u008F" + "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097\\u0098\\u0099" + "\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" + "\\u009A\\u009B\\u009C\\u009D\\u009E\\u009F"; // NOTE: For the unicode values u000a and u000d we need to use the Java // escape for both NL and CR as \n and \r respectively public static final String unicodeControlCharsNonEscaped = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009" + "\n\u000b\u000c\r\u000e\u000f" + "\n\u000B\u000C\r\u000E\u000F" + "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019" + "\u001a\u001b\u001c\u001d\u001e\u001f\u007f" + "\u001A\u001B\u001C\u001D\u001E\u001F\u007F" + "\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089" + "\u008a\u008b\u008c\u008d\u008e\u008f" + "\u008A\u008B\u008C\u008D\u008E\u008F" + "\u0090\u0091\u0092\u0093\u0094\u0095\u0096\u0097\u0098\u0099" + "\u009a\u009b\u009c\u009d\u009e\u009f" + "\u009A\u009B\u009C\u009D\u009E\u009F"; // Standard backslash escape characters public static final String escapeCharsAsString = "\"\\/\b\f\n\r\t"; public static final String asciiCharacters = "!@#$%^&*()_+|~1234567890-=;',./<>? " + "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; public static final String jsonArrayTestData = "[ \"\", \"string\", 100, true, false, null, {}, { \"name\" : \"value\" }, [], [ \"one\", \"two\" ] ]"; public static final String jsonObjectTestData = "{" + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + "\"null\" : null," + "\"object\" : { \"name\" : \"value\" }," + "\"array\" : [ \"one\", \"two\" ]," + "}"; public static final String jsonArrayTestData2 = "[" + "\"\"," + "[]," + "{}," + "\"string\"," + "100," + "true," + "false," + "null," + "{ \"name\" : \"value\" }," + "[ \"one\", \"two\" ]," + "]"; public static final String jsonObjectWithAllTypesOfData = "{" + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + "\"null\" : null," + "\"object\" : {" + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + "\"null\" : null," + "\"object\" : { \"name\" : \"value\" }," + "\"array\" : [ \"one\", \"two\" ]" + "}," + "\"array\" : [ \"string\", 100, true, false, null, { \"name\" : \"value\" }" + ", [ \"one\", \"two\" ] " + "]," + "\"intPositive\" : 100," + "\"intNegative\" : -100," + "\"longMax\" : 9223372036854775807," + "\"longMin\" : -9223372036854775808," + "\"fracPositive\" : 0.5," + "\"fracNegative\" : -0.5," + "\"expPositive1\" : 7e3," + "\"expPositive2\" : 7e+3," + "\"expPositive3\" : 9E3," + "\"expPositive4\" : 9E+3," + "\"expNegative1\" : 7e-3," + "\"expNegative2\" : 7E-3," + "\"asciiChars\" : \"" + asciiCharacters + "\"" + "}"; public static final String jsonArrayWithAllTypesOfData = "[" + "\"\"," + "[]," + "{}," + "\"string\"," + "100," + "true," + "false," + "null," + "{" + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + "\"null\" : null," + "\"object\" : { \"name\" : \"value\" }," + "\"array\" : [ \"one\", \"two\" ]" + "}," + "[ \"string\", 100, true, false, null, { \"name\" : \"value\" }" + ", [ \"one\", \"two\" ] " + "]," + "100," + "-100," + "9223372036854775807," + "-9223372036854775808," + "0.5," + "-0.5," + "7e3," + "7e+3," + "9E3," + "9E+3," + "7e-3," + "7E-3," + "\"" + asciiCharacters + "\"" + "]"; public static final String jsonObjectWithLotsOfNestedObjectsData = "{" + "\"nested1\" : {" + "\"name1\" : \"value1\"," + "\"nested2\" : {" + "\"name2\" : \"value2\"," + "\"nested3\" : {" + "\"name3\" : \"value3\"," + "\"nested4\" : {" + "\"name4\" : \"value4\"," + "\"nested5\" : {" + "\"name5\" : \"value5\"," + "\"nested6\" : {" + "\"name6\" : \"value6\"," + "\"nested7\" : {" + "\"name7\" : \"value7\"," + "\"nested8\" : {" + "\"name8\" : \"value8\"," + "\"nested9\" : {" + "\"name9\" : \"value9\"," + "\"nested10\" : {" + "\"name10\" : \"value10\"," + "\"nested11\" : {" + "\"name11\" : \"value11\"," + "\"nested12\" : {" + "\"name12\" : \"value12\"," + "\"nested13\" : {" + "\"name13\" : \"value13\"," + "\"nested14\" : {" + "\"name14\" : \"value14\"," + "\"nested15\" : {" + "\"name15\" : \"value15\"," + "\"nested16\" : {" + "\"name16\" : \"value16\"," + "\"nested17\" : {" + "\"name17\" : \"value17\"," + "\"nested18\" : {" + "\"name18\" : \"value18\"," + "\"nested19\" : {" + "\"name19\" : \"value19\"," + "\"nested20\" : {" + "\"name20\" : \"value20\"," + "\"nested21\" : {" + "\"name21\" : \"value21\"," + "\"nested22\" : {" + "\"name22\" : \"value22\"," + "\"nested23\" : {" + "\"name23\" : \"value23\"," + "\"nested24\" : {" + "\"name24\" : \"value24\"," + "\"nested25\" : {" + "\"name25\" : \"value25\"," + "\"nested26\" : {" + "\"name26\" : \"value26\"," + "\"nested27\" : {" + "\"name27\" : \"value27\"," + "\"nested28\" : {" + "\"name28\" : \"value28\"," + "\"nested29\" : {" + "\"name29\" : \"value29\"," + "\"nested30\" : {" + "\"name30\" : \"value30\"" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}"; public static final String jsonArrayWithLotsOfNestedObjectsData = "[" + "{" + "\"name1\" : \"value1\"," + "\"nested2\" : {" + "\"name2\" : \"value2\"," + "\"nested3\" : {" + "\"name3\" : \"value3\"," + "\"nested4\" : {" + "\"name4\" : \"value4\"," + "\"nested5\" : {" + "\"name5\" : \"value5\"," + "\"nested6\" : {" + "\"name6\" : \"value6\"," + "\"nested7\" : {" + "\"name7\" : \"value7\"," + "\"nested8\" : {" + "\"name8\" : \"value8\"," + "\"nested9\" : {" + "\"name9\" : \"value9\"," + "\"nested10\" : {" + "\"name10\" : \"value10\"," + "\"nested11\" : {" + "\"name11\" : \"value11\"," + "\"nested12\" : {" + "\"name12\" : \"value12\"," + "\"nested13\" : {" + "\"name13\" : \"value13\"," + "\"nested14\" : {" + "\"name14\" : \"value14\"," + "\"nested15\" : {" + "\"name15\" : \"value15\"," + "\"nested16\" : {" + "\"name16\" : \"value16\"," + "\"nested17\" : {" + "\"name17\" : \"value17\"," + "\"nested18\" : {" + "\"name18\" : \"value18\"," + "\"nested19\" : {" + "\"name19\" : \"value19\"," + "\"nested20\" : {" + "\"name20\" : \"value20\"," + "\"nested21\" : {" + "\"name21\" : \"value21\"," + "\"nested22\" : {" + "\"name22\" : \"value22\"," + "\"nested23\" : {" + "\"name23\" : \"value23\"," + "\"nested24\" : {" + "\"name24\" : \"value24\"," + "\"nested25\" : {" + "\"name25\" : \"value25\"," + "\"nested26\" : {" + "\"name26\" : \"value26\"," + "\"nested27\" : {" + "\"name27\" : \"value27\"," + "\"nested28\" : {" + "\"name28\" : \"value28\"," + "\"nested29\" : {" + "\"name29\" : \"value29\"," + "\"nested30\" : {" + "\"name30\" : \"value30\"" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "]"; public static final String jsonArrayWithMultipleArraysData = "[ \"string\", 100, true, false, null, { \"object\" : \"object\" }, [ \"one\"," + "\"two\" ], [ 100, 7e7, true, false, null, { \"object2\" : \"object2\" } ] ]"; } jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/JSONP_Util.java000066400000000000000000003126021451447132700317340ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.common; import java.util.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.nio.charset.Charset; import java.math.BigInteger; import java.math.BigDecimal; import java.util.logging.Logger; import jakarta.json.*; import jakarta.json.stream.*; public final class JSONP_Util { private static final Logger LOGGER = Logger.getLogger(JSONP_Util.class.getName()); // Charset CONSTANTS for all the supported UTF encodings public static final Charset UTF_8 = Charset.forName("UTF-8"); public static final Charset UTF_16 = Charset.forName("UTF-16"); public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); public static final Charset UTF_32BE = Charset.forName("UTF-32BE"); public static final Charset UTF_32LE = Charset.forName("UTF-32LE"); // Test Config properties public static final String FOO_CONFIG = "ee.jakarta.tck.jsonp.common.FOO_CONFIG"; // Number of parser errors encountered private static int parseErrs = 0; // A JsonNumber NumberType is now INTEGRAL or NON_INTEGRAL based on // JsonNumber.isIntegral(). // The following 2 constant definitions represent these NumberType boolean // values. public static final boolean INTEGRAL = true; public static final boolean NON_INTEGRAL = false; /********************************************************************************* * {@code void dumpContentsOfResource(String resource)} *********************************************************************************/ public static void dumpContentsOfResource(String resource) { LOGGER.info("Dumping contents of Resource file: " + resource); BufferedReader reader = null; try { InputStream iStream = JSONP_Util.class .getResourceAsStream("/" + resource); if (iStream == null) { LOGGER.warning( "dumpContentsOfResource: no resource found in classpath or archive named " + resource); return; } reader = new BufferedReader(new InputStreamReader(iStream)); String thisLine; while ((thisLine = reader.readLine()) != null) { LOGGER.info(thisLine); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (Exception e) { LOGGER.warning("exception closing stream: " + e); } } } /********************************************************************************* * {@code void dumpFile(String file)} *********************************************************************************/ public static void dumpFile(String file) { LOGGER.info("Dumping contents of file: " + file); BufferedReader reader = null; try { FileInputStream fis = new FileInputStream(file); if (fis == null) { LOGGER.warning("dumpFile: no file found named " + file); return; } reader = new BufferedReader(new InputStreamReader(fis)); String thisLine; while ((thisLine = reader.readLine()) != null) { LOGGER.info(thisLine); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (Exception e) { LOGGER.warning("exception closing stream: " + e); } } } /********************************************************************************* * {@code String getContentsOfResourceAsString(String resource)} *********************************************************************************/ public static String getContentsOfResourceAsString(String resource) { StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { InputStream iStream = JSONP_Util.class .getResourceAsStream("/" + resource); if (iStream == null) { LOGGER.warning( "dumpContentsOfResource: no resource found in classpath or archive named " + resource); return null; } reader = new BufferedReader(new InputStreamReader(iStream)); String thisLine; while ((thisLine = reader.readLine()) != null) { sb.append(thisLine); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (Exception e) { LOGGER.warning("exception closing stream: " + e); } } return sb.toString(); } /********************************************************************************* * {@code Reader getReaderFromResource(String resource)} *********************************************************************************/ public static Reader getReaderFromResource(String resource) { InputStreamReader reader = null; try { InputStream iStream = JSONP_Util.class .getResourceAsStream("/" + resource); if (iStream == null) LOGGER.warning( "getReaderFromResource: no resource found in classpath or archive named " + resource); else reader = new InputStreamReader(iStream); } catch (Exception e) { e.printStackTrace(); } return reader; } /********************************************************************************* * {@code Reader getReaderFromString(String contents)} *********************************************************************************/ public static Reader getReaderFromString(String contents) { InputStreamReader reader = null; try { InputStream iStream = new ByteArrayInputStream(contents.getBytes(UTF_8)); if (iStream == null) LOGGER.warning("getReaderFromString: no input stream"); else reader = new InputStreamReader(iStream); } catch (Exception e) { e.printStackTrace(); } return reader; } /********************************************************************************* * {@code InputStream getInputStreamFromResource(String resource)} *********************************************************************************/ public static InputStream getInputStreamFromResource(String resource) { InputStream iStream = null; try { iStream = JSONP_Util.class.getResourceAsStream("/" + resource); if (iStream == null) LOGGER.warning( "getInputStreamFromResource: no resource found in classpath or archive named " + resource); } catch (Exception e) { e.printStackTrace(); } return iStream; } /********************************************************************************* * {@code InputStream getInputStreamFromString(String contents)} *********************************************************************************/ public static InputStream getInputStreamFromString(String contents) { InputStream iStream = null; try { iStream = new ByteArrayInputStream(contents.getBytes(UTF_8)); if (iStream == null) LOGGER.warning("getInputStreamFromString: no input stream"); } catch (Exception e) { e.printStackTrace(); } return iStream; } /********************************************************************************* * {@code InputStream getInputStreamFromOutputStream(ByteArrayOutputStream baos)} *********************************************************************************/ public static InputStream getInputStreamFromOutputStream( ByteArrayOutputStream baos) { InputStream iStream = null; try { iStream = new ByteArrayInputStream(baos.toByteArray()); if (iStream == null) LOGGER.warning("getInputStreamFromOutputStream: no input stream"); } catch (Exception e) { e.printStackTrace(); } return iStream; } /********************************************************************************* * {@code String removeWhitespace(String text)} * * NOTE: This does not remove whitespace of Json text if a quoted string which * can include whitespace. *********************************************************************************/ public static String removeWhitespace(String text) { StringReader reader = new StringReader(text); StringWriter writer = new StringWriter(); try { boolean quotedString = false; boolean backslash = false; int c; while ((c = reader.read()) != -1) { // Skip white space if not quoted string if (!quotedString) { if (Character.isWhitespace(c)) continue; } writer.write(c); if (c == '"') { if (!backslash) quotedString = !quotedString; backslash = false; } else if (c == '\\') backslash = true; } } catch (IOException e) { e.printStackTrace(); } return writer.toString(); } /********************************************************************************* * {@code JsonNumber createJsonNumber} * * The following method signatures are available: * * o JsonNumber createJsonNumber(double) o JsonNumber createJsonNumber(long) o * JsonNumber createJsonNumber(int) o JsonNumber createJsonNumber(BigDecimal) * o JsonNumber createJsonNumber(BigInteger) *********************************************************************************/ public static JsonNumber createJsonNumber(double val) { JsonArray array = Json.createArrayBuilder().add(val).build(); return array.getJsonNumber(0); } public static JsonNumber createJsonNumber(long val) { JsonArray array = Json.createArrayBuilder().add(val).build(); return array.getJsonNumber(0); } public static JsonNumber createJsonNumber(int val) { JsonArray array = Json.createArrayBuilder().add(val).build(); return array.getJsonNumber(0); } public static JsonNumber createJsonNumber(BigDecimal val) { JsonArray array = Json.createArrayBuilder().add(val).build(); return array.getJsonNumber(0); } public static JsonNumber createJsonNumber(BigInteger val) { JsonArray array = Json.createArrayBuilder().add(val).build(); return array.getJsonNumber(0); } /********************************************************************************* * {@code JsonString createJsonString(String val)} *********************************************************************************/ public static JsonString createJsonString(String val) { JsonArray array = Json.createArrayBuilder().add(val).build(); return array.getJsonString(0); } /********************************************************************************* * {@code void dumpJsonString(JsonString val)} *********************************************************************************/ public static void dumpJsonString(JsonString value) { LOGGER.info("dumpJsonString->" + toStringJsonString(value)); } /********************************************************************************* * {@code void dumpJsonArray(JsonArray value)} *********************************************************************************/ public static void dumpJsonArray(JsonArray value) { LOGGER.info("dumpJsonArray->" + toStringJsonArray(value)); } /********************************************************************************* * {@code void dumpJsonObject(JsonObject value)} *********************************************************************************/ public static void dumpJsonObject(JsonObject value) { LOGGER.info("dumpJsonObject->" + toStringJsonObject(value)); } /********************************************************************************* * {@code void dumpJsonConstant(JsonValue value)} *********************************************************************************/ public static void dumpJsonConstant(JsonValue value) { LOGGER.info("dumpJsonConstant->" + toStringJsonConstant(value)); } /********************************************************************************* * {@code void dumpJsonNumber(JsonNumber value)} *********************************************************************************/ public static void dumpJsonNumber(JsonNumber value) { LOGGER.info("dumpJsonNumber->" + toStringJsonNumber(value)); } /********************************************************************************* * {@code void dumpJsonValue(JsonValue value)} *********************************************************************************/ public static void dumpJsonValue(JsonValue value) { if (value instanceof JsonNumber) { dumpJsonNumber((JsonNumber) value); } else if (value instanceof JsonString) { dumpJsonString((JsonString) value); } else if (value instanceof JsonArray) { dumpJsonArray((JsonArray) value); } else if (value instanceof JsonObject) { dumpJsonObject((JsonObject) value); } else dumpJsonConstant(value); } /********************************************************************************* * {@code String toStringJsonString(JsonString value)} *********************************************************************************/ public static String toStringJsonString(JsonString value) { if (value == null) return ("JsonString is null"); return ("\"" + value.getString() + "\""); } /********************************************************************************* * {@code String toStringJsonArray(JsonArray value)} *********************************************************************************/ public static String toStringJsonArray(JsonArray value) { if (value == null) return ("JsonArray is null"); StringBuilder sb = new StringBuilder(); sb.append("["); Iterator iter = value.iterator(); String comma = ""; while (iter.hasNext()) { sb.append(comma + toStringJsonValue(iter.next())); if (comma.equals("")) comma = ","; } sb.append("]"); return (sb.toString()); } /********************************************************************************* * {@code String toStringJsonObject(JsonObject value)} *********************************************************************************/ public static String toStringJsonObject(JsonObject value) { if (value == null) return ("JsonObject is null"); StringBuilder sb = new StringBuilder(); sb.append("{"); String comma = ""; for (Map.Entry entry : value.entrySet()) { sb.append(comma + "\"" + entry.getKey() + "\":" + toStringJsonValue(entry.getValue())); if (comma.equals("")) comma = ","; } sb.append("}"); return (sb.toString()); } /********************************************************************************* * {@code String toStringJsonConstant(JsonValue value)} *********************************************************************************/ public static String toStringJsonConstant(JsonValue value) { if (value == null) return ("JsonValue is null"); if (value == JsonValue.FALSE) return "false"; else if (value == JsonValue.TRUE) return "true"; else if (value == JsonValue.NULL) return "null"; else return "UNKNOWN"; } /********************************************************************************* * {@code String toStringJsonNumber(JsonNumber value)} *********************************************************************************/ public static String toStringJsonNumber(JsonNumber value) { if (value == null) return ("JsonNumber is null"); if (value.isIntegral() == INTEGRAL) return ("" + value.longValue()); else return ("" + value.bigDecimalValue()); } /********************************************************************************* * {@code String toStringJsonValue(JsonValue value)} *********************************************************************************/ public static String toStringJsonValue(JsonValue value) { if (value instanceof JsonNumber) { return toStringJsonNumber((JsonNumber) value); } else if (value instanceof JsonString) { return toStringJsonString((JsonString) value); } else if (value instanceof JsonArray) { return toStringJsonArray((JsonArray) value); } else if (value instanceof JsonObject) { return toStringJsonObject((JsonObject) value); } else return toStringJsonConstant(value); } /********************************************************************************* * {@code void dumpSet(Set set, String msg)} *********************************************************************************/ public static void dumpSet(Set set, String msg) { LOGGER.info("*** Beg: Dumping List contents ***"); if (msg != null) LOGGER.info("*** Message: " + msg); Iterator iterator = set.iterator(); LOGGER.info("Set: ("); while (iterator.hasNext()) { LOGGER.info((String) iterator.next()); } LOGGER.info(")"); LOGGER.info("*** End: Dumping Set contents ***"); } /********************************************************************************* * {@code void dumpSet(Set set)} *********************************************************************************/ public static void dumpSet(Set set) { dumpSet(set, null); } /********************************************************************************* * {@code String toStringSet(Set set)} *********************************************************************************/ public static String toStringSet(Set set) { Iterator iter = set.iterator(); StringBuilder sb = new StringBuilder(); sb.append("Set: ("); while (iter.hasNext()) { sb.append(iter.next()); if (iter.hasNext()) sb.append(","); } sb.append(")"); return sb.toString(); } /********************************************************************************* * {@code boolean assertEqualsSet(SetexpSet, SetactSet)} *********************************************************************************/ public static boolean assertEqualsSet(Set expSet, Set actSet) { if (actSet.equals(expSet)) { LOGGER.info("Sets are equal - match (Success)"); LOGGER.info("Expected: " + toStringSet(expSet)); LOGGER.info("Actual: " + toStringSet(actSet)); return true; } else { LOGGER.info("Sets are not equal - mismatch (Failure)"); LOGGER.warning("Expected: " + toStringSet(expSet)); LOGGER.warning("Actual: " + toStringSet(actSet)); return false; } } /********************************************************************************* * {@code void dumpMap(Map map, String msg)} *********************************************************************************/ public static void dumpMap(Map map, String msg) { LOGGER.info("*** Beg: Dumping Map contents ***"); if (msg != null) LOGGER.info("*** Message: " + msg); LOGGER.info("Map: {"); for (Map.Entry entry : map.entrySet()) { LOGGER.info( "\"" + entry.getKey() + "\":" + toStringJsonValue(entry.getValue())); } LOGGER.info("}"); LOGGER.info("*** End: Dumping Map contents ***"); } /********************************************************************************* * {@code void dumpMap(Map map)} *********************************************************************************/ public static void dumpMap(Map map) { dumpMap(map, null); } /********************************************************************************* * {@code String toStringMap(Map map)} *********************************************************************************/ public static String toStringMap(Map map) { StringBuilder sb = new StringBuilder(); sb.append("Map: {"); String comma = ""; for (Map.Entry entry : map.entrySet()) { sb.append(comma + "\"" + entry.getKey() + "\":" + toStringJsonValue(entry.getValue())); if (comma.equals("")) comma = ","; } sb.append("}"); return sb.toString(); } /********************************************************************************* * {@code boolean assertEqualsMap(MapexpMap, * MapactMap)} *********************************************************************************/ public static boolean assertEqualsMap(Map expMap, Map actMap) { if (actMap.equals(expMap)) { LOGGER.info("Maps are equal - match (Success)"); LOGGER.info("Expected: " + toStringMap(expMap)); LOGGER.info("Actual: " + toStringMap(actMap)); return true; } else { LOGGER.info("Maps are not equal - mismatch (Failure)"); LOGGER.warning("Expected: " + toStringMap(expMap)); LOGGER.warning("Actual: " + toStringMap(actMap)); return false; } } /********************************************************************************* * {@code assertEqualsMap2} *********************************************************************************/ public static boolean assertEqualsMap2(Map expMap, Map actMap) { LOGGER.info("*** Comparing Map expMap and Map actMap for equality ***"); LOGGER.info("Expected: " + toStringMap(expMap)); LOGGER.info("Actual: " + toStringMap(actMap)); LOGGER.info("Map expMap size should equal Map actMap size"); if (expMap.size() != actMap.size()) { LOGGER.warning("Map sizes are not equal: expMap size " + expMap.size() + ", actMap size " + actMap.size()); return false; } else { LOGGER.info("Map sizes are equal with size of " + expMap.size()); } for (Map.Entry entry : expMap.entrySet()) { String key = entry.getKey(); if (actMap.containsKey(key)) { if (expMap.get(key) != null && actMap.get(key) != null) { if (!expMap.get(key).equals(actMap.get(key))) { LOGGER.warning("key=" + key + ", expMap value " + expMap.get(key) + " does not equal actMap value " + actMap.get(key)); return false; } } } else { LOGGER.warning("actMap does not contain key " + key); return false; } } LOGGER.info("Maps expMap and actMap are equal."); return true; } /********************************************************************************* * {@code void dumpList(List list, String msg)} *********************************************************************************/ public static void dumpList(List list, String msg) { LOGGER.info("*** Beg: Dumping List contents ***"); if (msg != null) LOGGER.info("*** Message: " + msg); Iterator iter = list.iterator(); LOGGER.info("List: ["); while (iter.hasNext()) { LOGGER.info("" + toStringJsonValue(iter.next())); } LOGGER.info("]"); LOGGER.info("*** End: Dumping List contents ***"); } /********************************************************************************* * {@code void dumpList(List list)} *********************************************************************************/ public static void dumpList(List list) { dumpList(list, null); } /********************************************************************************* * {@code String toStringList(List list)} *********************************************************************************/ public static String toStringList(List list) { Iterator iter = list.iterator(); StringBuilder sb = new StringBuilder(); sb.append("List: ["); String comma = ""; while (iter.hasNext()) { sb.append(comma + toStringJsonValue(iter.next())); if (comma.equals("")) comma = ","; } sb.append("]"); return sb.toString(); } /********************************************************************************* * {@code boolean assertEqualsList(ListexpList, ListactList)} *********************************************************************************/ public static boolean assertEqualsList(List expList, List actList) { if (actList.equals(expList)) { LOGGER.info("Lists are equal - match (Success)"); LOGGER.info("Expected: " + toStringList(expList)); LOGGER.info("Actual: " + toStringList(actList)); return true; } else { LOGGER.info("Lists are not equal - mismatch (Failure)"); LOGGER.warning("Expected: " + toStringList(expList)); LOGGER.warning("Actual: " + toStringList(actList)); return false; } } /********************************************************************************* * {@code assertEqualsList2} *********************************************************************************/ public static boolean assertEqualsList2(List expList, List actList) { LOGGER.info( "*** Comparing contents of List expList and List actList for equality ***"); LOGGER.info("Expected: " + toStringList(expList)); LOGGER.info("Actual: " + toStringList(actList)); LOGGER.info("List expList size should equal List actList size"); if (expList.size() != actList.size()) { LOGGER.warning("List sizes are not equal: expList size " + expList.size() + ", actList size " + actList.size()); return false; } LOGGER.info("Compare Lists (all elements should MATCH)"); for (int i = 0; i < expList.size(); i++) { if (expList.get(i).equals(actList.get(i))) { LOGGER.info("expList element " + i + " matches actList element " + i); } else { LOGGER.warning( "expList element " + i + " does not match actList element " + i); LOGGER.warning("expList[" + i + "]=" + expList.get(i)); LOGGER.warning("actList[" + i + "]=" + actList.get(i)); return false; } } LOGGER.info("Lists are equal (Success)"); return true; } /********************************************************************************* * {@code void dumpIterator(Iterator iterator, String msg)} *********************************************************************************/ public static void dumpIterator(Iterator iterator, String msg) { LOGGER.info("*** Beg: Dumping Iterator contents ***"); if (msg != null) LOGGER.info("*** Message: " + msg); LOGGER.info("Iter: ["); while (iterator.hasNext()) { LOGGER.info("" + toStringJsonValue(iterator.next())); } LOGGER.info("]"); LOGGER.info("*** End: Dumping Iterator contents ***"); } /********************************************************************************* * {@code void dumpIterator(Iterator iterator)} *********************************************************************************/ public static void dumpIterator(Iterator iterator) { dumpIterator(iterator, null); } /********************************************************************************* * {@code String toStringIterator(Iterator iterator)} *********************************************************************************/ public static String toStringIterator(Iterator iter) { StringBuilder sb = new StringBuilder(); sb.append("Iterator: ["); while (iter.hasNext()) { sb.append(toStringJsonValue(iter.next())); if (iter.hasNext()) sb.append(","); } sb.append("]"); return sb.toString(); } /********************************************************************************* * {@code boolean assertEqualsIterator(IteratorexpIt, * IteratoractIt)} *********************************************************************************/ public static boolean assertEqualsIterator(Iterator expIt, Iterator actIt) { boolean pass = true; LOGGER.info( "*** Comparing contents of Iterator expIt and Iterator actIt for equality ***"); int i = 0; while (expIt.hasNext()) { if (!actIt.hasNext()) { LOGGER.warning( "Iterator expIt contains more elements than Iterator actIt"); return false; } ++i; JsonValue value1 = expIt.next(); JsonValue value2 = actIt.next(); if (assertEqualsJsonValues(value1, value2)) { LOGGER.info("Iterator expIt element " + i + " matches Iterator actIt element " + i); } else { LOGGER.warning("Iterator expIt element " + i + " does not match Iterator actIt element " + i); pass = false; } } if (actIt.hasNext()) { LOGGER.warning("Iterator actIt contains more elements than Iterator expIt"); return false; } if (pass) LOGGER.info("Iterators are equal (Success)"); else LOGGER.info("Iterators are not equal (Failure)"); return pass; } /********************************************************************************* * {@code boolean assertEqualsEmptyArrayList(List actual)} *********************************************************************************/ public static boolean assertEqualsEmptyArrayList(List actual) { if (actual.isEmpty()) { LOGGER.info("Array List is empty - expected"); return true; } else { LOGGER.warning("Array List is not empty - unexpected"); return false; } } /********************************************************************************* * {@code boolean assertEqualsEmptyObjectMap(Map actual)} *********************************************************************************/ public static boolean assertEqualsEmptyObjectMap( Map actual) { if (actual.isEmpty()) { LOGGER.info("Object Map is empty - expected"); return true; } else { LOGGER.warning("Object Map is not empty - unexpected"); return false; } } /********************************************************************************* * {@code boolean assertEqualsEmptyIterator(Map actual)} *********************************************************************************/ public static boolean assertEqualsEmptyIterator(Iterator actual) { if (!actual.hasNext()) { LOGGER.info("Iterator is empty - expected"); return true; } else { LOGGER.warning("Iterator is not empty - unexpected"); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonText(String expected, String actual)} *********************************************************************************/ public static boolean assertEqualsJsonText(String expected, String actual) { if (actual.equals(expected)) { LOGGER.info("JSON text match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("JSON text mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonArrays(JsonArray expected, JsonArray actual)} *********************************************************************************/ public static boolean assertEqualsJsonArrays(JsonArray expected, JsonArray actual) { if (actual.equals(expected)) { LOGGER.info("JsonArray match"); LOGGER.info("Expected: " + toStringJsonArray(expected)); LOGGER.info("Actual: " + toStringJsonArray(actual)); return true; } else { LOGGER.warning("JsonArray mismatch"); LOGGER.warning("Expected: " + toStringJsonArray(expected)); LOGGER.warning("Actual: " + toStringJsonArray(actual)); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonObjects(JsonObject expected, JsonObject actual)} *********************************************************************************/ public static boolean assertEqualsJsonObjects(JsonObject expected, JsonObject actual) { if (actual.equals(expected)) { LOGGER.info("JsonObject match"); LOGGER.info("Expected: " + toStringJsonObject(expected)); LOGGER.info("Actual: " + toStringJsonObject(actual)); return true; } else { LOGGER.warning("JsonObject mismatch"); LOGGER.warning("Expected: " + toStringJsonObject(expected)); LOGGER.warning("Actual: " + toStringJsonObject(actual)); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonNumbers(JsonNumber expected, JsonNumber actual)} *********************************************************************************/ public static boolean assertEqualsJsonNumbers(JsonNumber expected, JsonNumber actual) { boolean pass = true; if (actual.equals(expected)) { LOGGER.info("JsonNumber match"); LOGGER.info("Expected: " + toStringJsonNumber(expected)); LOGGER.info("Actual: " + toStringJsonNumber(actual)); return true; } else { LOGGER.warning("JsonNumber mismatch"); LOGGER.warning("Expected: " + toStringJsonNumber(expected)); LOGGER.warning("Actual: " + toStringJsonNumber(actual)); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonStrings(JsonString expected, JsonString actual)} *********************************************************************************/ public static boolean assertEqualsJsonStrings(JsonString expected, JsonString actual) { boolean pass = true; if (actual.equals(expected)) { LOGGER.info("JsonString match"); LOGGER.info("Expected: " + toStringJsonString(expected)); LOGGER.info("Actual: " + toStringJsonString(actual)); return true; } else { LOGGER.warning("JsonString mismatch"); LOGGER.warning("Expected: " + toStringJsonString(expected)); LOGGER.warning("Actual: " + toStringJsonString(actual)); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonValues(JsonValue expected, JsonValue actual)} *********************************************************************************/ public static boolean assertEqualsJsonValues(JsonValue expected, JsonValue actual) { boolean pass = true; // Comparing JsonNumbers if (expected instanceof JsonNumber) { if (!(actual instanceof JsonNumber)) { LOGGER.warning("expected type does not match actual type"); LOGGER.warning("expected=" + toStringJsonValue(expected)); LOGGER.warning("actual= " + toStringJsonValue(actual)); pass = false; } else { pass = assertEqualsJsonNumbers((JsonNumber) expected, (JsonNumber) actual); } // Comparing JsonStrings } else if (expected instanceof JsonString) { if (!(actual instanceof JsonString)) { LOGGER.warning("expected type does not match actual type"); LOGGER.warning("expected=" + toStringJsonValue(expected)); LOGGER.warning("actual= " + toStringJsonValue(actual)); pass = false; } else { pass = assertEqualsJsonStrings((JsonString) expected, (JsonString) actual); } // Comparing JsonArrays } else if (expected instanceof JsonArray) { if (!(actual instanceof JsonArray)) { LOGGER.warning("expected type does not match actual type"); LOGGER.warning("expected=" + toStringJsonValue(expected)); LOGGER.warning("actual= " + toStringJsonValue(actual)); pass = false; } else { pass = assertEqualsJsonArrays((JsonArray) expected, (JsonArray) actual); } // Comparing JsonObjects } else if (expected instanceof JsonObject) { if (!(actual instanceof JsonObject)) { LOGGER.warning("expected type does not match actual type"); LOGGER.warning("expected=" + toStringJsonValue(expected)); LOGGER.warning("actual= " + toStringJsonValue(actual)); pass = false; } else { pass = assertEqualsJsonObjects((JsonObject) expected, (JsonObject) actual); } // Comparing JsonValues } else if (expected.equals(actual)) { LOGGER.info("expected matches actual"); LOGGER.info("expected=" + toStringJsonValue(expected)); LOGGER.info("actual= " + toStringJsonValue(actual)); } else { LOGGER.warning("expected does not match actual"); LOGGER.warning("expected=" + toStringJsonValue(expected)); LOGGER.warning("actual= " + toStringJsonValue(actual)); pass = false; } return pass; } /********************************************************************************* * {@code boolean assertEqualsJsonValueType(JsonValue.ValueType * expected,JsonValue.ValueType actual)} *********************************************************************************/ public static boolean assertEqualsJsonValueType(JsonValue.ValueType expected, JsonValue.ValueType actual) { if (actual == expected) { LOGGER.info("JsonValue.ValueType match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("JsonValue.ValueType mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonNumberType(boolean expected,boolean actual)} *********************************************************************************/ public static boolean assertEqualsJsonNumberType(boolean expected, boolean actual) { if (actual == expected) { LOGGER.info("Json NumberType match"); LOGGER.info("Expected: " + toStringJsonNumberType(expected)); LOGGER.info("Actual: " + toStringJsonNumberType(actual)); return true; } else { LOGGER.warning("Json NumberType mismatch"); LOGGER.warning("Expected: " + toStringJsonNumberType(expected)); LOGGER.warning("Actual: " + toStringJsonNumberType(actual)); return false; } } /********************************************************************************* * {@code boolean assertEqualsJsonNumberTypes(boolean expected[],boolean actual)} *********************************************************************************/ public static boolean assertEqualsJsonNumberTypes(boolean expected[], boolean actual) { for (int i = 0; i < expected.length; i++) { if (actual == expected[i]) { LOGGER.info("Json NumberType match"); LOGGER.info("Expected: " + toStringJsonNumberType(expected[i])); LOGGER.info("Actual: " + toStringJsonNumberType(actual)); return true; } } LOGGER.warning("Json NumberType mismatch"); LOGGER.warning("Expected: " + toStringJsonNumberTypes(expected)); LOGGER.warning("Actual: " + toStringJsonNumberType(actual)); return false; } /********************************************************************************* * {@code String toStringJsonNumberType(boolean numberType)} *********************************************************************************/ public static String toStringJsonNumberType(boolean numberType) { if (numberType == INTEGRAL) return "INTEGRAL"; else return "NON_INTEGRAL"; } /********************************************************************************* * {@code String toStringJsonNumberTypes(boolean expected[])} *********************************************************************************/ public static String toStringJsonNumberTypes(boolean expected[]) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < expected.length; i++) { sb.append("" + toStringJsonNumberType(expected[i])); if (i + 1 < expected.length) sb.append("|"); } return sb.toString(); } /********************************************************************************* * {@code boolean assertEquals(Object, Object)} *********************************************************************************/ public static boolean assertEquals(Object expected, Object actual) { if (actual.equals(expected)) { LOGGER.info("Object match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("Object mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(boolean, boolean)} *********************************************************************************/ public static boolean assertEquals(boolean expected, boolean actual) { if (actual == expected) { LOGGER.info("boolean match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("boolean mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(short, short)} *********************************************************************************/ public static boolean assertEquals(short expected, short actual) { if (actual == expected) { LOGGER.info("short match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("short mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(int, int)} *********************************************************************************/ public static boolean assertEquals(int expected, int actual) { if (actual == expected) { LOGGER.info("int match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("int mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(long, long)} *********************************************************************************/ public static boolean assertEquals(long expected, long actual) { if (actual == expected) { LOGGER.info("long match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("long mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(float, float)} *********************************************************************************/ public static boolean assertEquals(float expected, float actual) { if (actual == expected) { LOGGER.info("float match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("float mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(double, double)} *********************************************************************************/ public static boolean assertEquals(double expected, double actual) { if (actual == expected) { LOGGER.info("double match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("double mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(BigDecimal, BigDecimal)} *********************************************************************************/ public static boolean assertEquals(BigDecimal expected, BigDecimal actual) { if (actual.equals(expected)) { LOGGER.info("BigDecimal match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("BigDecimal mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(BigInteger, BigInteger)} *********************************************************************************/ public static boolean assertEquals(BigInteger expected, BigInteger actual) { if (actual.equals(expected)) { LOGGER.info("BigInteger match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("BigInteger mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(String, String)} *********************************************************************************/ public static boolean assertEquals(String expected, String actual) { if (actual.equals(expected)) { LOGGER.info("String match"); LOGGER.info("Expected: " + expected); LOGGER.info("Actual: " + actual); return true; } else { LOGGER.warning("String mismatch"); LOGGER.warning("Expected: " + expected); LOGGER.warning("Actual: " + actual); return false; } } /********************************************************************************* * {@code boolean assertEquals(JsonValue, JsonValue)} *********************************************************************************/ public static boolean assertEquals(JsonValue expected, JsonValue actual) { if (actual.equals(expected)) { LOGGER.info("JsonValue match"); LOGGER.info("Expected: " + toStringJsonValue(expected)); LOGGER.info("Actual: " + toStringJsonValue(actual)); return true; } else { LOGGER.warning("JsonValue mismatch"); LOGGER.warning("Expected: " + toStringJsonValue(expected)); LOGGER.warning("Actual: " + toStringJsonValue(actual)); return false; } } /********************************************************************************* * {@code String getNumberTypeString(boolean numberType)} *********************************************************************************/ public static String getNumberTypeString(boolean numberType) { if (numberType == INTEGRAL) return "INTEGRAL"; else return "NON_INTEGRAL"; } /********************************************************************************* * {@code boolean getNumberType(String numberType)} *********************************************************************************/ public static boolean getNumberType(String numberType) { if (numberType.equals("INTEGRAL")) return INTEGRAL; else return NON_INTEGRAL; } /********************************************************************************* * {@code String getValueTypeString(JsonValue.ValueType valueType)} *********************************************************************************/ public static String getValueTypeString(JsonValue.ValueType valueType) { switch (valueType) { case ARRAY: return "ARRAY"; case FALSE: return "FALSE"; case NULL: return "NULL"; case NUMBER: return "NUMBER"; case OBJECT: return "OBJECT"; case STRING: return "STRING"; case TRUE: return "TRUE"; default: return null; } } /********************************************************************************* * {@code JsonValue.ValueType getValueType(String valueType)} *********************************************************************************/ public static JsonValue.ValueType getValueType(String valueType) { if (valueType.equals("ARRAY")) return JsonValue.ValueType.ARRAY; if (valueType.equals("FALSE")) return JsonValue.ValueType.FALSE; if (valueType.equals("NULL")) return JsonValue.ValueType.NULL; if (valueType.equals("NUMBER")) return JsonValue.ValueType.NUMBER; if (valueType.equals("OBJECT")) return JsonValue.ValueType.OBJECT; if (valueType.equals("STRING")) return JsonValue.ValueType.STRING; if (valueType.equals("TRUE")) return JsonValue.ValueType.TRUE; else return null; } /********************************************************************************* * {@code void dumpEventType(JsonParser.Event eventType)} *********************************************************************************/ public static void dumpEventType(JsonParser.Event eventType) { LOGGER.info("JsonParser.Event=" + eventType); } /********************************************************************************* * {@code getEventTypeString(JsonParser.Event eventType)} *********************************************************************************/ public static String getEventTypeString(JsonParser.Event eventType) { switch (eventType) { case START_ARRAY: return "START_ARRAY"; case START_OBJECT: return "START_OBJECT"; case KEY_NAME: return "KEY_NAME"; case VALUE_STRING: return "VALUE_STRING"; case VALUE_NUMBER: return "VALUE_NUMBER"; case VALUE_TRUE: return "VALUE_TRUE"; case VALUE_FALSE: return "VALUE_FALSE"; case VALUE_NULL: return "VALUE_NULL"; case END_OBJECT: return "END_OBJECT"; case END_ARRAY: return "END_ARRAY"; default: return null; } } /********************************************************************************* * {@code JsonParser.Event getEventType(String eventType)} *********************************************************************************/ public static JsonParser.Event getEventType(String eventType) { if (eventType.equals("START_ARRAY")) return JsonParser.Event.START_ARRAY; if (eventType.equals("START_OBJECT")) return JsonParser.Event.START_OBJECT; if (eventType.equals("KEY_NAME")) return JsonParser.Event.KEY_NAME; if (eventType.equals("VALUE_STRING")) return JsonParser.Event.VALUE_STRING; if (eventType.equals("VALUE_NUMBER")) return JsonParser.Event.VALUE_NUMBER; if (eventType.equals("VALUE_TRUE")) return JsonParser.Event.VALUE_TRUE; if (eventType.equals("VALUE_FALSE")) return JsonParser.Event.VALUE_FALSE; if (eventType.equals("VALUE_NULL")) return JsonParser.Event.VALUE_NULL; if (eventType.equals("END_OBJECT")) return JsonParser.Event.END_OBJECT; if (eventType.equals("END_ARRAY")) return JsonParser.Event.END_ARRAY; else return null; } /********************************************************************************* * {@code String getConfigName(String configValue)} *********************************************************************************/ public static String getConfigName(String configValue) { if (configValue.equals(JsonGenerator.PRETTY_PRINTING)) return "JsonGenerator.PRETTY_PRINTING"; else if (configValue.equals(JSONP_Util.FOO_CONFIG)) return "JSONP_Util.FOO_CONFIG"; else return null; } /********************************************************************************* * {@code String getConfigValue(String configProp)} *********************************************************************************/ public static String getConfigValue(String configProp) { if (configProp.equals("JsonGenerator.PRETTY_PRINING")) return JsonGenerator.PRETTY_PRINTING; else if (configProp.equals("JSONP_Util.FOO_CONFIG")) return JSONP_Util.FOO_CONFIG; else return null; } /********************************************************************************* * {@code void dumpConfigMap(Map map, String msg)} *********************************************************************************/ public static void dumpConfigMap(Map map, String msg) { LOGGER.info("*** Beg: Dumping Config Map contents ***"); if (msg != null) LOGGER.info("*** Message: " + msg); for (Map.Entry entry : map.entrySet()) { LOGGER.info("\"" + entry.getKey() + "\":" + entry.getValue()); } LOGGER.info("*** End: Dumping Config Map contents ***"); } /********************************************************************************* * {@code void dumpConfigMap(Map map)} *********************************************************************************/ public static void dumpConfigMap(Map map) { dumpConfigMap(map, null); } /********************************************************************************* * {@code boolean doConfigCheck(Map config, int expectedSize)} *********************************************************************************/ public static boolean doConfigCheck(Map config, int expectedSize) { return doConfigCheck(config, expectedSize, null); } public static boolean doConfigCheck(Map config, int expectedSize, String[] expectedProps) { boolean pass = true; dumpConfigMap(config); LOGGER.info("Checking factory configuration property size"); if (config.size() != expectedSize) { LOGGER.warning("Expecting no of properties=" + expectedSize + ", got=" + config.size()); pass = false; } else { LOGGER.info("Expecting no of properties=" + expectedSize + ", got=" + config.size()); } if (expectedSize != 0 && expectedProps != null) { LOGGER.info("Checking factory configuration property name and value"); for (int i = 0; i < expectedProps.length; i++) { if (config.containsKey(expectedProps[i])) { LOGGER.info("Does contain key: " + expectedProps[i] + " - expected."); if (!JSONP_Util.assertEquals(true, config.get(expectedProps[i]))) { pass = false; } } else { LOGGER.warning( "Does not contain key: " + expectedProps[i] + " - unexpected."); pass = false; } } } return pass; } /********************************************************************************* * {@code boolean isEmptyConfig(Map config)} *********************************************************************************/ public boolean isEmptyConfig(Map config) { LOGGER.info("isEmptyConfig"); return config.isEmpty(); } /********************************************************************************* * {@code Map getEmptyConfig()} *********************************************************************************/ public static Map getEmptyConfig() { LOGGER.info("getEmptyConfig"); Map config = new HashMap(); return config; } /********************************************************************************* * {@code Map getPrettyPrintingConfig()} *********************************************************************************/ public static Map getPrettyPrintingConfig() { LOGGER.info("getPrettyPrintConfig"); Map config = new HashMap(); LOGGER.info("Added property: JsonGenerator.PRETTY_PRINTING"); config.put(JsonGenerator.PRETTY_PRINTING, true); return config; } /********************************************************************************* * {@code Map getFooConfig()} *********************************************************************************/ public static Map getFooConfig() { LOGGER.info("getFooConfig"); Map config = new HashMap(); LOGGER.info("Added property: JSONP_Util.FOO_CONFIG"); config.put(JSONP_Util.FOO_CONFIG, true); return config; } /********************************************************************************* * {@code Map getAllConfig()} *********************************************************************************/ public static Map getAllConfig() { LOGGER.info("getAllConfig"); Map config = new HashMap(); LOGGER.info("Added property: JsonGenerator.PRETTY_PRINTING"); config.put(JsonGenerator.PRETTY_PRINTING, true); LOGGER.info("Added property: JSONP_Util.FOO_CONFIG"); config.put(JSONP_Util.FOO_CONFIG, true); return config; } /********************************************************************************* * {@code JsonObject createJsonObjectFromString(String jsonObjData)} *********************************************************************************/ public static JsonObject createJsonObjectFromString(String jsonObjData) { JsonReader reader = null; JsonObject object = null; try { reader = Json.createReader(new StringReader(jsonObjData)); object = reader.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) reader.close(); } return object; } /********************************************************************************* * {@code JsonArray createJsonArrayFromString(String jsonArrData)} *********************************************************************************/ public static JsonArray createJsonArrayFromString(String jsonArrData) { JsonReader reader = null; JsonArray array = null; try { reader = Json.createReader(new StringReader(jsonArrData)); array = reader.readArray(); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) reader.close(); } return array; } /********************************************************************************* * {@code void writeJsonObjectFromString(JsonWriter writer, String jsonObjData)} *********************************************************************************/ public static void writeJsonObjectFromString(JsonWriter writer, String jsonObjData) { try { JsonObject jsonObject = createJsonObjectFromString(jsonObjData); writer.writeObject(jsonObject); writer.close(); } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); } } /********************************************************************************* * {@code void writeJsonArrayFromString(JsonWriter writer, String jsonArrData)} *********************************************************************************/ public static void writeJsonArrayFromString(JsonWriter writer, String jsonArrData) { try { JsonArray jsonArray = createJsonArrayFromString(jsonArrData); writer.writeArray(jsonArray); writer.close(); } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); } } /********************************************************************************* * {@code void testKeyStringValue(JsonParser parser, String name, String value)} *********************************************************************************/ public static void testKeyStringValue(JsonParser parser, String name, String value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_STRING) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_STRING) + ", got event: " + getEventTypeString(e)); parseErrs++; } String keyvalue = parser.getString(); if (!keyvalue.equals(value)) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testKeyIntegerValue(JsonParser parser, String name, int value)} *********************************************************************************/ public static void testKeyIntegerValue(JsonParser parser, String name, int value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } int keyvalue = parser.getInt(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testKeyDoubleValue(JsonParser parser, String name, double value)} *********************************************************************************/ public static void testKeyDoubleValue(JsonParser parser, String name, double value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } double keyvalue = parser.getBigDecimal().doubleValue(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testKeyLongValue(JsonParser parser, String name, long value)} *********************************************************************************/ public static void testKeyLongValue(JsonParser parser, String name, long value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } long keyvalue = parser.getLong(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testKeyBigDecimalValue(JsonParser parser, String name, BigDecimal * value)} *********************************************************************************/ public static void testKeyBigDecimalValue(JsonParser parser, String name, BigDecimal value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } BigDecimal keyvalue = parser.getBigDecimal(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testKeyTrueValue(JsonParser parser, String name)} *********************************************************************************/ public static void testKeyTrueValue(JsonParser parser, String name) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_TRUE) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_TRUE) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } } /********************************************************************************* * {@code void testKeyFalseValue(JsonParser parser, String name)} *********************************************************************************/ public static void testKeyFalseValue(JsonParser parser, String name) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_FALSE) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_FALSE) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } } /********************************************************************************* * {@code void testKeyNullValue(JsonParser parser, String name)} *********************************************************************************/ public static void testKeyNullValue(JsonParser parser, String name) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.VALUE_NULL) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NULL) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } } /********************************************************************************* * {@code void testKeyStartObjectValue(JsonParser parser, String name)} *********************************************************************************/ public static void testKeyStartObjectValue(JsonParser parser, String name) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.START_OBJECT) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.START_OBJECT) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } } /********************************************************************************* * {@code void testKeyStartArrayValue(JsonParser parser, String name)} *********************************************************************************/ public static void testKeyStartArrayValue(JsonParser parser, String name) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.KEY_NAME) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyname = parser.getString(); if (!name.equals(keyname)) { LOGGER.warning("Expected keyname: " + name + ", got keyname: " + keyname); parseErrs++; } else { LOGGER.info("Got expected keyname: " + keyname); } if (!checkNextParserEvent(parser)) return; e = parser.next(); if (e != JsonParser.Event.START_ARRAY) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.START_ARRAY) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } } /********************************************************************************* * {@code boolean checkNextParserEvent(JsonParser parser)} *********************************************************************************/ public static boolean checkNextParserEvent(JsonParser parser) { if (!parser.hasNext()) { LOGGER.warning("no next parser event found - unexpected"); parseErrs++; return false; } else return true; } /********************************************************************************* * {@code JsonParser.Event getNextParserEvent(JsonParser parser)} *********************************************************************************/ public static JsonParser.Event getNextParserEvent(JsonParser parser) { if (parser.hasNext()) return parser.next(); else return null; } /********************************************************************************* * {@code JsonParser.Event getNextSpecificParserEvent(JsonParser parser, * JsonParser.Event thisEvent)} *********************************************************************************/ public static JsonParser.Event getNextSpecificParserEvent(JsonParser parser, JsonParser.Event thisEvent) { while (parser.hasNext()) { JsonParser.Event event = parser.next(); if (event == thisEvent) return event; } return null; } /********************************************************************************* * {@code void testEventType(JsonParser parser, JsonParser.Event expEvent)} *********************************************************************************/ public static void testEventType(JsonParser parser, JsonParser.Event expEvent) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != expEvent) { LOGGER.warning("Expected event: " + getEventTypeString(expEvent) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } } /********************************************************************************* * {@code void testStringValue(JsonParser parser, String value)} *********************************************************************************/ public static void testStringValue(JsonParser parser, String value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.VALUE_STRING) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_STRING) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } String keyvalue = parser.getString(); if (!keyvalue.equals(value)) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testIntegerValue(JsonParser parser, int value)} *********************************************************************************/ public static void testIntegerValue(JsonParser parser, int value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } int keyvalue = parser.getInt(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testDoubleValue(JsonParser parser, double value)} *********************************************************************************/ public static void testDoubleValue(JsonParser parser, double value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } double keyvalue = parser.getBigDecimal().doubleValue(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testLongValue(JsonParser parser, long value)} *********************************************************************************/ public static void testLongValue(JsonParser parser, long value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } long keyvalue = parser.getLong(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testBigDecimalValue(JsonParser parser, BigDecimal value)} *********************************************************************************/ public static void testBigDecimalValue(JsonParser parser, BigDecimal value) { if (!checkNextParserEvent(parser)) return; JsonParser.Event e = parser.next(); if (e != JsonParser.Event.VALUE_NUMBER) { LOGGER.warning( "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + ", got event: " + getEventTypeString(e)); parseErrs++; } else { LOGGER.info("Got expected event: " + getEventTypeString(e)); } BigDecimal keyvalue = parser.getBigDecimal(); if (keyvalue != value) { LOGGER.warning( "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); parseErrs++; } else { LOGGER.info("Got expected keyvalue: " + keyvalue); } } /********************************************************************************* * {@code void testTrueValue(JsonParser parser, JsonParser.Event expEvent)} *********************************************************************************/ public static void testTrueValue(JsonParser parser, JsonParser.Event expEvent) { testEventType(parser, expEvent); } /********************************************************************************* * {@code void testFalseValue(JsonParser parser, JsonParser.Event expEvent)} *********************************************************************************/ public static void testFalseValue(JsonParser parser, JsonParser.Event expEvent) { testEventType(parser, expEvent); } /********************************************************************************* * {@code void testNullValue(JsonParser parser, JsonParser.Event expEvent)} *********************************************************************************/ public static void testNullValue(JsonParser parser, JsonParser.Event expEvent) { testEventType(parser, expEvent); } /********************************************************************************* * {@code resetParseErrs()} *********************************************************************************/ public static void resetParseErrs() { parseErrs = 0; } /********************************************************************************* * {@code int getParseErrs()} *********************************************************************************/ public static int getParseErrs() { return parseErrs; } /********************************************************************************* * {@code String convertUnicodeCharToString(Char c)} * * Convert unicode to string value of form U+NNNN where NNNN are 4 hex digits * * Use a binary or with hex value '0x10000' when converting unicode char to * hex string and remove 1st char to get the 4 hex digits we need. *********************************************************************************/ public static String convertUnicodeCharToString(char c) { return "\\u" + Integer.toHexString((int) c | 0x10000).substring(1); } /********************************************************************************* * {@code boolean isUnicodeControlChar(Char c)} * * The following unicode control chars: * * U+0000 - U+001F and U+007F U+0080 - U+009F *********************************************************************************/ public static boolean isUnicodeControlChar(char c) { if ((c >= '\u0000' && c <= '\u001F') || (c == '\u007F') || (c >= '\u0080' && c <= '\u009F')) return true; else return false; } /********************************************************************************* * {@code void writeStringToFile(String string, String file, String encoding)} *********************************************************************************/ public static void writeStringToFile(String string, String file, String encoding) { try { FileOutputStream fos = new FileOutputStream(file); Writer out = new OutputStreamWriter(fos, encoding); out.write(string); out.close(); } catch (IOException e) { e.printStackTrace(); } } /********************************************************************************* * {@code String readStringFromFile(String file, String encoding)} *********************************************************************************/ public static String readStringFromFile(String file, String encoding) { StringBuffer buffer = new StringBuffer(); try { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, encoding); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char) ch); } in.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } /********************************************************************************* * {@code void writeStringToStream(String string, OutputStream os, String encoding)} *********************************************************************************/ public static void writeStringToStream(String string, OutputStream os, String encoding) { try { Writer out = new OutputStreamWriter(os, encoding); out.write(string); out.close(); } catch (IOException e) { e.printStackTrace(); } } /********************************************************************************* * {@code String readStringFromStream(InputStream is, String encoding)} *********************************************************************************/ public static String readStringFromStream(InputStream is, String encoding) { StringBuffer buffer = new StringBuffer(); try { InputStreamReader isr = new InputStreamReader(is, encoding); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char) ch); } in.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } /********************************************************************************* * {@code void writeStringToFile(String string, String file, Charset charset)} *********************************************************************************/ public static void writeStringToFile(String string, String file, Charset charset) { try { FileOutputStream fos = new FileOutputStream(file); Writer out = new OutputStreamWriter(fos, charset); out.write(string); out.close(); } catch (IOException e) { e.printStackTrace(); } } /********************************************************************************* * {@code String readStringFromFile(String file, Charset charset)} *********************************************************************************/ public static String readStringFromFile(String file, Charset charset) { StringBuffer buffer = new StringBuffer(); try { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, charset); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char) ch); } in.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } /********************************************************************************* * {@code void writeStringToStream(String string, OutputStream os, Charset charset)} *********************************************************************************/ public static void writeStringToStream(String string, OutputStream os, Charset charset) { try { Writer out = new OutputStreamWriter(os, charset); out.write(string); out.close(); } catch (IOException e) { e.printStackTrace(); } } /********************************************************************************* * {@code String readStringFromStream(InputStream is, Charset charset)} *********************************************************************************/ public static String readStringFromStream(InputStream is, Charset charset) { StringBuffer buffer = new StringBuffer(); try { InputStreamReader isr = new InputStreamReader(is, charset); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char) ch); } in.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } /********************************************************************************* * {@code Charset getCharset(String encoding)} *********************************************************************************/ public static Charset getCharset(String encoding) { Charset cs = null; try { cs = Charset.forName(encoding); } catch (Exception e) { e.printStackTrace(); } return cs; } /********************************************************************************* * {@code void dumpLocation(JsonLocation location)} *********************************************************************************/ public static void dumpLocation(JsonLocation location) { if (location != null) { LOGGER.info("JsonLocation info: lineNumber=" + location.getLineNumber() + ", columnNumber=" + location.getColumnNumber() + ", streamOffset=" + location.getStreamOffset()); } else { LOGGER.info("JsonLocation is null - no location info"); } } /********************************************************************************* * {@code void dumpLocation(JsonParser parser)} *********************************************************************************/ public static void dumpLocation(JsonParser parser) { dumpLocation(parser.getLocation()); } /********************************************************************************* * {@code boolean assertEquals(JsonLocation, JsonLocation)} *********************************************************************************/ public static boolean assertEquals(JsonLocation expLoc, JsonLocation actLoc) { if (expLoc.getLineNumber() == actLoc.getLineNumber() && expLoc.getColumnNumber() == actLoc.getColumnNumber() && expLoc.getStreamOffset() == actLoc.getStreamOffset()) { LOGGER.info("JsonLocations equal - match (Success)"); LOGGER.info( "Expected: JsonLocation info: lineNumber=" + expLoc.getLineNumber() + ", columnNumber=" + expLoc.getColumnNumber() + ", streamOffset=" + expLoc.getStreamOffset()); LOGGER.info( "Actual: JsonLocation info: lineNumber=" + actLoc.getLineNumber() + ", columnNumber=" + actLoc.getColumnNumber() + ", streamOffset=" + actLoc.getStreamOffset()); return true; } else { LOGGER.warning("JsonLocations not equal - mismatch (Failure)"); LOGGER.warning( "Expected: JsonLocation info: lineNumber=" + expLoc.getLineNumber() + ", columnNumber=" + expLoc.getColumnNumber() + ", streamOffset=" + expLoc.getStreamOffset()); LOGGER.warning( "Actual: JsonLocation info: lineNumber=" + actLoc.getLineNumber() + ", columnNumber=" + actLoc.getColumnNumber() + ", streamOffset=" + actLoc.getStreamOffset()); return false; } } /********************************************************************************* * {@code void addFileToClassPath(String s)} *********************************************************************************/ public static void addFileToClassPath(String s) throws Exception { addFileToClassPath(new File(s)); } /********************************************************************************* * {@code void addFileToClassPath(File f)} *********************************************************************************/ public static void addFileToClassPath(File f) throws Exception { addURLToClassPath((f.toURI()).toURL()); } /********************************************************************************* * {@code void addURLToClassPath(URL url)} *********************************************************************************/ public static void addURLToClassPath(URL url) throws Exception { LOGGER.info("addURLToClassPath-> " + url.toString()); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader .getSystemClassLoader(); try { Class urlClassLoaderClass = URLClassLoader.class; Method method = urlClassLoaderClass.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(urlClassLoader, new Object[] { url }); } catch (Throwable t) { t.printStackTrace(); throw new IOException("Error, could not add URL to system classloader"); } } /********************************************************************************* * {@code JsonArray buildJsonArrayFooBar} *********************************************************************************/ public static JsonArray buildJsonArrayFooBar() { try { JsonArray jsonArray = Json.createArrayBuilder().add("foo").add("bar") .build(); return jsonArray; } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); return null; } } public static final String JSONARRAYFOOBAR = "[\"foo\",\"bar\"]"; /********************************************************************************* * {@code JsonObject buildJsonObjectFooBar()} *********************************************************************************/ public static JsonObject buildJsonObjectFooBar() { try { JsonObject jsonObject = Json.createObjectBuilder().add("foo", "bar") .build(); return jsonObject; } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); return null; } } public static final String JSONOBJECTFOOBAR = "{\"foo\":\"bar\"}"; /********************************************************************************* * {@code JsonObject createSampleJsonObject()} * * Assertion ids covered: 400/401/403/404/406/408/409 *********************************************************************************/ public static JsonObject createSampleJsonObject() throws Exception { JsonObject object = Json.createObjectBuilder().add("firstName", "John") .add("lastName", "Smith").add("age", 25).add("elderly", JsonValue.FALSE) .add("patriot", JsonValue.TRUE) .add("address", Json.createObjectBuilder().add("streetAddress", "21 2nd Street") .add("city", "New York").add("state", "NY") .add("postalCode", "10021")) .add("phoneNumber", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder().add("type", "cell") .add("number", "646 555-4567"))) .add("objectOfFooBar", Json.createObjectBuilder() .add("objectFooBar", buildJsonObjectFooBar()) .add("arrayFooBar", buildJsonArrayFooBar())) .add("arrayOfFooBar", Json.createArrayBuilder() .add(buildJsonObjectFooBar()).add(buildJsonArrayFooBar())) .build(); return object; } /********************************************************************************* * {@code EXPECTED_SAMPLEJSONOBJECT_TEXT} Constant defining expected Json text output * of above sample JsonObject *********************************************************************************/ public final static String EXPECTED_SAMPLEJSONOBJECT_TEXT = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,\"elderly\":false,\"patriot\":true," + "\"address\":{\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\",\"state\":\"NY\"," + "\"postalCode\":\"10021\"},\"phoneNumber\":[{\"type\":\"home\",\"number\":\"212 555-1234\"}," + "{\"type\":\"cell\",\"number\":\"646 555-4567\"}],\"objectOfFooBar\":{\"objectFooBar\":" + "{\"foo\":\"bar\"},\"arrayFooBar\":[\"foo\",\"bar\"]},\"arrayOfFooBar\":[{\"foo\":\"bar\"}," + "[\"foo\",\"bar\"]]}"; /********************************************************************************* * {@code JsonObject createSampleJsonObject2()} *********************************************************************************/ public static JsonObject createSampleJsonObject2() throws Exception { JsonObject object = Json.createObjectBuilder().add("firstName", "John") .add("lastName", "Smith").add("age", 25).add("elderly", JsonValue.FALSE) .add("patriot", JsonValue.TRUE) .add("address", Json.createObjectBuilder().add("streetAddress", "21 2nd Street") .add("city", "New York").add("state", "NY") .add("postalCode", "10021")) .add("phoneNumber", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder().add("type", "cell") .add("number", "535 444-1234"))) .build(); return object; } /********************************************************************************* * {@code JsonArray createSampleJsonArray()} * * Assertion ids covered: 400/401/402/403/404/406/409 *********************************************************************************/ public static JsonArray createSampleJsonArray() throws Exception { // Indices JsonArray array = Json.createArrayBuilder().add(Json.createObjectBuilder() // 0 .add("name1", "value1").add("name2", "value2")).add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL) // 1,2,3 .add(100).add(200L).add("string") // 4,5,6 .add(BigDecimal.valueOf(123456789)).add(new BigInteger("123456789"))// 7,8 .add(Json.createObjectBuilder() // 9 .add("name3", "value3").add("name4", "value4")) .add(true).add(false).addNull() // 10,11,12 .add(Json.createArrayBuilder() // 13 .add(2).add(4)) .add(Json.createObjectBuilder() // 14 .add("objectFooBar", buildJsonObjectFooBar()) .add("arrayFooBar", buildJsonArrayFooBar())) .add(Json.createArrayBuilder() // 15 .add(buildJsonObjectFooBar()).add(buildJsonArrayFooBar())) .build(); return array; } /********************************************************************************* * {@code EXPECTED_SAMPLEJSONARRAY_TEXT} Constant defining expected Json text output * of above sample JsonArray *********************************************************************************/ public final static String EXPECTED_SAMPLEJSONARRAY_TEXT = "[{\"name1\":\"value1\",\"name2\":\"value2\"},true,false,null,100,200,\"string\",123456789,123456789," + "{\"name3\":\"value3\",\"name4\":\"value4\"},true,false,null,[2,4],{\"objectFooBar\":" + "{\"foo\":\"bar\"},\"arrayFooBar\":[\"foo\",\"bar\"]},[{\"foo\":\"bar\"},[\"foo\",\"bar\"]]]"; /********************************************************************************* * {@code JsonArray createSampleJsonArray2()} *********************************************************************************/ public static JsonArray createSampleJsonArray2() throws Exception { // Indices JsonArray array = Json.createArrayBuilder().add(Json.createObjectBuilder() // 0 .add("name1", "value1").add("name2", "value2")).add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL) // 1,2,3 .add(Integer.MAX_VALUE).add(Long.MAX_VALUE).add("string") // 4,5,6 .add(Json.createObjectBuilder() // 7 .add("name3", "value3").add("name4", "value4")) .add(true).add(false).addNull() // 8,9,10 .add(Json.createArrayBuilder() // 11 .add(1).add(3)) .build(); return array; } } MyBufferedInputStream.java000066400000000000000000000044201451447132700342070ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.common; import java.io.*; import java.util.logging.Logger; // A wrapper class to BufferedInputStream class used to inject IOException errors // when the throwIOException instance variable is set. All methods delegate // to the parent super class and check whether or not to throw an IOException // before delegation. public class MyBufferedInputStream extends BufferedInputStream { private static final Logger LOGGER = Logger.getLogger(MyBufferedInputStream.class.getName()); private boolean throwIOException = false; public MyBufferedInputStream(InputStream in) { super(in); } public MyBufferedInputStream(InputStream in, int sz) { super(in, sz); } public MyBufferedInputStream(InputStream in, boolean throwIOException) { super(in); this.throwIOException = throwIOException; } private void checkToTripIOException() throws IOException { if (throwIOException) { LOGGER.info( "MyBufferedInputStream->checkToTripIOException: *** tripping an IOException ***"); throw new IOException("tripping an IOException"); } } public void setThrowIOException(boolean throwIOException) { this.throwIOException = throwIOException; } public int read() throws IOException { checkToTripIOException(); int c = super.read(); return c; } public int read(byte[] b, int off, int len) throws IOException { checkToTripIOException(); int c = super.read(b, off, len); return c; } public void close() throws IOException { checkToTripIOException(); super.close(); } } MyBufferedReader.java000066400000000000000000000047141451447132700331440ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.common; import java.io.*; import java.util.logging.Logger; // A wrapper class to BufferedReader class used to inject IOException errors // when the throwIOException instance variable is set. All methods delegate // to the parent super class and check whether or not to throw an IOException // before delegation. public class MyBufferedReader extends BufferedReader { private static final Logger LOGGER = Logger.getLogger(MyBufferedReader.class.getName()); private boolean throwIOException; public MyBufferedReader(Reader in) { super(in); } public MyBufferedReader(Reader in, int sz) { super(in, sz); } public MyBufferedReader(Reader in, int sz, boolean throwIOException) { super(in, sz); this.throwIOException = throwIOException; } private void checkToTripIOException() throws IOException { if (throwIOException) { LOGGER.info("*** tripping an IOException ***"); throw new IOException("tripping an IOException"); } } public void setThrowIOException(boolean throwIOException) { this.throwIOException = throwIOException; } public int read() throws IOException { checkToTripIOException(); return super.read(); } public int read(char[] cbuf, int off, int len) throws IOException { checkToTripIOException(); return super.read(cbuf, off, len); } public String readLine() throws IOException { checkToTripIOException(); return super.readLine(); } public boolean ready() throws IOException { checkToTripIOException(); return super.ready(); } public void reset() throws IOException { checkToTripIOException(); super.reset(); } public void close() throws IOException { checkToTripIOException(); super.close(); } } MyBufferedWriter.java000066400000000000000000000051651451447132700332170ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.common; import java.io.*; import java.util.logging.Logger; // A wrapper class to BufferedWriter class used to inject IOException errors // when the throwIOException instance variable is set. All methods delegate // to the parent super class and check whether or not to throw an IOException // before delegation. public class MyBufferedWriter extends BufferedWriter { private static final Logger LOGGER = Logger.getLogger(MyBufferedWriter.class.getName()); private boolean throwIOException; public MyBufferedWriter(Writer out) { super(out); } public MyBufferedWriter(Writer out, int sz) { super(out, sz); } public MyBufferedWriter(Writer out, int sz, boolean throwIOException) { super(out, sz); this.throwIOException = throwIOException; } private void checkToTripIOException() throws IOException { if (throwIOException) { LOGGER.info("*** tripping an IOException ***"); throw new IOException("tripping an IOException"); } } public void setThrowIOException(boolean throwIOException) { this.throwIOException = throwIOException; } public void write(int c) throws IOException { checkToTripIOException(); super.write(c); } public void write(char[] cbuf) throws IOException { checkToTripIOException(); super.write(cbuf); } public void write(char[] cbuf, int offset, int length) throws IOException { checkToTripIOException(); super.write(cbuf, offset, length); } public void write(String str) throws IOException { checkToTripIOException(); super.write(str); } public void write(String str, int offset, int length) throws IOException { checkToTripIOException(); super.write(str, offset, length); } public void close() throws IOException { checkToTripIOException(); super.close(); } public void flush() throws IOException { checkToTripIOException(); super.flush(); } } jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/common/MyJsonLocation.java000066400000000000000000000031661451447132700327600ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.common; import jakarta.json.stream.JsonLocation; public class MyJsonLocation implements JsonLocation { private long lineNumber = -1; private long columnNumber = -1; private long streamOffset = -1; public MyJsonLocation() { } public MyJsonLocation(long lineNumber, long columnNumber, long streamOffset) { this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.streamOffset = streamOffset; } public void setLineNumber(long lineNumber) { this.lineNumber = lineNumber; } public long getLineNumber() { return lineNumber; } public void setColumnNumber(long columnNumber) { this.columnNumber = columnNumber; } public long getColumnNumber() { return columnNumber; } public void setStreamOffset(long streamOffset) { this.streamOffset = streamOffset; } public long getStreamOffset() { return streamOffset; } } jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/util/000077500000000000000000000000001451447132700266645ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/util/FileUTFConverter.java000066400000000000000000000073561451447132700326700ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ /* * Usage: java FileUTFConverter [-toUTF|-fromUTF] encoding infile outfile * * Utility program for converting a UTF-8 file to various UTF * encoded files and vice-versa. * * Example(s): * * java FileUTFConverter -toUTF UTF-16 jsonObjectUTF8.json jsonObjectUTF16.json * * The above takes a UTF-8 encoded input file (jsonObjectUTF8.json) and converts * it to a UTF-16 encoded output file (jsonObjectUTF16.json). * * java FileUTFConverter -fromUTF UTF-16 jsonObjectUTF16.json jsonObjectUTF8.json * * The above takes a UTF-16 encoded input file (jsonObjectUTF16.json) and * converts it to a UTF-8 encoded output file (jsonObjectUTF8.json). * * All UTF encodings can be used: * * UTF-8 * UTF-16 * UTF-16BE * UTF-16LE * UTF-32BE * UTF-32LE */ package ee.jakarta.tck.jsonp.util; import java.io.*; import java.util.logging.Logger; public class FileUTFConverter { private static final Logger LOGGER = Logger.getLogger(FileUTFConverter.class.getName()); private static final String USAGE = "Usage : java FileUTFConverter [-toUTF|-fromUTF] encoding infile outfile"; public static void main(String args[]) { try { if (args.length != 4) { LOGGER.warning(USAGE); System.exit(1); } // Convert UTF-8 input file to specified UTF encoded output file if (args[0].equals("-toUTF")) { LOGGER.info("FileUTFConverter-> convert UTF-8 encoded input file (" + args[2] + "), to encoding (" + args[1] + ") and write to output file (" + args[3] + ")"); FileInputStream fis = new FileInputStream(args[2]); BufferedReader br = new BufferedReader( new InputStreamReader(fis, "UTF-8")); FileOutputStream fos = new FileOutputStream(args[3]); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(fos, args[1])); for (String s = ""; (s = br.readLine()) != null;) { bw.write(s + System.getProperty("line.separator")); bw.flush(); } bw.close(); br.close(); // Convert specified UTF encoded input file to UTF-8 encoded output file } else if (args[0].equals("-fromUTF")) { LOGGER.info("FileUTFConverter-> convert UTF encoded input file (" + args[2] + "), from encoding (" + args[1] + ") and write to UTF-8 encoded output file (" + args[3] + ")"); FileInputStream fis = new FileInputStream(args[2]); BufferedReader br = new BufferedReader( new InputStreamReader(fis, args[1])); FileOutputStream fos = new FileOutputStream(args[3]); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(fos, "UTF-8")); for (String s = ""; (s = br.readLine()) != null;) { bw.write(s + System.getProperty("line.separator")); bw.flush(); } bw.close(); br.close(); } else { LOGGER.warning(USAGE); System.exit(1); } System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/util/MyEncoder.java000066400000000000000000000052471451447132700314240ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.util; import java.io.*; import java.util.logging.Logger; /* * Used to generate an encoded file preceded by N null characters. * * This utility takes a valid Json text file as input and generates * an encoded version as output file with N null characters preceded by * each character. For empty files it will just output the N null chars. * */ public class MyEncoder { private static final Logger LOGGER = Logger.getLogger(MyEncoder.class.getName()); private static final int NULL = '\0'; private static final String USAGE = "Usage : java MyEncoder #nulls infile outfile"; public static void main(String args[]) { if (args.length != 3) { LOGGER.warning(USAGE); System.exit(1); } FileReader inputStream = null; FileWriter outputStream = null; try { int n = Integer.parseInt(args[0]); inputStream = new FileReader(args[1]); outputStream = new FileWriter(args[2]); LOGGER.info("Null chars: " + args[0]); LOGGER.info("Input file: " + args[1]); LOGGER.info("Output file: " + args[2]); LOGGER.info("\nCreating an encoded file with each char preceded by " + n + " null chars.\n"); int c; int nchars = 0; while ((c = inputStream.read()) != -1) { nchars++; for (int i = 0; i < n; i++) outputStream.write(NULL); outputStream.write(c); } if (nchars == 0) { for (int i = 0; i < n; i++) outputStream.write(NULL); // if empty file at least write the nulls // out } } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } if (outputStream != null) { try { outputStream.close(); } catch (Exception e) { } } } System.exit(0); } } StringUTFConverter.java000066400000000000000000000040461451447132700331710ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-common/src/main/java/ee/jakarta/tck/jsonp/util/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ /* * Usage: java StringUTFConverter inputstring encoding outputfile * * Utility program to convert an input string to a UTF encoded output file. * * Example(s): * * java StringUTFConverter "foo" UTF-16LE fooUTF16LE * * The above converts an input string "foo" and outputs to UTF-16LE encoded * output file (fooUTF16LE). */ package ee.jakarta.tck.jsonp.util; import java.io.*; import java.util.logging.Logger; public class StringUTFConverter { private static final Logger LOGGER = Logger.getLogger(StringUTFConverter.class.getName()); private static final String USAGE = "Usage : java StringUTFConverter inputstring encoding outputfile"; public static void main(String args[]) { try { if (args.length != 3) { LOGGER.warning(USAGE); System.exit(1); } // Convert string to specified UTF encoded output file LOGGER.info( "StringtoUTF-> convert string (" + args[0] + "), to encoding (" + args[1] + ") and write to output file (" + args[2] + ")"); FileOutputStream fos = new FileOutputStream(args[2]); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(fos, args[1])); bw.write(args[0]); bw.flush(); bw.close(); System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/000077500000000000000000000000001451447132700177365ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/pom.xml000066400000000000000000000126721451447132700212630ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT ../pom.xml jakarta.json jakarta.json-tck-dist-eftl pom JSONP TCK EFTL Distribution Eclipse Foundation Technology Compatibility Kit License - v 1.0 manual https://www.eclipse.org/legal/tck.php true true true jakarta.json jakarta.json-tck-ug ${project.version} zip jakarta.json jakarta.json-tck ${project.version} pom jakarta.json jakarta.json-tck-common ${project.version} jar jakarta.json jakarta.json-tck-common ${project.version} pom jakarta.json jakarta.json-tck-common ${project.version} sources true jakarta.json jakarta.json-tck-tests ${project.version} jar jakarta.json jakarta.json-tck-tests ${project.version} pom jakarta.json jakarta.json-tck-tests ${project.version} sources true jakarta.json jakarta.json-tck-tests-pluggability ${project.version} jar jakarta.json jakarta.json-tck-tests-pluggability ${project.version} pom jakarta.json jakarta.json-tck-tests-pluggability ${project.version} sources true maven-assembly-plugin distribution package single src/main/assembly/assembly.xml \ false jakarta-jsonp-tck-${project.version} jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/000077500000000000000000000000001451447132700205255ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/000077500000000000000000000000001451447132700214515ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/assembly/000077500000000000000000000000001451447132700232705ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/assembly/assembly.xml000066400000000000000000000054751451447132700256440ustar00rootroot00000000000000 distribution jsonp-tck zip ${project.basedir}/src/main/resources . * ${project.build.scriptSourceDirectory} artifacts 0755 **/*.sh ${project.basedir}/src/main/bin bin **/*.xml true jakarta.json:jakarta.json-tck jakarta.json:jakarta.json-tck-common jakarta.json:jakarta.json-tck-tests jakarta.json:jakarta.json-tck-tests-pluggability false artifacts false jakarta.json:jakarta.json-tck-ug true . jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/bin/000077500000000000000000000000001451447132700222215ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/bin/pom.xml000066400000000000000000000135201451447132700235370ustar00rootroot00000000000000 4.0.0 org.eclipse.ee4j project 1.0.7 jakarta.json jakarta.json-tck-impl ${project.version} pom jakarta.json jakarta.json-api 2.1.0 org.eclipse.parsson parsson 1.1.0 ${project.version} UTF-8 \${project.build.directory}/jdk-bundle 2.1.0 true jakarta.json jakarta.json-tck \${jakarta.json-tck.version} pom import tck-tests tck-tests-pluggability \${jsonp-api.groupId} \${jsonp-api.artifactId} \${jsonp-api.version} test org.junit.jupiter junit-jupiter-api test org.junit.jupiter junit-jupiter-engine test verify org.apache.maven.plugins maven-dependency-plugin 3.2.0 jakarta.json jakarta.json-api \${jakarta.json-api.version} jar true \${project.build.directory}/signaturedirectory jakarta.json-api.jar org.apache.maven.plugins maven-surefire-plugin 3.0.0-M5 false \${impl.alltests} 1 false \${jimage.dir} \${project.build.directory}/signaturedirectory/jakarta.json-api.jar:\${jimage.dir}/java.base:\${jimage.dir}/java.rmi:\${jimage.dir}/java.sql:\${jimage.dir}/java.naming single-test test false jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/bin/tck-tests-pluggability/000077500000000000000000000000001451447132700266345ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/bin/tck-tests-pluggability/pom.xml000066400000000000000000000037161451447132700301600ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck-impl ${project.version} ../pom.xml tck-tests-pluggability jakarta.json jakarta.json-tck-tests-pluggability test org.apache.maven.plugins maven-surefire-plugin jakarta.json:jakarta.json-tck-tests-pluggability jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/bin/tck-tests/000077500000000000000000000000001451447132700241425ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/bin/tck-tests/pom.xml000066400000000000000000000055121451447132700254620ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck-impl ${project.version} ../pom.xml tck-tests \${jsonp-impl.groupId} \${jsonp-impl.artifactId} \${jsonp-impl.version} test jakarta.json jakarta.json-tck-tests test org.netbeans.tools sigtest-maven-plugin test org.apache.maven.plugins maven-dependency-plugin copy generate-test-sources copy org.apache.maven.plugins maven-surefire-plugin jakarta.json:jakarta.json-tck-tests jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/resources/000077500000000000000000000000001451447132700234635ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/resources/LICENSE.md000066400000000000000000000076541451447132700251030ustar00rootroot00000000000000# Eclipse Foundation Technology Compatibility Kit License - v 1.0 Copyright (c) 2018, Eclipse Foundation, Inc. and its licensors. Redistribution and use in binary form is permitted provided that the following conditions are met: 1. Use of the Technology Compatibility Kit accompanying this license (the "TCK") and its documentation is permitted solely for the purpose of testing compatibility of an implementation (the "Product") of a specification (the "Specification") made available by the Eclipse Foundation, Inc. ("Eclipse"). 2. Only those modifications expressly permitted by the TCK and its documentation are permitted. Except in these limited circumstances, no modifications to the TCK are permitted under this license. 3. A Product will be deemed to be "compatible" with the Specification if it fully and completely meets and satisfies all requirements of the TCK. 4. Before any claim of compatibility (or any similar claim suggesting compatibility) is made based on the TCK, the testing party must: a. use the TCK to demonstrate that the Product fully and completely meets and satisfies all requirements of the TCK; b. make TCK test results showing full and complete satisfaction of all requirements of the TCK publicly available on the testing party's website and send a link to such test results to Eclipse at [tck@eclipse.org](mailto:tck@eclipse.org); and c. comply with any requirements stated in the Specification with regard to subsetting, supersetting, modifying or extending the Specification in any Product claimed to be compatible with the Specification. 5. The test results must be continuously available and the link must be live for at least as long as the Product is available in the marketplace. 6. The TCK may not be used as a basis for any statements of partial compatibility. The TCK may only be used as a basis for true, factual statements of full compatibility of Products that fully meet and satisfy all requirements of the TCK. 7. A determination that a Product is compatible with the TCK does not, in itself, give rise to the right to use any name, mark, logo associated with the TCK, Eclipse, or Eclipse's contributors or licensors. 8. Upon the request of Eclipse, a tester will retract any statements of compatibility (or any similar claim suggesting compatibility) which Eclipse reasonably determines to be false or misleading or in violation of the terms of this license. 9. Redistribution of the TCK must be under this Eclipse Foundation Technology Compatibility Kit License and must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10. Neither the name, trademarks or logos of Eclipse, nor the names, trademarks or logos of its contributors or licensors may be used to endorse or promote products tested with this software without specific prior written permission. 11. The source code for the TCK accompanying this license is available from Eclipse. TO THE EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED 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. TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER THE COPYRIGHT OWNER OR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/scripts/000077500000000000000000000000001451447132700231405ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-eftl/src/main/scripts/artifact-install.sh000077500000000000000000000063231451447132700267440ustar00rootroot00000000000000#!/usr/bin/env bash # # Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. # # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v. 2.0, which is available at # http://www.eclipse.org/legal/epl-2.0. # # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the # Eclipse Public License v. 2.0 are satisfied: GNU General Public License, # version 2 with the GNU Classpath Exception, which is available at # https://www.gnu.org/software/classpath/license.html. # # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 # ##script to install the artifact directory contents into a local maven repository if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+.*$ ]]; then VERSION="$1" else VERSION="2.1.0-SNAPSHOT" fi # Parent pom mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-"$VERSION".pom -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck -Dversion="$VERSION" -Dpackaging=pom # pom mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-common-"$VERSION".pom -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-common -Dversion="$VERSION" -Dpackaging=pom # jar mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-common-"$VERSION".jar -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-common -Dversion="$VERSION" -Dpackaging=jar # sources jar mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-common-"$VERSION"-sources.jar -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-common-sources -Dversion="$VERSION" -Dpackaging=jar # pom mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-tests-"$VERSION".pom -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-tests -Dversion="$VERSION" -Dpackaging=pom # jar mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-tests-"$VERSION".jar -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-tests -Dversion="$VERSION" -Dpackaging=jar # sources jar mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-tests-"$VERSION"-sources.jar -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-tests-sources -Dversion="$VERSION" -Dpackaging=jar # pom mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-tests-pluggability-"$VERSION".pom -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-tests-pluggability -Dversion="$VERSION" -Dpackaging=pom # jar mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-tests-pluggability-"$VERSION".jar -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-tests-pluggability -Dversion="$VERSION" -Dpackaging=jar # sources jar mvn org.apache.maven.plugins:maven-install-plugin:3.0.0-M1:install-file \ -Dfile=jakarta.json-tck-tests-pluggability-"$VERSION"-sources.jar -DgroupId=jakarta.json \ -DartifactId=jakarta.json-tck-tests-pluggability-sources -Dversion="$VERSION" -Dpackaging=jar jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/000077500000000000000000000000001451447132700175645ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/pom.xml000066400000000000000000000147471451447132700211160ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT ../pom.xml jakarta.json jakarta.json-tck-dist-epl pom JSONP TCK EPL Distribution Eclipse Public License - v 2.0 repo https://www.eclipse.org/legal/epl-2.0/ jakarta.json jakarta.json-tck-ug ${project.version} zip jakarta.json jakarta.json-tck ${project.version} pom jakarta.json jakarta.json-tck-common ${project.version} jar jakarta.json jakarta.json-tck-common ${project.version} pom jakarta.json jakarta.json-tck-common ${project.version} sources true jakarta.json jakarta.json-tck-tests ${project.version} jar jakarta.json jakarta.json-tck-tests ${project.version} pom jakarta.json jakarta.json-tck-tests ${project.version} sources true jakarta.json jakarta.json-tck-tests-pluggability ${project.version} jar jakarta.json jakarta.json-tck-tests-pluggability ${project.version} pom jakarta.json jakarta.json-tck-tests-pluggability ${project.version} sources true org.apache.maven.plugins maven-dependency-plugin 3.2.0 unpack package unpack jakarta.json jakarta.json-tck-dist-eftl ${project.version} zip true **/LICENSE.md ${project.build.directory}/generated true maven-assembly-plugin distribution package single src/main/assembly/assembly.xml false jsonp-tck-${project.version} jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/src/000077500000000000000000000000001451447132700203535ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/src/main/000077500000000000000000000000001451447132700212775ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/src/main/assembly/000077500000000000000000000000001451447132700231165ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/src/main/assembly/assembly.xml000066400000000000000000000030661451447132700254640ustar00rootroot00000000000000 distribution jsonp-tck zip ${project.basedir}/src/main/resources . * ${project.build.directory}/generated/jsonp-tck . jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/src/main/resources/000077500000000000000000000000001451447132700233115ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-dist-epl/src/main/resources/LICENSE.md000066400000000000000000001044141451447132700247210ustar00rootroot00000000000000# Eclipse Public License - v 2.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution "originates" from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works. "Contributor" means any person or entity that Distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions Distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors. "Derivative Works" shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. "Modified Works" shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof. "Distribute" means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy. "Source Code" means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files. "Secondary License" means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3). 3. REQUIREMENTS 3.1 If a Contributor Distributes the Program in any form, then: a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license: i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3. 3.2 When the Program is Distributed as Source Code: a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and b) a copy of this Agreement must be included with each copy of the Program. 3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability ("notices") contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement. Exhibit A - Form of Secondary Licenses Notice "This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}." Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. --- ## The GNU General Public License (GPL) Version 2, June 1991 Copyright (C) 1989, 2022 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. One line to give the program's name and a brief idea of what it does. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. --- ## CLASSPATH EXCEPTION Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License version 2 cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. jsonp-api-2.1.3-RELEASE/tck/tck-docs/000077500000000000000000000000001451447132700167735ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/JSONP2.1-ReleaseNotes.html000066400000000000000000000111761451447132700233700ustar00rootroot00000000000000 Jakarta JSON Processing TCK Release Notes

Jakarta EE JSON Processing Technology Compatibility Kit, Version 2.1

Release Notes, February 2022

Kit Contents

The Jakarta EE JSON Processing, Version 2.1 Technology Compatibility Kit (TCK) includes the following items:

  • Jakarta EE JSON Processing TCK tests signature, API, and pluggability tests:

    • A signature test that checks that all of the public APIs are supported in the Jakarta EE JSON Processing Version 2.1 implementation that is being tested

    • API tests for all of the public APIs under the jakarta.json, jakarta.json.spi, jakarta.json.stream package

    • Pluggability tests for testing the SPI provider interface for supplying your own JsonProvider


Jakarta EE JSON Processing TCK Facts

The test suite bundle contains the following:

  • 1 signature test
  • 178 API tests
  • 18 pluggability tests

Platform Notes

The Jakarta EE JSON Processing TCK tests have been built with JDK 11 and tested with JavaTM Platform, Standard Edition 11+

The Jakarta EE JSON Processing TCK tests have been run on the following platforms:

  • CentOS 7
  • Alpine Linux v3.12

The Jakarta EE JSON Processing TCK tests have been run against the following Jakarta EE JSON Processing 2.1 Compatible Implementations:

  • Eclipse Parsson 1.1.0

Installing, Setting Up, and Running the JSON-P TCK

Refer to the JSON-P TCK 2.1 User's Guide (or PDF) for complete instructions on installing, setting up, and running the JSON-P TCK.


Copyright © 2013, 2022 Oracle and/or its affiliates. All rights reserved.

jsonp-api-2.1.3-RELEASE/tck/tck-docs/TCK-Exclude-List.txt000066400000000000000000000012561451447132700224610ustar00rootroot00000000000000# # Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved. # # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v. 2.0, which is available at # http://www.eclipse.org/legal/epl-2.0. # # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the # Eclipse Public License v. 2.0 are satisfied: GNU General Public License, # version 2 with the GNU Classpath Exception, which is available at # https://www.gnu.org/software/classpath/license.html. # # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 # jsonp-api-2.1.3-RELEASE/tck/tck-docs/assertions/000077500000000000000000000000001451447132700211655ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/assertions/JSONP2.1JavadocAssertions.html000066400000000000000000006331311451447132700265370ustar00rootroot00000000000000 JavaDoc Assertion Detail

Jakarta JSON Processing - 2.0
JavaDoc Assertion Detail

TotalsTotalActiveDeprecatedRemoved
# of Assertions 4122820130
# of Required Assertions 4122820130
# of Optional Assertions 0000

IDReturnMethod/FieldDescriptionRequiredDeprecatedTestable
JSONP:JAVADOC:6JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( JsonValue )
Adds a value to the array.true
true
JSONP:JAVADOC:8JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( String )
Adds a value to the array as a JsonString.true
true
JSONP:JAVADOC:10JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( BigDecimal )
Adds a value to the array as a JsonNumber.true
true
JSONP:JAVADOC:12JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( BigInteger )
Adds a value to the array as a JsonNumber.true
true
JSONP:JAVADOC:14JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int )
Adds a value to the array as a JsonNumber.true
true
JSONP:JAVADOC:16JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( long )
Adds a value to the array as a JsonNumber.true
true
JSONP:JAVADOC:18JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( double )
Adds a value to the array as a JsonNumber.true
true
JSONP:JAVADOC:21JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( boolean )
Adds a JsonValue#TRUE or JsonValue#FALSE value to the array.true
true
JSONP:JAVADOC:25JsonArrayBuilderjakarta.json.JsonArrayBuilder.addNull
Adds a JsonValue#NULL value to the array.true
true
JSONP:JAVADOC:37JsonExceptionjakarta.json.JsonException.JsonException
( String )
Constructs a new runtime exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to #initCause.true
true
JSONP:JAVADOC:38JsonExceptionjakarta.json.JsonException.JsonException
( String ,
Throwable )
Constructs a new runtime exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this runtime exception's detail message.true
true
JSONP:JAVADOC:40BigDecimaljakarta.json.JsonNumber.bigDecimalValue
Returns this JSON number as a BigDecimal object.true
true
JSONP:JAVADOC:41BigIntegerjakarta.json.JsonNumber.bigIntegerValue
Returns this JSON number as a BigInteger object. This is a a convenience method for bigDecimalValue().toBigInteger(). Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign.true
true
JSONP:JAVADOC:42BigIntegerjakarta.json.JsonNumber.bigIntegerValueExact
Returns this JSON number as a BigInteger object. This is a convenience method for bigDecimalValue().toBigIntegerExact().true
true
JSONP:JAVADOC:44doublejakarta.json.JsonNumber.doubleValue
Returns this JSON number as a double. This is a a convenience method for bigDecimalValue().doubleValue(). Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign.true
true
JSONP:JAVADOC:45intjakarta.json.JsonNumber.intValue
Returns this JSON number as an int. Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign.true
true
JSONP:JAVADOC:46intjakarta.json.JsonNumber.intValueExact
Returns this JSON number as an int.true
true
JSONP:JAVADOC:48longjakarta.json.JsonNumber.longValue
Returns this JSON number as a long. Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign.true
true
JSONP:JAVADOC:49longjakarta.json.JsonNumber.longValueExact
Returns this JSON number as a long.true
true
JSONP:JAVADOC:51booleanjakarta.json.JsonNumber.isIntegral
Returns true if this JSON number is a integral number. This method semantics are defined using bigDecimalValue().scale(). If the scale is zero, then it is considered integral type. This integral type information can be used to invoke an appropriate accessor method to obtain a numeric value as in the following example: JsonNumber num = ... if (num.isIntegral()) { num.longValue(); // or other methods to get integral value } else { num.doubleValue(); // or other methods to get decimal number value }true
true
JSONP:JAVADOC:58JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
JsonValue )
Adds a name/JsonValue pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:61JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
String )
Adds a name/JsonString pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:64JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
BigInteger )
Adds a name/JsonNumber pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:67JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
BigDecimal )
Adds a name/JsonNumber pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:70JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
int )
Adds a name/JsonNumber pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:73JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
long )
Adds a name/JsonNumber pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:76JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
double )
Adds a name/JsonNumber pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:80JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
boolean )
Adds a name/JsonValue#TRUE or name/JsonValue#FALSE pair to the JSON object associated with this object builder. If the object contains a mapping for the specified name, this method replaces the old value with the specified value.true
true
JSONP:JAVADOC:86JsonObjectBuilderjakarta.json.JsonObjectBuilder.addNull
( String )
Adds a name/JsonValue#NULL pair to the JSON object associated with this object builder where the value is null. If the object contains a mapping for the specified name, this method replaces the old value with null.true
true
JSONP:JAVADOC:96voidjakarta.json.JsonReader.close
Closes this reader and frees any resources associated with the reader. This method closes the underlying input source.true
true
JSONP:JAVADOC:97JsonReaderjakarta.json.Json.createReader
( Reader )
Creates a JSON reader from a character stream.true
true
JSONP:JAVADOC:101Stringjakarta.json.JsonString.getString
Returns the JSON string value.true
true
JSONP:JAVADOC:102ValueTypejakarta.json.JsonValue.getValueType
Returns the value type of this JSON value.true
true
JSONP:JAVADOC:103ValueTypejakarta.json.JsonValue.ValueType.valueOf
( String )

true
true
JSONP:JAVADOC:104ValueType[]jakarta.json.JsonValue.ValueType.values

true
true
JSONP:JAVADOC:105voidjakarta.json.JsonWriter.close

true
true
JSONP:JAVADOC:106JsonWriterjakarta.json.Json.createWriter
( Writer )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified character stream.true
true
JSONP:JAVADOC:107voidjakarta.json.JsonWriter.writeArray
( JsonArray )
Writes the specified JSON JsonArray array to the output source. This method needs to be called only once for a writer instance.true
true
JSONP:JAVADOC:110voidjakarta.json.JsonWriter.writeObject
( JsonObject )
Writes the specified JSON JsonObject object to the output source. This method needs to be called only once for a writer instance.true
true
JSONP:JAVADOC:115voidjakarta.json.stream.JsonGenerator.close
Closes this generator and frees any resources associated with it. This method closes the underlying output source.true
true
JSONP:JAVADOC:117voidjakarta.json.stream.JsonParser.close
Closes this parser and frees any resources associated with the parser. This method closes the underlying input source.true
true
JSONP:JAVADOC:120booleanjakarta.json.stream.JsonParser.isIntegralNumber
Returns true if the JSON number at the current parser state is a integral number. A BigDecimal may be used to store the value internally and this method semantics are defined using its scale(). If the scale is zero, then it is considered integral type. This integral type information can be used to invoke an appropriate accessor method to obtain a numeric value as in the following example: JsonParser parser = ... if (parser.isIntegralNumber()) { parser.getInt(); // or other methods to get integral value } else { parser.getBigDecimal(); }true
true
JSONP:JAVADOC:122Stringjakarta.json.stream.JsonParser.getString
Returns a String for the name in a name/value pair, for a string value or a number value. This method should only be called when the parser state is Event#KEY_NAME, Event#VALUE_STRING, or Event#VALUE_NUMBER.true
true
JSONP:JAVADOC:128Eventjakarta.json.stream.JsonParser.Event.valueOf
( String )

true
true
JSONP:JAVADOC:129Event[]jakarta.json.stream.JsonParser.Event.values

true
true
JSONP:JAVADOC:131JsonGeneratorjakarta.json.Json.createGenerator
( Writer )
Creates a JSON generator for writing JSON to a character stream.true
true
JSONP:JAVADOC:133JsonParserjakarta.json.Json.createParser
( Reader )
Creates a JSON parser from a character stream.true
true
JSONP:JAVADOC:144JsonGeneratorjakarta.json.spi.JsonProvider.createGenerator
( Writer )
Creates a JSON generator for writing JSON text to a character stream.true
true
JSONP:JAVADOC:146JsonParserjakarta.json.spi.JsonProvider.createParser
( Reader )
Creates a JSON parser from a character stream.true
true
JSONP:JAVADOC:152JsonProviderjakarta.json.spi.JsonProvider.provider
Creates a JSON provider object. The provider is loaded using the ServiceLoader#load(Class) method. If there are no available service providers, this method returns the default service provider. Users are recommended to cache the result of this method.true
true
JSONP:JAVADOC:162JsonGeneratorjakarta.json.stream.JsonGeneratorFactory.createGenerator
( Writer )
Creates a JSON generator to write JSON text to a character stream. The generator is configured with the factory configuration.true
true
JSONP:JAVADOC:163JsonGeneratorjakarta.json.stream.JsonGeneratorFactory.createGenerator
( OutputStream ,
Charset )
Creates a JSON generator to write JSON text to a byte stream. Characters written to the stream are encoded into bytes using the specified charset. The generator is configured with the factory's configuration.true
true
JSONP:JAVADOC:164JsonParserjakarta.json.stream.JsonParserFactory.createParser
( Reader )
Creates a JSON parser from a character stream.true
true
JSONP:JAVADOC:165JsonParserjakarta.json.stream.JsonParserFactory.createParser
( InputStream )
Creates a JSON parser from the specified byte stream. The character encoding of the stream is determined as specified in RFC 7159.true
true
JSONP:JAVADOC:166JsonParserjakarta.json.stream.JsonParserFactory.createParser
( JsonObject )
Creates a JSON parser from the specified JSON object.true
true
JSONP:JAVADOC:167JsonParserjakarta.json.stream.JsonParserFactory.createParser
( JsonArray )
Creates a JSON parser from the specified JSON array.true
true
JSONP:JAVADOC:168JsonGeneratorjakarta.json.Json.createGenerator
( OutputStream )
Creates a JSON generator for writing JSON to a byte stream.true
true
JSONP:JAVADOC:172JsonParserjakarta.json.Json.createParser
( InputStream )
Creates a JSON parser from a byte stream. The character encoding of the stream is determined as specified in RFC 7159.true
true
JSONP:JAVADOC:178JsonReaderjakarta.json.Json.createReader
( InputStream )
Creates a JSON reader from a byte stream. The character encoding of the stream is determined as described in RFC 7159.true
true
JSONP:JAVADOC:181JsonStructurejakarta.json.JsonReader.read
Returns a JSON array or object that is represented in the input source. This method needs to be called only once for a reader instance.true
true
JSONP:JAVADOC:184JsonArrayjakarta.json.JsonReader.readArray
Returns a JSON array that is represented in the input source. This method needs to be called only once for a reader instance.true
true
JSONP:JAVADOC:185JsonObjectjakarta.json.JsonReader.readObject
Returns a JSON object that is represented in the input source. This method needs to be called only once for a reader instance.true
true
JSONP:JAVADOC:187JsonWriterjakarta.json.Json.createWriter
( OutputStream )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified byte stream. Characters written to the stream are encoded into bytes using UTF-8 encoding.true
true
JSONP:JAVADOC:191voidjakarta.json.JsonWriter.write
( JsonStructure )
Writes the specified JSON JsonObject object or JsonArray array to the output source. This method needs to be called only once for a writer instance.true
true
JSONP:JAVADOC:192JsonGeneratorjakarta.json.spi.JsonProvider.createGenerator
( OutputStream )
Creates a JSON generator for writing JSON text to a byte stream.true
true
JSONP:JAVADOC:196JsonParserjakarta.json.spi.JsonProvider.createParser
( InputStream )
Creates a JSON parser from the specified byte stream. The character encoding of the stream is determined as defined in RFC 7159 .true
true
JSONP:JAVADOC:200JsonGeneratorjakarta.json.stream.JsonGeneratorFactory.createGenerator
( OutputStream )
Creates a JSON generator to write JSON text to a byte stream. Characters written to the stream are encoded into bytes using UTF-8 encoding. The generator is configured with the factory's configuration.true
true
JSONP:JAVADOC:201JsonParserjakarta.json.stream.JsonParserFactory.createParser
( InputStream ,
Charset )
Creates a JSON parser from the specified byte stream. The bytes of the stream are decoded to characters using the specified charset.true
true
JSONP:JAVADOC:215Stringjakarta.json.JsonNumber.toString
Returns a JSON text representation of the JSON number. The representation is equivalent to BigDecimal#toString().true
true
JSONP:JAVADOC:235BigDecimaljakarta.json.stream.JsonParser.getBigDecimal
Returns a JSON number as a BigDecimal. The BigDecimal is created using new BigDecimal(getString()). This method should only called when the parser state is Event#VALUE_NUMBER.true
true
JSONP:JAVADOC:237intjakarta.json.stream.JsonParser.getInt
Returns a JSON number as an integer. The returned value is equal to new BigDecimal(getString()).intValue(). Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign. This method should only be called when the parser state is Event#VALUE_NUMBER.true
true
JSONP:JAVADOC:239longjakarta.json.stream.JsonParser.getLong
Returns a JSON number as a long. The returned value is equal to new BigDecimal(getString()).longValue(). Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign. This method is only called when the parser state is Event#VALUE_NUMBER.true
true
JSONP:JAVADOC:250booleanjakarta.json.JsonNumber.equals
( Object )
Compares the specified object with this JsonNumber object for equality. Returns true if and only if the type of the specified object is also JsonNumber and their #bigDecimalValue() objects are equaltrue
true
JSONP:JAVADOC:251intjakarta.json.JsonNumber.hashCode
Returns the hash code value for this JsonNumber object. The hash code of a JsonNumber object is defined as the hash code of its #bigDecimalValue() object.true
true
JSONP:JAVADOC:254booleanjakarta.json.JsonString.equals
( Object )
Compares the specified object with this JsonString for equality. Returns true if and only if the specified object is also a JsonString, and their #getString() objects are equal.true
true
JSONP:JAVADOC:255intjakarta.json.JsonString.hashCode
Returns the hash code value for this JsonString object. The hash code of a JsonString object is defined to be its #getString() object's hash code.true
true
JSONP:JAVADOC:262intjakarta.json.JsonArray.getInt
( int )
A convenience method for getJsonNumber(index).intValue().true
true
JSONP:JAVADOC:263Stringjakarta.json.JsonArray.getString
( int )
A convenience method for getJsonString(index).getString().true
true
JSONP:JAVADOC:264intjakarta.json.JsonObject.getInt
( String )
A convenience method for getJsonNumber(name).intValue()true
true
JSONP:JAVADOC:265Stringjakarta.json.JsonObject.getString
( String )
A convenience method for getJsonString(name).getString()true
true
JSONP:JAVADOC:278JsonGenerationExceptionjakarta.json.stream.JsonGenerationException.JsonGenerationException
( String )
Constructs a new runtime exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to #initCause.true
true
JSONP:JAVADOC:279JsonGenerationExceptionjakarta.json.stream.JsonGenerationException.JsonGenerationException
( String ,
Throwable )
Constructs a new runtime exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this runtime exception's detail message.true
true
JSONP:JAVADOC:285JsonParsingExceptionjakarta.json.stream.JsonParsingException.JsonParsingException
( String ,
JsonLocation )
Constructs a new runtime exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to #initCause.true
true
JSONP:JAVADOC:286JsonParsingExceptionjakarta.json.stream.JsonParsingException.JsonParsingException
( String ,
Throwable ,
JsonLocation )
Constructs a new runtime exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this runtime exception's detail message.true
true
JSONP:JAVADOC:288Stringjakarta.json.JsonValue.toString
Returns JSON text for this JSON value.true
true
JSONP:JAVADOC:289JsonGeneratorjakarta.json.stream.JsonGenerator.writeEnd
Writes the end of the current context. If the current context is an array context, this method writes the end-of-array character (']'). If the current context is an object context, this method writes the end-of-object character ('}'). After writing the end of the current context, the parent context becomes the new current context. If parent context is field context, it is closed.true
true
JSONP:JAVADOC:291voidjakarta.json.stream.JsonGenerator.flush
Flushes the underlying output source. If the generator has saved any characters in a buffer, writes them immediately to the underlying output source before flushing it.true
true
JSONP:JAVADOC:292JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
JsonValue )
Writes a JSON name/value pair in the current object context.true
true
JSONP:JAVADOC:295JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
String )
Writes a JSON name/string value pair in the current object context. The specified value is written as JSON string value.true
true
JSONP:JAVADOC:298JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
BigInteger )
Writes a JSON name/number value pair in the current object context. The specified value is written as a JSON number value. The string new BigDecimal(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:301JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
BigDecimal )
Writes a JSON name/number value pair in the current object context. The specified value is written as a JSON number value. The specified value's toString() is used as the text value for writing.true
true
JSONP:JAVADOC:304JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
int )
Writes a JSON name/number value pair in the current object context. The specified value is written as a JSON number value. The string new BigDecimal(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:307JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
long )
Writes a JSON name/number value pair in the current object context. The specified value is written as a JSON number value. The string new BigDecimal(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:310JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
double )
Writes a JSON name/number value pair in the current object context. The specified value is written as a JSON number value. The string BigDecimal.valueOf(double).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:314JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String ,
boolean )
Writes a JSON name/boolean value pair in the current object context. If value is true, it writes the JSON true value, otherwise it writes the JSON false value.true
true
JSONP:JAVADOC:317JsonGeneratorjakarta.json.stream.JsonGenerator.write
( JsonValue )
Writes the specified value as a JSON value within the current array, field or root context.true
true
JSONP:JAVADOC:319JsonGeneratorjakarta.json.stream.JsonGenerator.write
( String )
Writes the specified value as a JSON string value within the current array, field or root context.true
true
JSONP:JAVADOC:321JsonGeneratorjakarta.json.stream.JsonGenerator.write
( BigDecimal )
Writes the specified value as a JSON number value within the current array, field or root context. The specified value's toString() is used as the the text value for writing.true
true
JSONP:JAVADOC:323JsonGeneratorjakarta.json.stream.JsonGenerator.write
( BigInteger )
Writes the specified value as a JSON number value within the current array, field or root context. The string new BigDecimal(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:325JsonGeneratorjakarta.json.stream.JsonGenerator.write
( int )
Writes the specified value as a JSON number value within the current array, field or root context. The string new BigDecimal(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:327JsonGeneratorjakarta.json.stream.JsonGenerator.write
( long )
Writes the specified value as a JSON number value within the current array, field or root context. The string new BigDecimal(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:329JsonGeneratorjakarta.json.stream.JsonGenerator.write
( double )
Writes the specified value as a JSON number value within the current array, field or root context. The string BigDecimal.valueOf(value).toString() is used as the text value for writing.true
true
JSONP:JAVADOC:332JsonGeneratorjakarta.json.stream.JsonGenerator.write
( boolean )
Writes a JSON true or false value within the current array, field or root context. If value is true, this method writes the JSON true value, otherwise it writes the JSON false value.true
true
JSONP:JAVADOC:334JsonGeneratorjakarta.json.stream.JsonGenerator.writeNull
( String )
Writes a JSON name/null value pair in an current object context.true
true
JSONP:JAVADOC:337JsonGeneratorjakarta.json.stream.JsonGenerator.writeNull
Writes a JSON null value within the current array, field or root context.true
true
JSONP:JAVADOC:339JsonGeneratorjakarta.json.stream.JsonGenerator.writeStartArray
Writes the JSON start array character. It starts a new child array context within which JSON values can be written to the array. This method is valid only in an array context, field context or in no context (when a context is not yet started). This method can only be called once in no context.true
true
JSONP:JAVADOC:340JsonGeneratorjakarta.json.stream.JsonGenerator.writeStartArray
( String )
Writes the JSON name/start array character pair with in the current object context. It starts a new child array context within which JSON values can be written to the array.true
true
JSONP:JAVADOC:341JsonGeneratorjakarta.json.stream.JsonGenerator.writeStartObject
Writes the JSON start object character. It starts a new child object context within which JSON name/value pairs can be written to the object. This method is valid only in an array context, field context or in no context (when a context is not yet started). This method can only be called once in no context.true
true
JSONP:JAVADOC:342JsonGeneratorjakarta.json.stream.JsonGenerator.writeStartObject
( String )
Writes the JSON name/start object character pair in the current object context. It starts a new child object context within which JSON name/value pairs can be written to the object.true
true
JSONP:JAVADOC:375booleanjakarta.json.stream.JsonParser.hasNext
Returns true if there are more parsing states. This method returns false if the parser reaches the end of the JSON text.true
true
JSONP:JAVADOC:376Eventjakarta.json.stream.JsonParser.next
Returns the event for the next parsing state.true
true
JSONP:JAVADOC:383CharSequencejakarta.json.JsonString.getChars
Returns the char sequence for the JSON String valuetrue
true
JSONP:JAVADOC:400JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( JsonObjectBuilder )
Adds a JsonObject from an object builder to the array.true
true
JSONP:JAVADOC:401JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( JsonArrayBuilder )
Adds a JsonArray from an array builder to the array.true
true
JSONP:JAVADOC:402JsonArrayjakarta.json.JsonArrayBuilder.build
Returns the current array.true
true
JSONP:JAVADOC:403JsonArrayBuilderjakarta.json.Json.createArrayBuilder
Creates a JSON array buildertrue
true
JSONP:JAVADOC:404JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
JsonObjectBuilder )
Adds a name/JsonObject pair to the JSON object associated with this object builder. The value JsonObject is built from the specified object builder. If the object contains a mapping for the specified name, this method replaces the old value with the JsonObject from the specified object builder.true
true
JSONP:JAVADOC:406JsonObjectBuilderjakarta.json.JsonObjectBuilder.add
( String ,
JsonArrayBuilder )
Adds a name/JsonArray pair to the JSON object associated with this object builder. The value JsonArray is built from the specified array builder. If the object contains a mapping for the specified name, this method replaces the old value with the JsonArray from the specified array builder.true
true
JSONP:JAVADOC:408JsonObjectjakarta.json.JsonObjectBuilder.build
Returns the JSON object associated with this object builder. The iteration order for the JsonObject is based on the order in which name/value pairs are added to the object using this builder.true
true
JSONP:JAVADOC:409JsonObjectBuilderjakarta.json.Json.createObjectBuilder
Creates a JSON object buildertrue
true
JSONP:JAVADOC:416JsonGeneratorFactoryjakarta.json.Json.createGeneratorFactory
( Map )
Creates a generator factory for creating JsonGenerator objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:417JsonParserFactoryjakarta.json.Json.createParserFactory
( Map )
Creates a parser factory for creating JsonParser objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:419JsonReaderjakarta.json.JsonReaderFactory.createReader
( Reader )
Creates a JSON reader from a character stream. The reader is configured with the factory configuration.true
true
JSONP:JAVADOC:420JsonReaderjakarta.json.JsonReaderFactory.createReader
( InputStream ,
Charset )
Creates a JSON reader from a byte stream. The bytes of the stream are decoded to characters using the specified charset. The reader is configured with the factory configuration.true
true
JSONP:JAVADOC:422JsonWriterjakarta.json.JsonWriterFactory.createWriter
( Writer )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified character stream. The writer is configured with the factory configuration.true
true
JSONP:JAVADOC:423JsonWriterjakarta.json.JsonWriterFactory.createWriter
( OutputStream )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified byte stream. Characters written to the stream are encoded into bytes using UTF-8 encoding. The writer is configured with the factory configuration.true
true
JSONP:JAVADOC:424JsonWriterjakarta.json.JsonWriterFactory.createWriter
( OutputStream ,
Charset )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified byte stream. Characters written to the stream are encoded into bytes using the specified charset. The writer is configured with the factory configuration.true
true
JSONP:JAVADOC:425JsonGeneratorFactoryjakarta.json.spi.JsonProvider.createGeneratorFactory
( Map )
Creates a generator factory for creating JsonGenerator instances. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:426JsonParserFactoryjakarta.json.spi.JsonProvider.createParserFactory
( Map )
Creates a parser factory for creating JsonParser instances. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:427Mapjakarta.json.stream.JsonGeneratorFactory.getConfigInUse
Returns a read-only map of supported provider specific configuration properties that are used to configure the JSON generators. If there are any specified configuration properties that are not supported by the provider, they won't be part of the returned map.true
true
JSONP:JAVADOC:428Mapjakarta.json.stream.JsonParserFactory.getConfigInUse
Returns a read-only map of supported provider specific configuration properties that are used to configure the JSON parsers. If there are any specified configuration properties that are not supported by the provider, they won't be part of the returned map.true
true
JSONP:JAVADOC:429JsonReaderjakarta.json.JsonReaderFactory.createReader
( InputStream )
Creates a JSON reader from a byte stream. The character encoding of the stream is determined as described in RFC 7159. The reader is configured with the factory configuration.true
true
JSONP:JAVADOC:430booleanjakarta.json.JsonArray.getBoolean
( int )
Returns the boolean value at the specified position. If the value at the specified position is JsonValue.TRUE this method returns true. If the value at the specified position is JsonValue.FALSE this method returns false.true
true
JSONP:JAVADOC:433booleanjakarta.json.JsonArray.getBoolean
( int ,
boolean )
Returns the boolean value at the specified position. If the value at the specified position is JsonValue.TRUE this method returns true. If the value at the specified position is JsonValue.FALSE this method returns false. Otherwise this method returns the specified default value.true
true
JSONP:JAVADOC:434intjakarta.json.JsonArray.getInt
( int ,
int )
Returns the int value of the JsonNumber at the specified position. If the value at that position is a JsonNumber, this method returns jakarta.json.JsonNumber#intValue(). Otherwise this method returns the specified default value.true
true
JSONP:JAVADOC:435Stringjakarta.json.JsonArray.getString
( int ,
String )
Returns the String value of JsonString at the specified position in this JSON array values. If JsonString is found, its jakarta.json.JsonString#getString() is returned. Otherwise, the specified default value is returned.true
true
JSONP:JAVADOC:436booleanjakarta.json.JsonObject.getBoolean
( String )
Returns the boolean value of the associated mapping for the specified name. If the associated mapping is JsonValue.TRUE, then returns true. If the associated mapping is JsonValue.FALSE, then returns false.true
true
JSONP:JAVADOC:439booleanjakarta.json.JsonObject.getBoolean
( String ,
boolean )
Returns the boolean value of the associated mapping for the specified name. If the associated mapping is JsonValue.TRUE, then returns true. If the associated mapping is JsonValue.FALSE, then returns false. Otherwise, the specified default value is returned.true
true
JSONP:JAVADOC:441intjakarta.json.JsonObject.getInt
( String ,
int )
Returns the int value of the associated JsonNumber mapping for the specified name. If JsonNumber is found, then its jakarta.json.JsonNumber#intValue() is returned. Otherwise, the specified default value is returned.true
true
JSONP:JAVADOC:443Stringjakarta.json.JsonObject.getString
( String ,
String )
Returns the string value of the associated JsonString mapping for the specified name. If JsonString is found, then its jakarta.json.JsonString#getString() is returned. Otherwise, the specified default value is returned.true
true
JSONP:JAVADOC:445JsonBuilderFactoryjakarta.json.Json.createBuilderFactory
( Map )
Creates a builder factory for creating JsonArrayBuilder and JsonObjectBuilder objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:449JsonReaderFactoryjakarta.json.Json.createReaderFactory
( Map )
Creates a reader factory for creating JsonReader objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:452JsonWriterFactoryjakarta.json.Json.createWriterFactory
( Map )
Creates a writer factory for creating JsonWriter objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:453JsonArrayBuilderjakarta.json.JsonBuilderFactory.createArrayBuilder
Creates a JsonArrayBuilder instance that is used to build JsonArraytrue
true
JSONP:JAVADOC:454JsonObjectBuilderjakarta.json.JsonBuilderFactory.createObjectBuilder
Creates a JsonObjectBuilder instance that is used to build JsonObject.true
true
JSONP:JAVADOC:455Mapjakarta.json.JsonBuilderFactory.getConfigInUse
Returns read-only map of supported provider specific configuration properties that are used to configure the created JSON builders. If there are any specified configuration properties that are not supported by the provider, they won't be part of the returned map.true
true
JSONP:JAVADOC:459Mapjakarta.json.JsonReaderFactory.getConfigInUse
Returns read-only map of supported provider specific configuration properties that are used to configure the created JSON readers. If there are any specified configuration properties that are not supported by the provider, they won't be part of the returned map.true
true
JSONP:JAVADOC:463Mapjakarta.json.JsonWriterFactory.getConfigInUse
Returns read-only map of supported provider specific configuration properties that are used to configure the created JSON writer objects. If there are any specified configuration properties that are not supported by the provider, they won't be part of the returned map.true
true
JSONP:JAVADOC:464JsonArrayBuilderjakarta.json.spi.JsonProvider.createArrayBuilder
Creates a JSON array builder.true
true
JSONP:JAVADOC:465JsonBuilderFactoryjakarta.json.spi.JsonProvider.createBuilderFactory
( Map )
Creates a builder factory for creating JsonArrayBuilder and JsonObjectBuilder objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:466JsonObjectBuilderjakarta.json.spi.JsonProvider.createObjectBuilder
Creates a JSON object builder.true
true
JSONP:JAVADOC:467JsonReaderjakarta.json.spi.JsonProvider.createReader
( Reader )
Creates a JSON reader from a character stream.true
true
JSONP:JAVADOC:468JsonReaderjakarta.json.spi.JsonProvider.createReader
( InputStream )
Creates a JSON reader from a byte stream. The character encoding of the stream is determined as described in RFC 7159.true
true
JSONP:JAVADOC:469JsonReaderFactoryjakarta.json.spi.JsonProvider.createReaderFactory
( Map )
Creates a reader factory for creating JsonReader objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:470JsonWriterjakarta.json.spi.JsonProvider.createWriter
( Writer )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified character stream.true
true
JSONP:JAVADOC:471JsonWriterjakarta.json.spi.JsonProvider.createWriter
( OutputStream )
Creates a JSON writer to write a JSON JsonObject object or JsonArray array structure to the specified byte stream. Characters written to the stream are encoded into bytes using UTF-8 encoding.true
true
JSONP:JAVADOC:472JsonWriterFactoryjakarta.json.spi.JsonProvider.createWriterFactory
( Map )
Creates a writer factory for creating JsonWriter objects. The factory is configured with the specified map of provider specific configuration properties. Provider implementations should ignore any unsupported configuration properties specified in the map.true
true
JSONP:JAVADOC:474longjakarta.json.stream.JsonLocation.getColumnNumber
Return the column number (starts with 1 for the first column) for the current JSON event in the input source.true
true
JSONP:JAVADOC:475longjakarta.json.stream.JsonLocation.getLineNumber
Return the line number (starts with 1 for the first line) for the current JSON event in the input source.true
true
JSONP:JAVADOC:476longjakarta.json.stream.JsonLocation.getStreamOffset
Return the stream offset into the input source this location is pointing to. If the input source is a file or a byte stream then this is the byte offset into that stream, but if the input source is a character media then the offset is the character offset. Returns -1 if there is no offset available.true
true
JSONP:JAVADOC:477JsonLocationjakarta.json.stream.JsonParser.getLocation
Return the location that corresponds to the parser's current state in the JSON input source. The location information is only valid in the current parser state (or until the parser is advanced to a next state).true
true
JSONP:JAVADOC:478JsonLocationjakarta.json.stream.JsonParsingException.getLocation
Return the location of the incorrect JSON.true
true
JSONP:JAVADOC:481Listjakarta.json.JsonArray.getValuesAs
( Class )
Returns a list view of the specified type for the array. This method does not verify if there is a value of wrong type in the array. Providing this typesafe view dynamically may cause a program fail with a ClassCastException, if there is a value of wrong type in this array. Unfortunately, the exception can occur at any time after this method returns.true
true
JSONP:JAVADOC:490JsonArrayjakarta.json.JsonArray.getJsonArray
( int )
Returns the array value at the specified position in this array. This is a convenience method for (JsonArray)get(index).true
true
JSONP:JAVADOC:493JsonNumberjakarta.json.JsonArray.getJsonNumber
( int )
Returns the number value at the specified position in this array. This is a convenience method for (JsonNumber)get(index).true
true
JSONP:JAVADOC:496JsonObjectjakarta.json.JsonArray.getJsonObject
( int )
Returns the object value at the specified position in this array. This is a convenience method for (JsonObject)get(index).true
true
JSONP:JAVADOC:499JsonStringjakarta.json.JsonArray.getJsonString
( int )
Returns the string value at ths specified position in this array. This is a convenience method for (JsonString)get(index).true
true
JSONP:JAVADOC:506booleanjakarta.json.JsonArray.isNull
( int )
Returns true if the value at the specified location in this array is JsonValue.NULL.true
true
JSONP:JAVADOC:527JsonArrayjakarta.json.JsonObject.getJsonArray
( String )
Returns the array value to which the specified name is mapped. This is a convenience method for (JsonArray)get(name) to get the value.true
true
JSONP:JAVADOC:529JsonNumberjakarta.json.JsonObject.getJsonNumber
( String )
Returns the number value to which the specified name is mapped. This is a convenience method for (JsonNumber)get(name) to get the value.true
true
JSONP:JAVADOC:531JsonObjectjakarta.json.JsonObject.getJsonObject
( String )
Returns the object value to which the specified name is mapped. This is a convenience method for (JsonObject)get(name) to get the value.true
true
JSONP:JAVADOC:533JsonStringjakarta.json.JsonObject.getJsonString
( String )
Returns the string value to which the specified name is mapped. This is a convenience method for (JsonString)get(name) to get the value.true
true
JSONP:JAVADOC:539booleanjakarta.json.JsonObject.isNull
( String )
Returns true if the associated value for the specified name is JsonValue.NULL.true
true
JSONP:JAVADOC:572JsonArrayBuilderjakarta.json.Json.createArrayBuilder
( JsonArray )
Creates a JSON array builder, initialized with the specified arraytrue
true
JSONP:JAVADOC:573JsonArrayBuilderjakarta.json.Json.createArrayBuilder
( Collection )
Creates a JSON array builder, initialized with the specified arraytrue
true
JSONP:JAVADOC:574JsonPatchjakarta.json.Json.createDiff
( JsonStructure ,
JsonStructure )
Generates a JSON Patch (RFC 6902) from the source and target JsonStructure. The generated JSON Patch need not be unique.true
true
JSONP:JAVADOC:575JsonMergePatchjakarta.json.Json.createMergeDiff
( JsonValue ,
JsonValue )
Generates a JSON Merge Patch (RFC 7396) from the source and target JsonValues which when applied to the source, yields the target.true
true
JSONP:JAVADOC:576JsonMergePatchjakarta.json.Json.createMergePatch
( JsonValue )
Creates JSON Merge Patch (RFC 7396) from specified JsonValue.true
true
JSONP:JAVADOC:577JsonObjectBuilderjakarta.json.Json.createObjectBuilder
( JsonObject )
Creates a JSON object builder, initialized with the specified object.true
true
JSONP:JAVADOC:578JsonObjectBuilderjakarta.json.Json.createObjectBuilder
( Map )
Creates a JSON object builder, initialized with the specified object.true
true
JSONP:JAVADOC:579JsonPatchjakarta.json.Json.createPatch
( JsonArray )
Creates a JSON Patch (RFC 6902) from the specified operations.true
true
JSONP:JAVADOC:580JsonPatchBuilderjakarta.json.Json.createPatchBuilder
Creates a JSON Patch builder (RFC 6902).true
true
JSONP:JAVADOC:581JsonPatchBuilderjakarta.json.Json.createPatchBuilder
( JsonArray )
Creates a JSON Patch builder (RFC 6902), initialized with the specified operations.true
true
JSONP:JAVADOC:582JsonPointerjakarta.json.Json.createPointer
( String )
Creates JSON Pointer (RFC 6901) from given jsonPointer string. An empty jsonPointer string defines a reference to the target itself. If the jsonPointer string is non-empty, it must be a sequence of '/' prefixed tokens.true
true
JSONP:JAVADOC:583JsonStringjakarta.json.Json.createValue
( String )
Creates a JsonString.true
true
JSONP:JAVADOC:584JsonNumberjakarta.json.Json.createValue
( int )
Creates a JsonNumber.true
true
JSONP:JAVADOC:585JsonNumberjakarta.json.Json.createValue
( long )
Creates a JsonNumber.true
true
JSONP:JAVADOC:586JsonNumberjakarta.json.Json.createValue
( double )
Creates a JsonNumber.true
true
JSONP:JAVADOC:587JsonNumberjakarta.json.Json.createValue
( BigDecimal )
Creates a JsonNumber.true
true
JSONP:JAVADOC:588JsonNumberjakarta.json.Json.createValue
( BigInteger )
Creates a JsonNumber.true
true
JSONP:JAVADOC:589Listjakarta.json.JsonArray.getValuesAs
( Function )
Returns a list view for the array. The value and the type of the elements in the list is specified by the func argument. This method can be used to obtain a list of the unwrapped types, such as List strings = ary1.getValuesAs(JsonString::getString); List ints = ary2.getValuesAs(JsonNumber::intValue); or a list of simple projections, such as List stringsizes = ary1.getValueAs((JsonString v)->v.getString().length();true
true
JSONP:JAVADOC:590JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
JsonValue )
Inserts a value to the array at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:591JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
String )
Adds a value to the array as a JsonString at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:592JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
BigDecimal )
Adds a value to the array as a JsonNumber at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:593JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
BigInteger )
Adds a value to the array as a JsonNumber at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:594JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
int )
Adds a value to the array as a JsonNumber at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:595JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
long )
Adds a value to the array as a JsonNumber at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:596JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
double )
Adds a value to the array as a JsonNumber at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:597JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
boolean )
Adds a JsonValue#TRUE or JsonValue#FALSE value to the array at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:598JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
JsonObjectBuilder )
Adds a JsonObject from an object builder to the array at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:599JsonArrayBuilderjakarta.json.JsonArrayBuilder.add
( int ,
JsonArrayBuilder )
Adds a JsonArray from an array builder to the array at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:600JsonArrayBuilderjakarta.json.JsonArrayBuilder.addAll
( JsonArrayBuilder )
Adds all elements of the array in the specified array builder to the array.true
true
JSONP:JAVADOC:601JsonArrayBuilderjakarta.json.JsonArrayBuilder.addNull
( int )
Adds a JsonValue#NULL value to the array at the specified position. Shifts the value currently at that position (if any) and any subsequent values to the right (adds one to their indices). Index starts with 0.true
true
JSONP:JAVADOC:602JsonArrayBuilderjakarta.json.JsonArrayBuilder.remove
( int )
Remove the value in the array at the specified position. Shift any subsequent values to the left (subtracts one from their indices.true
true
JSONP:JAVADOC:603JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
JsonValue )
Replaces a value in the array with the specified value at the specified position.true
true
JSONP:JAVADOC:604JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
String )
Replaces a value in the array with the specified value as a JsonString at the specified position.true
true
JSONP:JAVADOC:605JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
BigDecimal )
Replaces a value in the array with the specified value as a JsonNumber at the specified position.true
true
JSONP:JAVADOC:606JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
BigInteger )
Replaces a value in the array with the specified value as a JsonNumber at the specified position.true
true
JSONP:JAVADOC:607JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
int )
Replaces a value in the array with the specified value as a JsonNumber at the specified position.true
true
JSONP:JAVADOC:608JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
long )
Replaces a value in the array with the specified value as a JsonNumber at the specified position.true
true
JSONP:JAVADOC:609JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
double )
Replaces a value in the array with the specified value as a JsonNumber at the specified position.true
true
JSONP:JAVADOC:610JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
boolean )
Replaces a value in the array with a JsonValue#TRUE or JsonValue#FALSE value at the specified position.true
true
JSONP:JAVADOC:611JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
JsonObjectBuilder )
Replaces a value in the array with the specified value as a JsonObject from an object builder at the specified position.true
true
JSONP:JAVADOC:612JsonArrayBuilderjakarta.json.JsonArrayBuilder.set
( int ,
JsonArrayBuilder )
Replaces a value in the array with the specified value as a JsonArray from an array builder at the specified position.true
true
JSONP:JAVADOC:613JsonArrayBuilderjakarta.json.JsonArrayBuilder.setNull
( int )
Replaces a value in the array with a JsonValue#NULL value at the specified position.true
true
JSONP:JAVADOC:614JsonArrayBuilderjakarta.json.JsonBuilderFactory.createArrayBuilder
( JsonArray )
Creates a JsonArrayBuilder instance, initialized with an array.true
true
JSONP:JAVADOC:615JsonObjectBuilderjakarta.json.JsonBuilderFactory.createObjectBuilder
( JsonObject )
Creates a JsonObjectBuilder instance, initialized with an object.true
true
JSONP:JAVADOC:616JsonValuejakarta.json.JsonMergePatch.apply
( JsonValue )
Applies the JSON Merge Patch to the specified target. The target is not modified by the patch.true
true
JSONP:JAVADOC:617JsonValuejakarta.json.JsonMergePatch.toJsonValue
Returns the JsonMergePatch as JsonValue.true
true
JSONP:JAVADOC:618JsonObjectBuilderjakarta.json.JsonObjectBuilder.addAll
( JsonObjectBuilder )
Adds all name/value pairs in the JSON object associated with the specified object builder to the JSON object associated with this object builder. The newly added name/value pair will replace any existing name/value pair with the same name.true
true
JSONP:JAVADOC:619JsonObjectBuilderjakarta.json.JsonObjectBuilder.remove
( String )
Remove the name/value pair from the JSON object associated with this object builder if it is present.true
true
JSONP:JAVADOC:620JsonStructurejakarta.json.JsonPatch.apply
( JsonStructure )
Applies the patch operations to the specified target. The target is not modified by the patch.true
true
JSONP:JAVADOC:621JsonArrayjakarta.json.JsonPatch.toJsonArray
Returns the JsonPatch as JsonArray.true
true
JSONP:JAVADOC:622Operationjakarta.json.JsonPatch.Operation.fromOperationName
( String )
Returns the enum constant with the specified name.true
true
JSONP:JAVADOC:623Stringjakarta.json.JsonPatch.Operation.operationName
Returns enum constant name as lower case string.true
true
JSONP:JAVADOC:624Operationjakarta.json.JsonPatch.Operation.valueOf
( String )

true
true
JSONP:JAVADOC:625Operation[]jakarta.json.JsonPatch.Operation.values

true
true
JSONP:JAVADOC:626JsonPatchBuilderjakarta.json.JsonPatchBuilder.add
( String ,
JsonValue )
Adds an "add" JSON Patch operation.true
true
JSONP:JAVADOC:627JsonPatchBuilderjakarta.json.JsonPatchBuilder.add
( String ,
String )
Adds an "add" JSON Patch operation.true
true
JSONP:JAVADOC:628JsonPatchBuilderjakarta.json.JsonPatchBuilder.add
( String ,
int )
Adds an "add" JSON Patch operation.true
true
JSONP:JAVADOC:629JsonPatchBuilderjakarta.json.JsonPatchBuilder.add
( String ,
boolean )
Adds an "add" JSON Patch operation.true
true
JSONP:JAVADOC:630JsonPatchjakarta.json.JsonPatchBuilder.build
Returns the JSON Patch.true
true
JSONP:JAVADOC:631JsonPatchBuilderjakarta.json.JsonPatchBuilder.copy
( String ,
String )
Adds a "copy" JSON Patch operation.true
true
JSONP:JAVADOC:632JsonPatchBuilderjakarta.json.JsonPatchBuilder.move
( String ,
String )
Adds a "move" JSON Patch operation.true
true
JSONP:JAVADOC:633JsonPatchBuilderjakarta.json.JsonPatchBuilder.remove
( String )
Adds a "remove" JSON Patch operation.true
true
JSONP:JAVADOC:634JsonPatchBuilderjakarta.json.JsonPatchBuilder.replace
( String ,
JsonValue )
Adds a "replace" JSON Patch operation.true
true
JSONP:JAVADOC:635JsonPatchBuilderjakarta.json.JsonPatchBuilder.replace
( String ,
String )
Adds a "replace" JSON Patch operation.true
true
JSONP:JAVADOC:636JsonPatchBuilderjakarta.json.JsonPatchBuilder.replace
( String ,
int )
Adds a "replace" JSON Patch operation.true
true
JSONP:JAVADOC:637JsonPatchBuilderjakarta.json.JsonPatchBuilder.replace
( String ,
boolean )
Adds a "replace" JSON Patch operation.true
true
JSONP:JAVADOC:638JsonPatchBuilderjakarta.json.JsonPatchBuilder.test
( String ,
JsonValue )
Adds a "test" JSON Patch operation.true
true
JSONP:JAVADOC:639JsonPatchBuilderjakarta.json.JsonPatchBuilder.test
( String ,
String )
Adds a "test" JSON Patch operation.true
true
JSONP:JAVADOC:640JsonPatchBuilderjakarta.json.JsonPatchBuilder.test
( String ,
int )
Adds a "test" JSON Patch operation.true
true
JSONP:JAVADOC:641JsonPatchBuilderjakarta.json.JsonPatchBuilder.test
( String ,
boolean )
Adds a "test" JSON Patch operation.true
true
JSONP:JAVADOC:642JsonStructurejakarta.json.JsonPointer.add
( JsonStructure ,
JsonValue )
Adds or replaces a value at the referenced location in the specified target with the specified value. If the reference is the target (empty JSON Pointer string), the specified value, which must be the same type as specified target, is returned. If the reference is an array element, the specified value is inserted into the array, at the referenced index. The value currently at that location, and any subsequent values, are shifted to the right (adds one to the indices). Index starts with 0. If the reference is specified with a "-", or if the index is equal to the size of the array, the value is appended to the array. If the reference is a name/value pair of a JsonObject, and the referenced value exists, the value is replaced by the specified value. If the value does not exist, a new name/value pair is added to the object.true
true
JSONP:JAVADOC:643JsonValuejakarta.json.JsonPointer.getValue
( JsonStructure )
Returns the value at the referenced location in the specified target.true
true
JSONP:JAVADOC:644JsonStructurejakarta.json.JsonPointer.remove
( JsonStructure )
Removes the value at the reference location in the specified target.true
true
JSONP:JAVADOC:645JsonStructurejakarta.json.JsonPointer.replace
( JsonStructure ,
JsonValue )
Replaces the value at the referenced location in the specified target with the specified value.true
true
JSONP:JAVADOC:646JsonValuejakarta.json.JsonReader.readValue
Returns a JSON value that is represented in the input source. This method needs to be called only once for a reader instance.true
true
JSONP:JAVADOC:647JsonValuejakarta.json.JsonStructure.getValue
( String )
Get the value referenced by the provided JSON Pointer in the JsonStructure.true
true
JSONP:JAVADOC:648JsonArrayjakarta.json.JsonValue.asJsonArray
Return the JsonValue as a JsonArraytrue
true
JSONP:JAVADOC:649JsonObjectjakarta.json.JsonValue.asJsonObject
Return the JsonValue as a JsonObjecttrue
true
JSONP:JAVADOC:650voidjakarta.json.JsonWriter.write
( JsonValue )
Writes the specified JsonValue to the output source. method needs to be called only once for a write instance.true
true
JSONP:JAVADOC:651JsonArrayBuilderjakarta.json.spi.JsonProvider.createArrayBuilder
( JsonArray )
Creates a JSON array builder, initialized with the specified array.true
true
JSONP:JAVADOC:652JsonArrayBuilderjakarta.json.spi.JsonProvider.createArrayBuilder
( Collection )
Creates a JSON array builder, initialized with the specified collection.true
true
JSONP:JAVADOC:653JsonPatchjakarta.json.spi.JsonProvider.createDiff
( JsonStructure ,
JsonStructure )
Generates a JSON Patch (RFC 6902) from the source and target JsonStructure. The generated JSON Patch need not be unique.true
true
JSONP:JAVADOC:654JsonMergePatchjakarta.json.spi.JsonProvider.createMergeDiff
( JsonValue ,
JsonValue )
Generates a JSON Merge Patch (RFC 7396) from the source and target JsonValues which when applied to the source, yields the target.true
true
JSONP:JAVADOC:655JsonMergePatchjakarta.json.spi.JsonProvider.createMergePatch
( JsonValue )
Creates JSON Merge Patch (RFC 7396) from specified JsonValue.true
true
JSONP:JAVADOC:656JsonObjectBuilderjakarta.json.spi.JsonProvider.createObjectBuilder
( JsonObject )
Creates a JSON object builder, initialized with the specified object.true
true
JSONP:JAVADOC:657JsonObjectBuilderjakarta.json.spi.JsonProvider.createObjectBuilder
( Map )
Creates a JSON object builder, initialized with the specified Map.true
true
JSONP:JAVADOC:658JsonPatchjakarta.json.spi.JsonProvider.createPatch
( JsonArray )
Creates a JSON Patch (RFC 6902) from the specified operations.true
true
JSONP:JAVADOC:659JsonPatchBuilderjakarta.json.spi.JsonProvider.createPatchBuilder
Creates a JSON Patch builder (RFC 6902).true
true
JSONP:JAVADOC:660JsonPatchBuilderjakarta.json.spi.JsonProvider.createPatchBuilder
( JsonArray )
Creates a JSON Patch builder (RFC 6902), initialized with the specified operations.true
true
JSONP:JAVADOC:661JsonPointerjakarta.json.spi.JsonProvider.createPointer
( String )
Creates JSON Pointer (RFC 6901) from given jsonPointer string. An empty jsonPointer string defines a reference to the target itself. If the jsonPointer string is non-empty, it must be a sequence of '/' prefixed tokens.true
true
JSONP:JAVADOC:662JsonStringjakarta.json.spi.JsonProvider.createValue
( String )
Creates a JsonString.true
true
JSONP:JAVADOC:663JsonNumberjakarta.json.spi.JsonProvider.createValue
( int )
Creates a JsonNumber.true
true
JSONP:JAVADOC:664JsonNumberjakarta.json.spi.JsonProvider.createValue
( long )
Creates a JsonNumber.true
true
JSONP:JAVADOC:665JsonNumberjakarta.json.spi.JsonProvider.createValue
( double )
Creates a JsonNumber.true
true
JSONP:JAVADOC:666JsonNumberjakarta.json.spi.JsonProvider.createValue
( BigDecimal )
Creates a JsonNumber.true
true
JSONP:JAVADOC:667JsonNumberjakarta.json.spi.JsonProvider.createValue
( BigInteger )
Creates a JsonNumber.true
true
JSONP:JAVADOC:668Collectorjakarta.json.stream.JsonCollectors.groupingBy
( Function ,
Collector )
Constructs a java.util.stream.Collector that implements a "group by" operation on the input JsonValue elements. A classifier function maps the input JsonValues to keys, and the JsonValues are partitioned into groups according to the value of the key. A reduction operation is performed on the JsonValues in each group, using the downstream Collector. For each group, the key and the results of the reduction operation become the name/value pairs of the resultant JsonObject.true
true
JSONP:JAVADOC:669Collectorjakarta.json.stream.JsonCollectors.groupingBy
( Function )
Constructs a java.util.stream.Collector that implements a "group by" operation on the input JsonValue elements. A classifier function maps the input JsonValues to keys, and the JsonValues are partitioned into groups according to the value of the key. The JsonValues in each group are added to a JsonArray. The key and the JsonArray in each group becomes the name/value pair of the resultant JsonObject.true
true
JSONP:JAVADOC:670Collectorjakarta.json.stream.JsonCollectors.toJsonArray
Constructs a java.util.stream.Collector that accumulates the input JsonValue elements into a JsonArray.true
true
JSONP:JAVADOC:671Collectorjakarta.json.stream.JsonCollectors.toJsonObject
( Function ,
Function )
Constructs a java.util.stream.Collector that accumulates the input JsonValue elements into a JsonObject. The name/value pairs of the JsonObject are computed by applying the provided mapping functions.true
true
JSONP:JAVADOC:672JsonGeneratorjakarta.json.stream.JsonGenerator.writeKey
( String )
Writes the JSON name with a colon. It starts a field context, in which valid options are writing a value, starting an object or an array. Writing value closes field context, if object or array is started after field name, field context will be closed after object/array close.true
true
JSONP:JAVADOC:673JsonArrayjakarta.json.stream.JsonParser.getArray
Returns a JsonArray and advance the parser to the the corresponding END_ARRAY.true
true
JSONP:JAVADOC:674Streamjakarta.json.stream.JsonParser.getArrayStream
Returns a stream of the JsonArray elements. The parser state must be START_ARRAY. The elements are read lazily, on an as-needed basis, as required by the stream operations. If the stream operations do not consume all of the array elements, skipArray can be used to skip the unprocessed array elements.true
true
JSONP:JAVADOC:675JsonObjectjakarta.json.stream.JsonParser.getObject
Returns a JsonObject and advances the parser to the corresponding END_OBJECT.true
true
JSONP:JAVADOC:676Streamjakarta.json.stream.JsonParser.getObjectStream
Returns a stream of the JsonObject's name/value pairs. The parser state must be START_OBJECT. The name/value pairs are read lazily, on an as-needed basis, as required by the stream operations. If the stream operations do not consume all of the object's name/value pairs, skipObject can be used to skip the unprocessed elements.true
true
JSONP:JAVADOC:677JsonValuejakarta.json.stream.JsonParser.getValue
Returns a JsonValue at the current parser position. If the parser state is START_ARRAY, the behavior is the same as #getArray. If the parser state is START_OBJECT, the behavior is the same as #getObject. For all other cases, if applicable, the JSON value is read and returned.true
true
JSONP:JAVADOC:678Streamjakarta.json.stream.JsonParser.getValueStream
Returns a stream of JsonValue from a sequence of JSON values. The values are read lazily, on an as-needed basis, as needed by the stream operations.true
true
JSONP:JAVADOC:679voidjakarta.json.stream.JsonParser.skipArray
Advance the parser to END_ARRAY. If the parser is in array context, i.e. it has previously encountered a START_ARRAY without encountering the corresponding END_ARRAY, the parser is advanced to the corresponding END_ARRAY. If the parser is not in any array context, nothing happens.true
true
JSONP:JAVADOC:680voidjakarta.json.stream.JsonParser.skipObject
Advance the parser to END_OBJECT. If the parser is in object context, i.e. it has previously encountered a START_OBJECT without encountering the corresponding END_OBJECT, the parser is advanced to the corresponding END_OBJECT. If the parser is not in any object context, nothing happens.true
true
JSONP:JAVADOC:681enumjakarta.json.JsonConfig.KeyStrategy
Defines the different values allowed for KEY_STRATEGY.true
true
JSONP:JAVADOC:682JsonNumberjakarta.json.Json.createValue(Number value)
Creates a JsonNumber.true
true
JSONP:JAVADOC:683Eventjakarta.json.stream.JsonParser.currentEvent
The event for the current parsing state.true
true
jsonp-api-2.1.3-RELEASE/tck/tck-docs/index.html000066400000000000000000000066221451447132700207760ustar00rootroot00000000000000 Welcome to the Jakarta EE JSON Processing TCK

Welcome to the Jakarta EE JSON Processing TCK, Version 2.1

Your Starting Point


Guide to Jakarta EE JSON Processing TCK 2.1 Documentation

The Jakarta EE JSON Processing TCK 2.1 documentation includes the following:


Copyright © 2013, 2022 Oracle and/or its affiliates. All rights reserved.

jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/000077500000000000000000000000001451447132700207675ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/README.md000066400000000000000000000033221451447132700222460ustar00rootroot00000000000000# A JBake project template ## About JBake JBake is a static site generator, it's inspired from jekyll and written in java. The basic idea is to have templates for the structure of the page, and the body generated from asciidoc content. ## Pre requisites - Maven - JDK11+ Deploying to Github will require password less authentication. This is done by exporting your SSH public key into your Github account. ## Build the site locally The site is generated under target/staging. Open file:///PATH_TO_PROJECT_DIR/target/staging in a browser to view the site. ``` mvn generate-resources ``` Or you can invoke the JBake plugin directly. ``` mvn jbake:build ``` ### Rebuild the site on changes ``` mvn jbake:watch ``` If you keep this command running, changes to the sources will be detected and the site will be rendered incrementally. This is convenient when writing content. ### Serve the site locally ``` mvn jbake:serve ``` If a webserver is required (e.g. absolute path are used), this command will start a webserver (jetty) at http://localhost:8820. It will also watch for changes and rebuild incrementally. ## Deploy the site to Github Pages ``` mvn deploy ``` ## Produce a zip file for download To produce a zip file containing the generated html files, use: ``` mvn package ``` When making a release on GitHub, this zip file should be added to the release. ## Links - [JBake maven plugin documentation](https://github.com/Blazebit/jbake-maven-plugin) - [JBake documentation](http://jbake.org/docs/2.5.1) - [Freemarker documentation](http://freemarker.org/docs) - [AsciiDoc User Guide](http://asciidoc.org/userguide.html) - [Asciidoctor quick reference](http://asciidoctor.org/docs/asciidoc-syntax-quick-reference) jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/pom.xml000066400000000000000000000303751451447132700223140ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT ../../pom.xml jakarta.json jakarta.json-tck-ug pom 2.1.0-SNAPSHOT Eclipse Foundation Technology Compatibility Kit User's Guide for Jakarta JSON Processing for Jakarta EE, Release 2.1 UTF-8 ${project.build.directory}/staging 2.4.2 2.1.0 2.1.0 1.5.3 0.3.3 2.3.30 DRAFT Jakarta-JSON-Processing-TCK-Users-Guide.pdf true scm:git:git@github.com:eclipse-ee4j/jsonp.git package org.apache.maven.plugins maven-clean-plugin src/main/jbake/content toc.adoc org.apache.maven.plugins maven-enforcer-plugin enforce-versions enforce [11,) You need JDK11 or newer org.glassfish.doc glassfish-doc-maven-plugin generate-toc generate-resources toc [A-C0-9]+\s.*,Preface.*,Part\s.* generate-book generate-resources book org.jbake jbake-maven-plugin ${site.output.dir} ${status} build-site generate-resources generate org.asciidoctor asciidoctor-maven-plugin ${project.build.directory}/book book.adoc ${project.build.directory}/staging/ pdf ${doc.pdf} ${project.basedir}/src/theme jakartaee book ${status} font font true - true true generate-pdf-doc generate-resources process-asciidoc maven-assembly-plugin distribution package single src/main/assembly/assembly.xml false org.apache.maven.plugins maven-clean-plugin 3.1.0 org.glassfish.doc glassfish-doc-maven-plugin 1.3 org.apache.maven.plugins maven-enforcer-plugin 3.0.0-M3 org.apache.maven.plugins maven-assembly-plugin 3.3.0 org.apache.maven.plugins maven-scm-publish-plugin 3.1.0 org.jbake jbake-maven-plugin ${jbake.maven.plugin.version} org.asciidoctor asciidoctorj ${asciidoctorj.version} org.asciidoctor asciidoctorj-diagram ${asciidoctorj.diagram.version} org.freemarker freemarker ${freemarker.version} org.asciidoctor asciidoctor-maven-plugin ${asciidoctorj.maven.plugin.version} org.asciidoctor asciidoctorj-pdf ${asciidoctorj.pdf.version} updateGhPages false org.apache.maven.plugins maven-scm-publish-plugin deploy-site deploy publish-scm gh-pages false Update site jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/000077500000000000000000000000001451447132700215565ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/000077500000000000000000000000001451447132700225025ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/assembly/000077500000000000000000000000001451447132700243215ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/assembly/assembly.xml000066400000000000000000000044211451447132700266630ustar00rootroot00000000000000 userguides false zip ${project.build.directory}/generated-docs docs/pdf-usersguide **/*.pdf ${project.build.directory}/staging docs/html-usersguide *.inc *.conf *.yml *.md README ../assertions docs/assertions *Assertions.html ../ docs/ *.* jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/000077500000000000000000000000001451447132700235565ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/000077500000000000000000000000001451447132700250605ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/README.md000066400000000000000000000001521451447132700263350ustar00rootroot00000000000000# About The {{site.title}} project contains the [AsciiDoc](http://asciidoc.org/) source code for the ... jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/_config.yml000066400000000000000000000007511451447132700272120ustar00rootroot00000000000000remote_theme: jakartaee/jekyll-theme-jakarta-ee title: [tck_jsonp_v2_1] description: [Oracle Technology Compatibility Kit User's Guide for Java API for JSON Processing 2.1 for Technology Licensees, Release 2.1] # sidebar links url links: source: https://github.com/eclipse-ee4j/jsonp download: https://github.com/eclipse-ee4j/jsonp/releases/tag/2.1.0-RELEASE #mailinglist: https://javaee.groups.io/g/tck_jsonp_v1_1 #javadocs: docs: https://eclipse-ee4j.github.io/jsonp #faq: jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/css/000077500000000000000000000000001451447132700256505ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/css/style.css000066400000000000000000000267451451447132700275400ustar00rootroot00000000000000/* CSS */ /*! normalize.css v3.0.2 | MIT License | git.io/normalize */ /** 1. Set default font family to sans-serif. 2. Prevent iOS text size adjust after orientation change, without disabling user zoom. */ html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ } /* HTML5 display definitions ========================================================================== */ /** Correct `block` display not defined for any HTML5 element in IE 8/9. Correct `block` display not defined for `details` or `summary` in IE 10/11 and Firefox. Correct `block` display not defined for `main` in IE 11. */ article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary { display: block; } /** 1. Correct `inline-block` display not defined in IE 8/9. 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. */ audio, canvas, progress, video { display: inline-block; /* 1 */ vertical-align: baseline; /* 2 */ } /** Prevent modern browsers from displaying `audio` without controls. Remove excess height in iOS 5 devices. */ audio:not([controls]) { display: none; height: 0; } /** Address `[hidden]` styling not present in IE 8/9/10. Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22. */ [hidden], template { display: none; } /* Links ========================================================================== */ /** Remove the gray background color from active links in IE 10. */ a { background-color: transparent; } /** Improve readability when focused and also mouse hovered in all browsers. */ a:active, a:hover { outline: 0; } /* Text-level semantics ========================================================================== */ /** Address styling not present in IE 8/9/10/11, Safari, and Chrome. */ abbr[title] { border-bottom: 1px dotted; } /** Address style set to `bolder` in Firefox 4+, Safari, and Chrome. */ b, strong { font-weight: bold; } /** Address styling not present in Safari and Chrome. */ dfn { font-style: italic; } /** Address variable `h1` font-size and margin within `section` and `article` contexts in Firefox 4+, Safari, and Chrome. */ h1 { font-size: 2em; margin: 0.67em 0; } /** Address styling not present in IE 8/9. */ mark { background: #ff0; color: #000; } /** Address inconsistent and variable font size in all browsers. */ small { font-size: 80%; } /** Prevent `sub` and `sup` affecting `line-height` in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* Embedded content ========================================================================== */ /** Remove border when inside `a` element in IE 8/9/10. */ img { border: 0; } /** Correct overflow not hidden in IE 9/10/11. */ svg:not(:root) { overflow: hidden; } /* Grouping content ========================================================================== */ /** Address margin not present in IE 8/9 and Safari. */ figure { margin: 1em 40px; } /** Address differences between Firefox and other browsers. */ hr { box-sizing: content-box; height: 0; } /** Contain overflow in all browsers. */ pre { overflow: auto; } /** Address odd `em`-unit font size rendering in all browsers. */ code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; } /* Forms ========================================================================== */ /** Known limitation: by default, Chrome and Safari on OS X allow very limited styling of `select`, unless a `border` property is set. */ /** 1. Correct color not being inherited. Known issue: affects color of disabled elements. 2. Correct font properties not being inherited. 3. Address margins set differently in Firefox 4+, Safari, and Chrome. */ button, input, optgroup, select, textarea { color: inherit; /* 1 */ font: inherit; /* 2 */ margin: 0; /* 3 */ } /** Address `overflow` set to `hidden` in IE 8/9/10/11. */ button { overflow: visible; } /** Address inconsistent `text-transform` inheritance for `button` and `select`. All other form control elements do not inherit `text-transform` values. Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. Correct `select` style inheritance in Firefox. */ button, select { text-transform: none; } /** 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` and `video` controls. 2. Correct inability to style clickable `input` types in iOS. 3. Improve usability and consistency of cursor style between image-type `input` and others. */ button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } /** Re-set default cursor for disabled elements. */ button[disabled], html input[disabled] { cursor: default; } /** Remove inner padding and border in Firefox 4+. */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /** Address Firefox 4+ setting `line-height` on `input` using `!important` in the UA stylesheet. */ input { line-height: normal; } /** It's recommended that you don't attempt to style these elements. Firefox's implementation doesn't respect box-sizing, padding, or width. 1. Address box sizing set to `content-box` in IE 8/9/10. 2. Remove excess padding in IE 8/9/10. */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /** Fix the cursor style for Chrome's increment/decrement buttons. For certain `font-size` values of the `input`, it causes the cursor style of the decrement button to change from `default` to `text`. */ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { height: auto; } /** 1. Address `appearance` set to `searchfield` in Safari and Chrome. 2. Address `box-sizing` set to `border-box` in Safari and Chrome (include `-moz` to future-proof). */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ /* 2 */ box-sizing: content-box; } /** Remove inner padding and search cancel button in Safari and Chrome on OS X. Safari (but not Chrome) clips the cancel button when the search input has padding (and `textfield` appearance). */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /** Define consistent border, margin, and padding. */ fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /** 1. Correct `color` not being inherited in IE 8/9/10/11. 2. Remove padding so people aren't caught out if they zero out fieldsets. */ legend { border: 0; /* 1 */ padding: 0; /* 2 */ } /** Remove default vertical scrollbar in IE 8/9/10/11. */ textarea { overflow: auto; } /** Don't inherit the `font-weight` (applied by a rule above). NOTE: the default cannot safely be changed in Chrome and Safari on OS X. */ optgroup { font-weight: bold; } /* Tables ========================================================================== */ /** Remove most spacing between table cells. */ table { border-collapse: collapse; border-spacing: 0; } td, th { padding: 0; } /* LAYOUT STYLES */ p { margin-top: 0; } code, pre { margin-bottom: 30px; font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; font-size: 13px; color: #222; } code { padding: 0 3px; background-color: #f2f8fc; border: solid 1px #dbe7f3; } pre { padding: 20px; overflow: auto; text-shadow: none; background: #fff; border: solid 1px #f2f2f2; } pre code { padding: 0; color: #2879d0; background-color: #fff; border: none; } ul, ol, dl { margin-bottom: 20px; } /* COMMON STYLES */ td.halign-right { text-align: right; } td.halign-center { text-align: center; } form { padding: 20px; background: #f2f2f2; } h2 { font-size: 2em; line-height: 1.2em; font-weight: 200; letter-spacing: 0; } h3 { font-size: 1.4em; line-height: 1.2em; font-weight: normal; letter-spacing: 0; } .sect1 { margin-left: 4%; margin-right: 4%; font: 13px/20px Arial, Helvetica, sans-serif } a:link { text-decoration: none; color: #09569d; } #preamble hr{ margin-left: 0%; margin-right: 0%; } #preamble .sectionbody table { font-weight: 200; margin-left: 4%; margin-right: 4%; } hr { margin-bottom: 12px; } table.tableblock.frame-all.grid-all.spread { font-size: 12px; } code { font-size:.9em; border: 1px solid #eaeaea; background-color: #f6f6f6; border-radius: 3px; padding: 1px; padding-left:2px; padding-right:2px; } pre.prettyprint.highlight { border: 1px solid #eaeaea; background-color: #f6f6f6; border-radius: 4px; padding: 8px; padding-top:4px; padding-bottom:4px; } .language-oac_no_warn { font-size:.9em; color:#222; background-color: transparent; } #doc-title { margin-left: 4%; } #top-nav { margin-left: 4%; font-size: 12px; } #bottom-nav { margin-left: 4%; font-size: 12px; } .vector-font { color:grey; font-size: 20px; } #copyright { padding-top: 10px; padding-bottom: 4px; display: table; margin:0 auto; color: grey; font-size: 12px; vertical-align: middle; } .beta {color: #FF0000} /* GENERAL ELEMENT TYPE STYLES */ /* #Media Queries ================================================== */ /* Smaller than standard 960 (devices and browsers) */ /* Tablet Portrait size to standard 960 (devices and browsers) */ @media only screen and (min-width: 768px) and (max-width: 959px) { .inner { width: 740px; } header h1, header h2 { width: 340px; } header h1 { font-size: 60px; } header h2 { font-size: 30px; } } /* All Mobile Sizes (devices and browser) */ @media only screen and (max-width: 767px) { .inner { width: 93%; } header { padding: 20px 0; } header .inner { position: relative; } header h1, header h2 { width: 100%; } header h1 { font-size: 48px; } header h2 { font-size: 24px; } header a.button { position: relative; display: inline-block; width: auto; height: auto; padding: 5px 10px; margin-top: 15px; font-size: 13px; line-height: 1; color: #2879d0; text-align: center; background-color: #9ddcff; background-image: none; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } header a.button small { display: inline; font-size: 13px; } } /* Mobile Landscape Size to Tablet Portrait (devices and browsers) */ /* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */ header h1 { padding-top: 14px; font-size: 2em; font-weight: 200; line-height: 1.4; color: #FFFFFF; letter-spacing: 0px; border-bottom: 0px; } header h2 { font-size: 1.2em; margin-top: 0; margin-bottom: 0; font-weight: 200; line-height: .8; color: #ec7D11; letter-spacing: 0; } //header a.button { background: transparent url(../images/logo.png) 0 0 no-repeat; padding-left: 32px; } header a:hover { text-decoration: none; } /* Admonition (Note) block */ .admonitionblock > table { border: 0; background: none; width: 100%; table-layout: auto; margin-bottom: 10.5px; } .admonitionblock > table td.icon { text-align: center; width: 60px; } .admonitionblock > table td.icon img { max-width: none; } .admonitionblock > table td.icon .title { text-transform: uppercase; } .admonitionblock > table td.content { padding-left: 1em; padding-right: 1em; border-left: 3px solid #ddd; } .admonitionblock > table td.content > :last-child > :last-child { margin-bottom: 0; } .admonitionblock td.icon [class^="fa icon-"]:before { font-size: 2.5em; text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); cursor: default; } .admonitionblock td.icon .icon-note:before { content: "\f05a"; color: #5bc0de; } jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/img/000077500000000000000000000000001451447132700256345ustar00rootroot00000000000000eclipse_foundation_logo_tiny.png000066400000000000000000000070341451447132700342240ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/assets/imgPNG  IHDRz(1bKGD pHYs.#.#x?vtIME # IDATxy?AȢU\1XqGZE;ֱUR[mu0"֍VVmպLUZBU㸂 "xۯDy :d^~Yng|Ϲ@ fn@`_0` PYK@NvhB?NjvaglM^qiR Lm9Ij2f~$0^<;ǚw &k2&4;(~0#4;h-eZ젥k29tx7tCGR-N򼋶% wb7TM=^~4E_5:t:0b7O .TLL֙67W.0^lm@ZUFGUvmYp=?K@bagw]oPjJ-(V/vuCU XX#x?4TʛOӌI &O hN?Ve0,&ؖ(seON|!bp=qML.` !V*ְ!!Sy_).p=?L8.-8w=i 09FS',8KJ%,zss,9Ku=I1L_VYr3%be7p8!Gl $yKR+qYi5D]bQ&k觖iz22VXqiN[ 6Gj@o.Gy7wQ&fkg2i2zBq"c0co'r z&e9NLp=n fo+G)> O-1k=߬4[FW3r@+z6Lc yر|4UdQ\u?W_F7{0Yc5r1p^"r T.~ | Yq 6@P#%3$>!t9eƎVN2wLc 20xTs"(lQVTqO-ge7)kP -ZF:uAC跈ݡM^%òVi5_g"_ĉ:׷ LڀG>Umc08FUXT%沔w5qܬánF[gO)2e?_4h_4L% B\K* r*}4NT :3ZS-80z4ӍCG:ف(=~:$MH\; ؟ @1iv0d4r=N7vLt=N*B!!702LY vF <-Ervyqy/r~ՃrչBѪV;"(j5@?_UhM6YmUah hr}qX*E\Uf c^ l7-XaJ,;%N^1 DyZi.'KB,M"A-+`DR)KL mi}dzR$M$&k=s=-peSox95)kTf1g?YKPE3X;jx2Z 5Wj)`K5Xo,!F\TgJՅo1y/ZuwG)fR߯/yv浸,Hۜ#:5;QQ % "t{|(%T 6ގȵJW/hv^H:Y+)zǦxEy+Vf28Ie4fmHT7=ؕ0n7\+AUD)fa\\Jz3WW:ρ/U],(ڙ ܼNԁ젉(ıR%^Giv0=m"e#=_0n`Ȇ|5gP)Ǽ&sQmX=PRQְP#&rNnb~^~AQDz5BG£nf+(R|(8N4"YTM,\/g;^f Oz4;xOD}s3Y4wf}3)8>t6e?#fFbݕiBS|! {)J_+a:[%Sfga2pf~9DYFŒ!Pm'Tt>IENDB`jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/000077500000000000000000000000001451447132700252305ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/README000066400000000000000000000040111451447132700261040ustar00rootroot00000000000000The file attributes.conf defines several attributes (variables) that need to be customized for each technology. The *.adoc files should not be modified. The following "include" files should be customized as necessary for the specific technology: - rules.inc Additional compatibility rules needed by some technologies. The rules in rules.adoc should NOT be changed. - defns.inc Additional definitions needed by additional compatibility rules in rules.inc. - config.inc Detailed instructions for configuring the TCK, included in Chapter 4. Unfortunately, these are sections 4.1 - 4.3, so even if the TCK doesn't require 3 sections you need to make up something, or else change the sections to "N/A". - packages.inc A simple list of Jakarta EE package names for the technology. - tck-packages.inc A list of additional software packages included in the TCK. - req-software.inc A list of software required in addition to the TCK and CI. - install-server.inc Steps to install the Jakarta EE CI, if needed. For standalone technologies, no server may be required, and this file can be empty. This is used in install.adoc in section 3.2. - install-server-vi.inc Steps to install a Vendor's web server, if needed. For standalone technologies, no web server may be required, and this file can be empty. This is used in install.adoc in section 3.2. - using-examples.inc Command line examples showing how to run the TCK. - using.inc Optional additional instructions for running the TCK. - debug-tips.inc Technology-specific troubleshooting tips for Chapter 6. If this isn't needed, it can be an empty file, but toc.adoc will need to be fixed. - rebuild.inc Special instructions for rebuilding the WAR files used by some TCKs. If needed, customize it appropriately and define the "rebuild" attribute in attributes.conf. - title.inc Add acronym references as required do distinguish between legacy and current APIs. Note that this template is NOT sufficient for the Jakarta EE platform or Jakarta EE Web Profile. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/attributes.conf000066400000000000000000000027711451447132700302740ustar00rootroot00000000000000:TechnologyFullName: Jakarta JSON Processing :TechnologyShortName: JSON Processing :LegacyAcronym: JSONP :ReleaseDate: February 2022 :CopyrightDates: 2017, 2022 :TechnologyVersion: 2.1 :TechnologyRI: Eclipse Parsson 1.1.0 :TechnologyRIURL: https://projects.eclipse.org/projects/ee4j.parsson :SpecificationURL: https://jakarta.ee/specifications/jsonp/2.1/ :TCKInquiryList: mailto:jsonp-dev@eclipse.org[jsonp-dev@eclipse.org] :SpecificationInquiryList: mailto:jsonp-dev@eclipse.org[jsonp-dev@eclipse.org] :techID: JSONP // Define this attribute (uncomment it) if the TCK includes no API tests. (Rare.) // :no-api-tests: // Define this attribute (uncomment it) if the TCK includes end-to-end tests. // :end-to-end-tests: // Define this attribute (uncomment it) if subsets of the API are allowed. // (Common Annotations only) // :subset-allowed: // // The environment variable used to specify the home directory // for the technology. Used in config.inc. :TechnologyTCKHomeEnv: JSONPTCK_HOME // Java SE version required. :SEversion: 11+ :JakartaEEVersion: 10.0 :MavenVersion: 3.6.3+ :JunitVersion: 5.7.2+ :excludeListFileName: tck-docs/TCK-Exclude-List.txt :TCKPackageName: jakarta-jsonp-tck-2.1.0.zip // Directory names used in examples in using.adoc. :sigTestExample: ee/jakarta/tck/jsonp/signaturetest/jsonp/** :singleTestExample: ee/jakarta/tck/jsonp/api/jsoncoding/ClientTests :subsetTestDirectoryExample: ee/jakarta/tck/jsonp/api/** // Define this attribute (uncomment it) if the TCK needs the rebuild appendix. // :rebuild: jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/config.adoc000066400000000000000000000237641451447132700273410ustar00rootroot00000000000000type=page status=published title=Setup and Configuration next=using.html prev=install.html ~~~~~~ include::attributes.conf[] Setup and Configuration ======================= [[GBFVV]] [[setup-and-configuration]] 4 Setup and Configuration ------------------------- [NOTE] ==== The Jakarta EE Specification process provides for any number of compatible implementations. As additional implementations become available, refer to project or product documentation from those vendors for specific TCK setup and operational guidance. ==== This chapter describes how to set up the {TechnologyShortName} TCK . Before proceeding with the instructions in this chapter, be sure to install all required software, as described in link:install.html#GBFTP[Chapter 3, "Installation."] After completing the instructions in this chapter, proceed to link:using.html#GBFWO[Chapter 5, "Executing Tests,"] for instructions on running the {TechnologyShortName} TCK. [NOTE] ==== The {TechnologyShortName} TCK is not depended on any particular build tool to run the tests. It will be convenient and advisable to create a Apache Maven project to setup and run the TCK. This chapter will henceforth use instructions and steps to provide setup with Apache Maven as a build tool. ==== /////////////////////////////////////////////////////////////////////// NOTE TO WRITERS: The following sections should be customized for the technology. This text was originally from the JAX-RS TCK. Most references to JAX-RS have been parameterized to serve as a simple starting point for customization. There are still many details that will need to be changed or removed. The major sections 4.1, 4.2, and 4.3 should be preserved. If their titles are changed, the links at the top of config.adoc will need to be changed as well as well as toc.adoc. /////////////////////////////////////////////////////////////////////// [[GBFVU]][[configuring-your-environment-to-run-the-tck-against-the-reference-implementation]] 4.1 Configuring Your Environment to Run the TCK Against the Compatible Implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After configuring your environment as described in this section, continue with the instructions in link:#GBFWO[Chapter 5, "Executing Tests."] [NOTE] ======================================================================= In these instructions, variables in angle brackets need to be expanded for each platform. For example, `` becomes `$JAVA_HOME` on Solaris/Linux and `%JAVA_HOME%` on Windows. In addition, the forward slashes (`/`) used in all of the examples need to be replaced with backslashes (`\`) for Windows. Finally, be sure to use the appropriate separator for your operating system when specifying multiple path entries (`;` on Windows, `:` on UNIX/Linux). On Windows, you must escape any backslashes with an extra backslash in path separators used in any of the following properties, or use forward slashes as a path separator instead. ======================================================================= 1. Set the following environment variables in your shell environment: a. `JAVA_HOME` to the directory in which Java SE {SEversion} is installed b. `M2_HOME` to the directory in which the Apache Maven build tool is installed. c. +{TechnologyTCKHomeEnv}+ to the directory in which the {TechnologyShortName} {TechnologyVersion} TCK has been installed d. `PATH` to include the following directories: `JAVA_HOME/bin`, and `M2_HOME/bin` 2. Set the following System properties: a. `jsonp-impl.groupId` property is set to the Maven Group Id of the CI to test. b. `jsonp-impl.artifactId` property is set to the Maven Artifact Id of the CI to test. c. `jsonp-impl.version` property is set to the Maven Version of the CI to test. d. `jimage.dir` property is set to extract the Java SE {SEversion} modules for running the signature tests. 3. Set the below jars to the classpath a. JAR file for the {TechnologyShortName} {TechnologyVersion} API. + `jakarta.json-api.jar`. b. JUnit 5 jars ({JunitVersion}) c. sigtest-maven-plugin (1.4) to run the signature tests. d. {TechnologyShortName} TCK tests (`jakarta.json:jakarta.json-tck-tests`) or {TechnologyShortName} TCK pluggability tests (`jakarta.json:jakarta.json-tck-tests-pluggability`) depending on which test suite to run. + .Example: Maven configuration [source,oac_no_warn,xml] ---- jakarta.json jakarta.json-tck 2.1.0 pom import .... org.eclipse.parsson parsson 1.1.0 test jakarta.json jakarta.json-api 2.1.0 test org.junit.jupiter junit-jupiter-api test org.junit.jupiter junit-jupiter-engine test org.netbeans.tools sigtest-maven-plugin test jakarta.json jakarta.json-tck-tests test ---- + [[GCLHU]][[configuring-your-environment-to-repackage-and-run-the-tck-against-the-vendor-implementation]] 4.2 Configuring Your Environment to Run the TCK Against the Vendor Implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After configuring your environment as described in this section, continue with the instructions in link:#GBFWO[Chapter 5, "Executing Tests."] [NOTE] ======================================================================= In these instructions, variables in angle brackets need to be expanded for each platform. For example, `` becomes `$JAVA_HOME` on Solaris/Linux and `%JAVA_HOME%` on Windows. In addition, the forward slashes (`/`) used in all of the examples need to be replaced with backslashes (`\`) for Windows. Finally, be sure to use the appropriate separator for your operating system when specifying multiple path entries (`;` on Windows, `:` on UNIX/Linux). On Windows, you must escape any backslashes with an extra backslash in path separators used in any of the following properties, or use forward slashes as a path separator instead. ======================================================================= 1. Set the following environment variables in your shell environment: a. `JAVA_HOME` to the directory in which Java SE {SEversion} is installed b. `M2_HOME` to the directory in which the Apache Maven build tool is installed. c. +{TechnologyTCKHomeEnv}+ to the directory in which the {TechnologyShortName} {TechnologyVersion} TCK has been installed d. `PATH` to include the following directories: `JAVA_HOME/bin`, and `M2_HOME/bin` 2. Set the following System properties: a. `jsonp-api.groupId` property is set to the Maven Group Id of the VI to test. b. `jsonp-api.artifactId` property is set to the Maven Artifact Id of the VI to test. c. `jsonp-api.version` property is set to the Maven Version of the VI to test. d. `jimage.dir` property is set to extract the Java SE {SEversion} modules for running the signature tests. 3. Set the below jars to the classpath a. JAR file for the {TechnologyShortName} {TechnologyVersion} CI. + `parsson.jar`. b. JUnit 5 jars ({JunitVersion}) c. sigtest-maven-plugin (1.4) to run the signature tests. d. {TechnologyShortName} TCK tests (`jakarta.json:jakarta.json-tck-tests`) or {TechnologyShortName} TCK pluggability tests (`jakarta.json:jakarta.json-tck-tests-pluggability`) depending on which test suite to run. + .Example: Maven configuration [source,oac_no_warn,xml] ---- jakarta.json jakarta.json-tck 2.1.0 pom import .... org.eclipse.parsson parsson 1.1.0 test org.junit.jupiter junit-jupiter-api test org.junit.jupiter junit-jupiter-engine test org.netbeans.tools sigtest-maven-plugin test jakarta.json jakarta.json-tck-tests test ---- + [[GHGDG]][[publishing-the-test-applications]] 4.3 Publishing the Test Applications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Not needed for the {TechnologyShortName} TCK. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/debug-tips.inc000066400000000000000000000000001451447132700277540ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/debug.adoc000066400000000000000000000031371451447132700271520ustar00rootroot00000000000000type=page status=published title=Debugging Test Problems next=faq.html prev=using.html ~~~~~~ include::attributes.conf[] Debugging Test Problems ======================= [[GBFUV]] [[debugging-test-problems]] 6 Debugging Test Problems ------------------------- There are a number of reasons that tests can fail to execute properly. This chapter provides some approaches for dealing with these failures. This chapter includes the following topics: * link:#GBFYP[Overview] * link:#GBFYF[Configuration Failures] [[GBFYP]][[overview]] 6.1 Overview ~~~~~~~~~~~~ The goal of a test run is for all tests in the test suite that are not filtered out to have passing results. If the root test suite folder contains tests with errors or failing results, you must troubleshoot and correct the cause to satisfactorily complete the test run. * Errors: Tests with errors could not be executed by the Junit framework. These errors usually occur because the test environment is not properly configured. * Failures: Tests that fail were executed but had failing results. For every test run, the Junit framework creates a set of report files in the target directory. If a large number of tests failed, you should read link:#GBFYF[Configuration Failures] to see if a configuration issue is the cause of the failures. [[GBFYF]][[configuration-failures]] 6.2 Configuration Failures ~~~~~~~~~~~~~~~~~~~~~~~~~~ Configuration failures are easily recognized because many tests fail the same way. When all your tests begin to fail, you may want to stop the run immediately and start viewing individual test output. include::debug-tips.inc[] jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/defns.inc000066400000000000000000000035051451447132700270250ustar00rootroot00000000000000// NOTE TO WRITERS: // Most technologies will only need the compatibility rules in rules.adoc. // Some technologies will need additional definitions to go with additional // rules. If they're needed, remove the comment characters below // and update the definitions as appropriate. // // The first block below is additional definitions needed by // Jakarta XML Web Services. // // The second block below is additional defintions needed by // Jakarta Server Pages. // // NOTE: This set of examples is NOT complete, but should be. // // // Jakarta XML Web Services // // |Development Kit |A software product that implements or incorporates a // Compiler, a Schema Compiler, a Schema Generator, a Java-to-WSDL Tool, a // WSDL-to-Java Tool, and/or an RMI Compiler. // // |Java-to-WSDL Output |Output of a Java-to-WSDL Tool that is required for // Web service deployment and invocation. // // |Java-to-WSDL Tool |A software development tool that implements or // incorporates a function that generates web service endpoint descriptions // in WSDL and XML schema format from Source Code as specified by the // Jakarta XML Web Services Specification. // // |WSDL-to-Java Output |Output of a WSDL-to-Java tool that is required for // Web service deployment and invocation. // // |WSDL-to-Java Tool |A software development tool that implements or // incorporates a function that generates web service interfaces for // clients and endpoints from a WSDL description as specified by the // Jakarta XML Web Services Specification. // // // Jakarta Server Pages // // |Jakarta Server Page |A text-based document that uses Jakarta Server // Pages technology. // // |Jakarta Server Page Implementation Class |A program constructed by // transforming the Jakarta Server Page text into a Java language program // using the transformation rules described in the Specifications. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/faq.adoc000066400000000000000000000043761451447132700266410ustar00rootroot00000000000000type=page status=published title=Appendix A: Frequently Asked Questions next=rebuild.html prev=debug.html ~~~~~~ include::attributes.conf[] Appendix A: Frequently Asked Questions ====================================== [[GBFYD]] [[a-frequently-asked-questions]] A Frequently Asked Questions ---------------------------- This appendix contains the following questions. * link:#GBFYQ[Where do I start to debug a test failure?] * link:#GBFYR[How do I restart a crashed test run?] * link:#GBFWU[What would cause tests be added to the exclude list?] [[GBFYQ]][[a.1-where-do-i-start-to-debug-a-test-failure]] A.1 Where do I start to debug a test failure? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From the JavaTest GUI, you can view recently run tests using the Test Results Summary, by selecting the red Failed tab or the blue Error tab. See link:debug.html#GBFUV[Chapter 6, "Debugging Test Problems,"] for more information. [[GBFYR]][[a.2-how-do-i-restart-a-crashed-test-run]] A.2 How do I restart a crashed test run? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you need to restart a test run, you can figure out which test crashed the test suite by looking at the `harness.trace` file. The `harness.trace` file is in the report directory that you supplied to the JavaTest GUI or parameter file. Examine this trace file, then change the JavaTest GUI initial files to that location or to a directory location below that file, and restart. This will overwrite only `.jtr` files that you rerun. As long as you do not change the value of the GUI work directory, you can continue testing and then later compile a complete report to include results from all such partial runs. [[GBFWU]][[a.3-what-would-cause-tests-be-added-to-the-exclude-list]] A.3 What would cause tests be added to the exclude list? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The JavaTest exclude file (+{excludeListFileName}+) contains all tests that are not required to be run. The following is a list of reasons for a test to be included in the Exclude List: * An error in a Compatible Implementation that does not allow the test to execute properly has been discovered. * An error in the specification that was used as the basis of the test has been discovered. * An error in the test has been discovered. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/install-server-vi.inc000066400000000000000000000000001451447132700312770ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/install-server.inc000066400000000000000000000000001451447132700306630ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/install.adoc000066400000000000000000000065301451447132700275320ustar00rootroot00000000000000type=page status=published title=Installation next=config.html prev=rules.html ~~~~~~ include::attributes.conf[] Installation ============ [[GBFTP]] [[installation]] 3 Installation -------------- This chapter explains how to install the {TechnologyFullName} TCK software. After installing the software according to the instructions in this chapter, proceed to link:config.html#GBFVV[Chapter 4, "Setup and Configuration,"] for instructions on configuring your test environment. [NOTE] ======================================================================= Although the {TechnologyShortName} {TechnologyVersion} TCK is not depended on any particular build tool, it is convenient to install Apache Maven {MavenVersion} for setup and execution of tests. Any other build tools like Gradle and JUnit 5 Console Runner can also be used that is Jupiter API compatible. ======================================================================= [[GBFUD]][[obtaining-the-reference-implementation]] 3.1 Obtaining a Compatible Implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each compatible implementation (CI) will provide instructions for obtaining their implementation. {TechnologyRI} is a compatible implementation which may be obtained from {TechnologyRIURL} [[GBFTS]][[installing-the-software]] 3.2 Installing the Software ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before you can run the {TechnologyShortName} TCK tests, you must install and set up the following software components: include::req-software.inc[] * Java SE {SEversion} * A CI for {TechnologyShortName} {TechnologyVersion}, one example is {TechnologyRI} * The {TechnologyShortName} {TechnologyVersion} Vendor Implementation (VI) * Any Jupiter API compatible test runner (eg. Apache Maven {MavenVersion}) Follow these steps: . Install the Java SE {SEversion} software, if it is not already installed. + Download and install the Java SE {SEversion} software from http://www.oracle.com/technetwork/java/javase/downloads/index.html. Refer to the installation instructions that accompany the software for additional information. . Install the build tool that will be used to run the TCK, if it is not already installed. + It will be convenient to use Apache Maven {MavenVersion} for running the tests. The test kit is not depended on Maven, any build tool compatible with Jupiter API is suffitient. . Install the {TechnologyShortName} TCK {TechnologyVersion} software. a. Copy or download the {TechnologyShortName} TCK software to your local system. + You can obtain the {TechnologyShortName} TCK software from the Jakarta EE site {SpecificationURL}. b. Use the `unzip` command to extract the bundle in the directory of your choice: + +unzip {TCKPackageName}+ + include::install-server.inc[] . Install a {TechnologyShortName} {TechnologyVersion} Compatible Implementation. + A Compatible Implementation is used to validate your initial configuration and setup of the {TechnologyShortName} TCK {TechnologyVersion} tests, which are explained further in link:config.html#GBFVV[Chapter 4, "Setup and Configuration."] + The Compatible Implementations for {TechnologyShortName} are listed on the Jakarta EE Specifications web site: {SpecificationURL}. include::install-server-vi.inc[] . Install the {TechnologyShortName} VI to be tested. + Follow the installation instructions for the particular VI under test. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/intro.adoc000066400000000000000000000301321451447132700272120ustar00rootroot00000000000000type=page status=published title=Introduction next=rules.html prev=preface.html ~~~~~~ include::attributes.conf[] Introduction ============ [[GBFOW]] [[introduction]] 1 Introduction -------------- This chapter provides an overview of the principles that apply generally to all Technology Compatibility Kits (TCKs) and describes the {TechnologyFullName} TCK ({TechnologyShortName} {TechnologyVersion} TCK). It also includes a high level listing of what is needed to get up and running with the {TechnologyShortName} TCK. This chapter includes the following topics: * link:#GBFTK[Compatibility Testing] * link:#GBFQR[About the TCK] * link:#GBFQW[Getting Started With the TCK] [[GBFTK]][[compatibility-testing]] 1.1 Compatibility Testing ~~~~~~~~~~~~~~~~~~~~~~~~~ Compatibility testing differs from traditional product testing in a number of ways. The focus of compatibility testing is to test those features and areas of an implementation that are likely to differ across other implementations, such as those features that: * Rely on hardware or operating system-specific behavior * Are difficult to port * Mask or abstract hardware or operating system behavior Compatibility test development for a given feature relies on a complete specification and compatible implementation (CI) for that feature. Compatibility testing is not primarily concerned with robustness, performance, nor ease of use. [[GBFQN]][[why-compatibility-testing-is-important]] 1.1.1 Why Compatibility Testing is Important ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Jakarta platform compatibility is important to different groups involved with Jakarta technologies for different reasons: * Compatibility testing ensures that the Jakarta platform does not become fragmented as it is ported to different operating systems and hardware environments. * Compatibility testing benefits developers working in the Jakarta programming language, allowing them to write applications once and then to deploy them across heterogeneous computing environments without porting. * Compatibility testing allows application users to obtain applications from disparate sources and deploy them with confidence. * Conformance testing benefits Jakarta platform implementors by ensuring a level playing field for all Jakarta platform ports. [[GBFPR]][[tck-compatibility-rules]] 1.1.2 TCK Compatibility Rules ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Compatibility criteria for all technology implementations are embodied in the TCK Compatibility Rules that apply to a specified technology. Each TCK tests for adherence to these Rules as described in link:rules.html#GBFSN[Chapter 2, "Procedure for Certification."] [[GBFPW]][[tck-overview]] 1.1.3 TCK Overview ^^^^^^^^^^^^^^^^^^ A TCK is a set of tools and tests used to verify that a vendor's compatible implementation of a Jakarta EE technology conforms to the applicable specification. All tests in the TCK are based on the written specifications for the Jakarta EE platform. A TCK tests compatibility of a vendor's compatible implementation of the technology to the applicable specification of the technology. Compatibility testing is a means of ensuring correctness, completeness, and consistency across all implementations developed by technology licensees. The set of tests included with each TCK is called the test suite. Most tests in a TCK's test suite are self-checking, but some tests may require tester interaction. Most tests return either a Pass or Fail status. For a given platform to be certified, all of the required tests must pass. The definition of required tests may change from platform to platform. The definition of required tests will change over time. Before your final certification test pass, be sure to download the latest version of this TCK. [[GBFPB]][[java-community-process-jcp-program-and-compatibility-testing]] 1.1.4 Jakarta EE Specification Process (JESP) Program and Compatibility Testing ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Jakarta EE Specification Process (JESP) program is the formalization of the open process that has been used since 2019 to develop and revise Jakarta EE technology specifications in cooperation with the international Jakarta EE community. The JESP program specifies that the following three major components must be included as deliverables in a final Jakarta EE technology release under the direction of the responsible Expert Group: * Technology Specification * Compatible Implementation (CI) * Technology Compatibility Kit (TCK) For further information about the JESP program, go to Jakarta EE Specification Process community page https://jakarta.ee/specifications. [[GBFQR]][[about-the-tck]] 1.2 About the TCK ~~~~~~~~~~~~~~~~~ The {TechnologyShortName} TCK {TechnologyVersion} is designed as a portable, configurable, automated test suite for verifying the compatibility of a vendor's implementation of the {TechnologyShortName} {TechnologyVersion} Specification. [[GBFQV]][[tck-specifications-and-requirements]] 1.2.1 TCK Specifications and Requirements ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This section lists the applicable requirements and specifications. * Specification Requirements: Software requirements for a {TechnologyShortName} implementation are described in detail in the {TechnologyShortName} {TechnologyVersion} Specification. Links to the {TechnologyShortName} specification and other product information can be found at {SpecificationURL}. * {TechnologyShortName} Version: The {TechnologyShortName} {TechnologyVersion} TCK is based on the {TechnologyShortName} Specification, Version {TechnologyVersion}. * Compatible Implementation: One {TechnologyShortName} {TechnologyVersion} Compatible Implementation, {TechnologyRI} is available from the Eclipse EE4J project (https://projects.eclipse.org/projects/ee4j). See the CI documentation page at {TechnologyRIURL} for more information. See the {TechnologyShortName} TCK Release Notes for more specific information about Java SE version requirements, supported platforms, restrictions, and so on. [[GBFSQ]][[tck-components]] 1.2.2 TCK Components ^^^^^^^^^^^^^^^^^^^^ The {TechnologyShortName} TCK {TechnologyVersion} includes the following components: * {TechnologyShortName} TCK signature tests; check that all public APIs are supported and/or defined as specified in the {TechnologyShortName} Version {TechnologyVersion} implementation under test. * If applicable, an exclude list, which provides a list of tests that your implementation is not required to pass. ifndef::no-api-tests[] * API tests for all of the {TechnologyShortName} API in all related packages: include::packages.inc[] endif::no-api-tests[] ifdef::end-to-end-tests[] * End-to-end tests that demonstrate compliance with the {TechnologyFullName} Specification. endif::end-to-end-tests[] The {TechnologyShortName} TCK tests run on the following platforms: include::platforms.inc[] [[GBFRA]][[tck-compatibility-test-suite]] 1.2.3 TCK Compatibility Test Suite ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The test suite is the collection of tests used by the JavaTest harness to test a particular technology implementation. In this case, it is the collection of tests used by the {TechnologyShortName} TCK {TechnologyVersion} to test a {TechnologyShortName} {TechnologyVersion} implementation. The tests are designed to verify that a vendor's runtime implementation of the technology complies with the appropriate specification. The individual tests correspond to assertions of the specification. The tests that make up the TCK compatibility test suite are precompiled and indexed within the TCK test directory structure. When a test run is started, the JavaTest harness scans through the set of tests that are located under the directories that have been selected. While scanning, the JavaTest harness selects the appropriate tests according to any matches with the filters you are using and queues them up for execution. [[GBFSH]][[exclude-lists]] 1.2.4 Exclude Lists ^^^^^^^^^^^^^^^^^^^ Each version of a TCK includes an Exclude List contained in a `TCK-Exclude-List.txt` file. This is a list of test file URLs that identify tests which do not have to be run for the specific version of the TCK being used. Whenever tests are run, the Junit framework automatically excludes these tests from being executed as those are disabled using '@Disabled' tag in JUnit. A vendor's compatible implementation is not required to pass or run any test on the Exclude List. The Exclude List file, +{excludeListFileName}+, is documented in the {TechnologyShortName} TCK. Please note this file is not parsed to exclude any test and is only for documentation purpose. [NOTE] ======================================================================= From time to time, updates to the Exclude List are made available. The exclude list is included in the TCK ZIP archive. Each time an update is approved and released, the version number will be incremented. You should always make sure you are using an up-to-date copy of the Exclude List before running the {TechnologyShortName} TCK to verify your implementation. ======================================================================= A test might be in the Exclude List for reasons such as: * An error in an underlying implementation API has been discovered which does not allow the test to execute properly. * An error in the specification that was used as the basis of the test has been discovered. * An error in the test itself has been discovered. * The test fails due to a bug in the tools used to run the test. In addition, all tests are run against the compatible implementations. Any tests that fail when run on a compatible Jakarta platform are put on the Exclude List. Any test that is not specification-based, or for which the specification is vague, may be excluded. Any test that is found to be implementation dependent (based on a particular thread scheduling model, based on a particular file system behavior, and so on) may be excluded. [NOTE] ======================================================================= Vendors are not permitted to alter or modify Exclude Lists. Changes to an Exclude List can only be made by using the procedure described in link:rules.html#CJAJEAEI[Section 2.3.1, "TCK Test Appeals Steps."] ======================================================================= [[GBFRR]][[tck-configuration]] 1.2.5 TCK Configuration ^^^^^^^^^^^^^^^^^^^^^^^ You need to set several variables in your test environment, and run the {TechnologyShortName} tests, as described in link:config.html#GBFVV[Chapter 4, "Setup and Configuration."] include::intro.inc[] [[GBFQW]][[getting-started-with-the-tck]] [NOTE] ==== The Jakarta EE Specification Process support multiple compatible implementations. These instructions explain how to get started with the {TechnologyRI} CI. If you are using another compatible implementation, refer to material provided by that implementation for specific instructions and procedures. ==== 1.3 Getting Started With the TCK ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This section provides an general overview of what needs to be done to install, set up, test, and use the {TechnologyShortName} TCK. These steps are explained in more detail in subsequent chapters of this guide. 1. Make sure that the following software has been correctly installed on the system: + -- include::req-software.inc[] * Java SE {SEversion} * A CI for {TechnologyShortName} {TechnologyVersion}. One example is {TechnologyRI}. * The {TechnologyShortName} {TechnologyVersion} Vendor Implementation (VI) + * Any Jupiter API compatible test runner -- See the documentation for each of these software applications for installation instructions. See link:install.html#GBFTP[Chapter 3, "Installation,"] for instructions on installing the {TechnologyShortName} TCK. 2. Set up the {TechnologyShortName} TCK software. + See link:config.html#GBFVV[Chapter 4, "Setup and Configuration,"] for details about the following steps. a. Set up your shell environment. b. Set the required System properties. 3. Test the {TechnologyShortName} {TechnologyVersion} implementation. + Test the {TechnologyShortName} implementation installation by running the test suite. See link:using.html#GBFWO[Chapter 5, "Executing Tests."] jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/intro.inc000066400000000000000000000000001451447132700270440ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/packages.inc000066400000000000000000000001031451447132700274730ustar00rootroot00000000000000** `jakarta.json` ** `jakarta.json.spi` ** `jakarta.json.stream` jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/platforms.inc000066400000000000000000000000201451447132700277220ustar00rootroot00000000000000* CentOS Linux 7jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/preface.adoc000066400000000000000000000104261451447132700274700ustar00rootroot00000000000000type=page status=published title=Preface next=intro.html prev=title.html ~~~~~~ include::attributes.conf[] Preface ======= [[TCJRS00001]][[GBFTI]] [[preface]] Preface ------- This guide describes how to install, configure, and run the Technology Compatibility Kit (TCK) that is used to test the {TechnologyFullName} ({TechnologyShortName} {TechnologyVersion}) technology. The {TechnologyShortName} TCK is a portable, configurable automated test suite for verifying the compatibility of a vendor's implementation of the {TechnologyShortName} {TechnologyVersion} Specification (hereafter referred to as the vendor implementation or VI). The {TechnologyShortName} TCK uses the Junit framework to run the test suite [NOTE] ======================================================================= Note All references to specific Web URLs are given for the sake of your convenience in locating the resources quickly. These references are always subject to changes that are in many cases beyond the control of the authors of this guide. ======================================================================= Jakarta EE is a community sponsored and community run program. Organizations contribute, along side individual contributors who use, evolve and assist others. Commercial support is not available through the Eclipse Foundation resources. Please refer to the Eclipse EE4J project site (https://projects.eclipse.org/projects/ee4j). There, you will find additional details as well as a list of all the associated sub-projects (Implementations and APIs), that make up Jakarta EE and define these specifications. If you have questions about this Specification you may send inquiries to {SpecificationInquiryList}. If you have questions about this TCK, you may send inquiries to {TCKInquiryList}. [[TCJRS00034]][[GBFUS]] [[who-should-use-this-book]] Who Should Use This Book ~~~~~~~~~~~~~~~~~~~~~~~~ This guide is for vendors that implement the {TechnologyShortName} {TechnologyVersion} technology to assist them in running the test suite that verifies compatibility of their implementation of the {TechnologyShortName} {TechnologyVersion} Specification. [[TCJRS00035]][[GBFPO]] [[before-you-read-this-book]] Before You Read This Book ~~~~~~~~~~~~~~~~~~~~~~~~~ You should be familiar with the {TechnologyShortName} {TechnologyVersion}, version {TechnologyVersion} Specification, which can be found at {SpecificationURL}. [[TCJRS00036]][[GBFWF]] [[typographic-conventions]] Typographic Conventions ~~~~~~~~~~~~~~~~~~~~~~~ The following table describes the typographic conventions that are used in this book. [width="100%",cols="15%,40%,45%",options="header",] |======================================================================= |Convention |Meaning |Example |*Boldface* |Boldface type indicates graphical user interface elements associated with an action, terms defined in text, or what you type, contrasted with onscreen computer output. a| From the *File* menu, select *Open Project*. A *cache* is a copy that is stored locally. `machine_name% *su*` + `Password:` |`Monospace` |Monospace type indicates the names of files and directories, commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter. a| Edit your `.login` file. Use `ls` `-a` to list all files. `machine_name% you have mail.` |_Italic_ |Italic type indicates book titles, emphasis, or placeholder variables for which you supply particular values. a| Read Chapter 6 in the _User's Guide_. Do _not_ save the file. The command to remove a file is `rm` _filename_. |======================================================================= [[TCJRS00037]][[FWBSD]] [[shell-prompts-in-command-examples]] Shell Prompts in Command Examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following table shows the default UNIX system prompt and superuser prompt for the C shell, Bourne shell, and Korn shell. [width="100%",cols="50%,50%",options="header",] |===================================================== |Shell |Prompt |C shell |`machine_name%` |C shell for superuser |`machine_name#` |Bourne shell and Korn shell |`$` + |Bourne shell and Korn shell for superuser |`#` + |Bash shell |`shell_name-shell_version$` |Bash shell for superuser |`shell_name-shell_version#` |===================================================== jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/rebuild.adoc000066400000000000000000000004761451447132700275150ustar00rootroot00000000000000type=page status=published title=Appendix B: Rebuild Rules prev=faq.html ~~~~~~ include::attributes.conf[] Appendix B: Rebuild Rules ========================= ifdef::rebuild[] include::rebuild.inc[] endif::rebuild[] ifndef::rebuild[] <<< Appendix B is not used for the {TechnologyShortName} TCK. endif::rebuild[] jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/rebuild.inc000066400000000000000000000004361451447132700273540ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////// NOTE TO WRITERS: The following sections should be customized for the technology. See the JAXRS for an example of this include file /////////////////////////////////////////////////////////////////////// [[GCLIZ]] jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/req-software.inc000066400000000000000000000007441451447132700303470ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////// NOTE TO WRITERS: This is a list of software required in addition to the TCK and the RI. For many Java EE APIs, the Java EE RI will be required, as described below. For standalone technologies, no other software may be required, and the below line can be removed. This is used in intro.adoc in section 1.3 and install.adoc in section 3.2. /////////////////////////////////////////////////////////////////////// jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/rules.adoc000066400000000000000000000443341451447132700272220ustar00rootroot00000000000000type=page status=published title=Procedure for Certification next=install.html prev=intro.html ~~~~~~ include::attributes.conf[] Procedure for Certification =========================== [[GBFSN]] [[procedure-for-certification]] 2 Procedure for Certification ----------------------------- This chapter describes the compatibility testing procedure and compatibility requirements for {TechnologyFullName}. This chapter contains the following sections: * link:#CJAFFDGI[Certification Overview] * link:#CJAFGIGG[Compatibility Requirements] * link:#CJAIIBDJ[Test Appeals Process] * link:#CJAJECIE[Specifications for {TechnologyFullName}] * link:#CJABAHGI[Libraries for {TechnologyFullName}] [[CJAFFDGI]][[certification-overview]] 2.1 Certification Overview ~~~~~~~~~~~~~~~~~~~~~~~~~~ The certification process for {technologyShortName} {TechnologyVersion} consists of the following activities: * Install the appropriate version of the Technology Compatibility Kit (TCK) and execute it in accordance with the instructions in this User's Guide. * Ensure that you meet the requirements outlined in link:#CJAFGIGG[Compatibility Requirements] below. * Certify to the Eclipse Foundation that you have finished testing and that you meet all of the compatibility requirements, as required by the Eclipse Foundation TCK License. [[CJAFGIGG]][[compatibility-requirements]] 2.2 Compatibility Requirements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The compatibility requirements for {TechnologyShortName} {TechnologyVersion} consist of meeting the requirements set forth by the rules and associated definitions contained in this section. [[sthref4]][[definitions]] 2.2.1 Definitions ^^^^^^^^^^^^^^^^^ These definitions are for use only with these compatibility requirements and are not intended for any other purpose. [[sthref5]][[sthref6]] Table 2-1 Definitions  [width="100%",cols="25%,75%",options="header",] |======================================================================= |Term |Definition |API Definition Product |A Product for which the only Java class files contained in the product are those corresponding to the application programming interfaces defined by the Specifications, and which is intended only as a means for formally specifying the application programming interfaces defined by the Specifications. |Computational Resource a| A piece of hardware or software that may vary in quantity, existence, or version, which may be required to exist in a minimum quantity and/or at a specific or minimum revision level so as to satisfy the requirements of the Test Suite. Examples of computational resources that may vary in quantity are RAM and file descriptors. Examples of computational resources that may vary in existence (that is, may or may not exist) are graphics cards and device drivers. Examples of computational resources that may vary in version are operating systems and device drivers. |Configuration Descriptor |Any file whose format is well defined by a specification and which contains configuration information for a set of Java classes, archive, or other feature defined in the specification. |Conformance Tests |All tests in the Test Suite for an indicated Technology Under Test, as released and distributed by the Eclipse Foundation, excluding those tests on the published Exclude List for the Technology Under Test. |Container |An implementation of the associated Libraries, as specified in the Specifications, and a version of a Java Platform, Standard Edition Runtime Product, as specified in the Specifications, or a later version of a Java Platform, Standard Edition Runtime Product that also meets these compatibility requirements. |Documented |Made technically accessible and made known to users, typically by means such as marketing materials, product documentation, usage messages, or developer support programs. |Exclude List |The most current list of tests, released and distributed by the Eclipse Foundation, that are not required to be passed to certify conformance. The Jakarta EE Specification Committee may add to the Exclude List for that Test Suite as needed at any time, in which case the updated TCK version supplants any previous Exclude Lists for that Test Suite. |Libraries a| The class libraries, as specified through the Jakarta EE Specification Process (JESP), for the Technology Under Test. The Libraries for {TechnologyFullName} are listed at the end of this chapter. |Location Resource a| A location of classes or native libraries that are components of the test tools or tests, such that these classes or libraries may be required to exist in a certain location in order to satisfy the requirements of the test suite. For example, classes may be required to exist in directories named in a CLASSPATH variable, or native libraries may be required to exist in directories named in a PATH variable. |Maintenance Lead |The corresponding Jakarta EE Specification Project is responsible for maintaining the Specification, and the TCK for the Technology. The Specification Project Team will propose revisions and updates to the Jakarta EE Specification Committee which will approve and release new versions of the specification and TCK. |Operating Mode a| Any Documented option of a Product that can be changed by a user in order to modify the behavior of the Product. For example, an Operating Mode can be binary (enable/disable optimization), an enumeration (select from a list of protocols), or a range (set the maximum number of active threads). Note that an Operating Mode may be selected by a command line switch, an environment variable, a GUI user interface element, a configuration or control file, etc. |Product |A vendor's product in which the Technology Under Test is implemented or incorporated, and that is subject to compatibility testing. |Product Configuration a| A specific setting or instantiation of an Operating Mode. For example, a Product supporting an Operating Mode that permits user selection of an external encryption package may have a Product Configuration that links the Product to that encryption package. |Rebuildable Tests |Tests that must be built using an implementation-specific mechanism. This mechanism must produce specification-defined artifacts. Rebuilding and running these tests against a known compatible implementation verifies that the mechanism generates compatible artifacts. |Resource |A Computational Resource, a Location Resource, or a Security Resource. |Rules |These definitions and rules in this Compatibility Requirements section of this User's Guide. |Runtime |The Containers specified in the Specifications. |Security Resource a| A security privilege or policy necessary for the proper execution of the Test Suite. For example, the user executing the Test Suite will need the privilege to access the files and network resources necessary for use of the Product. |Specifications a| The documents produced through the Jakarta EE Specification Process (JESP) that define a particular Version of a Technology. The Specifications for the Technology Under Test are referenced later in this chapter. |Technology |Specifications and one or more compatible implementations produced through the Jakarta EE Specification Process (JESP). |Technology Under Test |Specifications and a compatible implementation for {TechnologyFullName} Version {TechnologyVersion}. |Test Suite |The requirements, tests, and testing tools distributed by the Maintenance Lead as applicable to a given Version of the Technology. |Version |A release of the Technology, as produced through the Jakarta EE Specification Process (JESP). include::defns.inc[] |======================================================================= [[sthref7]][[rules-for-products]] 2.2.2 Rules for {TechnologyFullName} Products ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The following rules apply for each version of an operating system, software component, and hardware platform Documented as supporting the Product: *{techID}1* The Product must be able to satisfy all applicable compatibility requirements, including passing all Conformance Tests, in every Product Configuration and in every combination of Product Configurations, except only as specifically exempted by these Rules. For example, if a Product provides distinct Operating Modes to optimize performance, then that Product must satisfy all applicable compatibility requirements for a Product in each Product Configuration, and combination of Product Configurations, of those Operating Modes. *{techID}1.1* If an Operating Mode controls a Resource necessary for the basic execution of the Test Suite, testing may always use a Product Configuration of that Operating Mode providing that Resource, even if other Product Configurations do not provide that Resource. Notwithstanding such exceptions, each Product must have at least one set of Product Configurations of such Operating Modes that is able to pass all the Conformance Tests. For example, a Product with an Operating Mode that controls a security policy (i.e., Security Resource) which has one or more Product Configurations that cause Conformance Tests to fail may be tested using a Product Configuration that allows all Conformance Tests to pass. *{techID}1.2* A Product Configuration of an Operating Mode that causes the Product to report only version, usage, or diagnostic information is exempted from these compatibility rules. *{techID}1.3* An API Definition Product is exempt from all functional testing requirements defined here, except the signature tests. *{techID}2* Some Conformance Tests may have properties that may be changed. Properties that can be changed are identified in the configuration interview. Properties that can be changed are identified in the JavaTest Environment (.jte) files in the Test Suite installation. Apart from changing such properties and other allowed modifications described in this User's Guide (if any), no source or binary code for a Conformance Test may be altered in any way without prior written permission. Any such allowed alterations to the Conformance Tests will be provided via the Jakarta EE Specification Project website and apply to all vendor compatible implementations. *{techID}3* The testing tools supplied as part of the Test Suite or as updated by the Maintenance Lead must be used to certify compliance. *{techID}4* The Exclude List associated with the Test Suite cannot be modified. *{techID}5* The Maintenance Lead can define exceptions to these Rules. Such exceptions would be made available as above, and will apply to all vendor implementations. *{techID}6* All hardware and software component additions, deletions, and modifications to a Documented supporting hardware/software platform, that are not part of the Product but required for the Product to satisfy the compatibility requirements, must be Documented and available to users of the Product. For example, if a patch to a particular version of a supporting operating system is required for the Product to pass the Conformance Tests, that patch must be Documented and available to users of the Product. *{techID}7* The Product must contain the full set of public and protected classes and interfaces for all the Libraries. Those classes and interfaces must contain exactly the set of public and protected methods, constructors, and fields defined by the Specifications for those Libraries. No subsetting, supersetting, or modifications of the public and protected API of the Libraries are allowed except only as specifically exempted by these Rules. *{techID}7.1* If a Product includes Technologies in addition to the Technology Under Test, then it must contain the full set of combined public and protected classes and interfaces. The API of the Product must contain the union of the included Technologies. No further modifications to the APIs of the included Technologies are allowed. ifdef::subset-allowed[] *{techID}7.2* The Product may contain a subset of the classes and interfaces for the Libraries. endif::subset-allowed[] *{techID}8* Except for tests specifically required by this TCK to be rebuilt (if any), the binary Conformance Tests supplied as part of the Test Suite or as updated by the Maintenance Lead must be used to certify compliance. *{techID}9* The functional programmatic behavior of any binary class or interface must be that defined by the Specifications. include::rules.inc[] [[CJAIIBDJ]][[test-appeals-process]] 2.3 Test Appeals Process ~~~~~~~~~~~~~~~~~~~~~~~~ Jakarta has a well established process for managing challenges to its TCKs. Any implementor may submit a challenge to one or more tests in the {TechnologyShortName} TCK as it relates to their implementation. Implementor means the entity as a whole in charge of producing the final certified release. *Challenges filed should represent the consensus of that entity*. 2.3.1 Valid Challenges ^^^^^^^^^^^^^^^^^^^^^^ Any test case (e.g., test class, @Test method), test case configuration (e.g., deployment descriptor), test beans, annotations, and other resources considered part of the TCK may be challenged. The following scenarios are considered in scope for test challenges: * Claims that a test assertion conflicts with the specification. * Claims that a test asserts requirements over and above that of the specification. * Claims that an assertion of the specification is not sufficiently implementable. * Claims that a test is not portable or depends on a particular implementation. 2.3.2 Invalid Challenges ^^^^^^^^^^^^^^^^^^^^^^^^ The following scenarios are considered out of scope for test challenges and will be immediately closed if filed: * Challenging an implementation’s claim of passing a test. Certification is an honor system and these issues must be raised directly with the implementation. * Challenging the usefulness of a specification requirement. The challenge process cannot be used to bypass the specification process and raise in question the need or relevance of a specification requirement. * Claims the TCK is inadequate or missing assertions required by the specification. See the Improvement section, which is outside the scope of test challenges. * Challenges that do not represent a consensus of the implementing community will be closed until such time that the community does agree or agreement cannot be made. The test challenge process is not the place for implementations to initiate their own internal discussions. * Challenges to tests that are already excluded for any reason. * Challenges that an excluded test should not have been excluded and should be re-added should be opened as a new enhancement request Test challenges must be made in writing via the {TechnologyShortName} specification project issue tracker as described in link:#CJAJEAEI[Section 2.3.3, "TCK Test Appeals Steps."] All tests found to be invalid will be placed on the Exclude List for that version of the {TechnologyShortName} TCK. [[CJAJEAEI]][[tck-test-appeals-steps]] 2.3.3 TCK Test Appeals Steps ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Challenges should be filed via the {TechnologyFullName} specification project’s issue tracker using the label `challenge` and include the following information: * The relevant specification version and section number(s) * The coordinates of the challenged test(s) * The exact TCK and exclude list versions * The implementation being tested, including name and company * The full test name * A full description of why the test is invalid and what the correct behavior is believed to be * Any supporting material; debug logs, test output, test logs, run scripts, etc. 2. Specification project evaluates the challenge. + Challenges can be resolved by a specification project lead, or a project challenge triage team, after a consensus of the specification project committers is reached or attempts to gain consensus fails. Specification projects may exercise lazy consensus, voting or any practice that follows the principles of Eclipse Foundation Development Process. The expected timeframe for a response is two weeks or less. If consensus cannot be reached by the specification project for a prolonged period of time, the default recommendation is to exclude the tests and address the dispute in a future revision of the specification. 3. Accepted Challenges. + A consensus that a test produces invalid results will result in the exclusion of that test from certification requirements, and an immediate update and release of an official distribution of the TCK including the new exclude list. The associated `challenge` issue must be closed with an `accepted` label to indicate it has been resolved. 4. Rejected Challenges and Remedy. + When a`challenge` issue is rejected, it must be closed with a label of `invalid` to indicate it has been rejected. There appeal process for challenges rejected on technical terms is outlined in Escalation Appeal. If, however, an implementer feels the TCK challenge process was not followed, an appeal issue should be filed with specification project’s TCK issue tracker using the label `challenge-appeal`. A project lead should escalate the issue with the Jakarta EE Specification Committee via email (jakarta.ee-spec@eclipse.org). The committee will evaluate the matter purely in terms of due process. If the appeal is accepted, the original TCK challenge issue will be reopened and a label of `appealed-challenge` added, along with a discussion of the appeal decision, and the `challenge-appeal` issue with be closed. If the appeal is rejected, the `challenge-appeal` issue should closed with a label of `invalid`. 5. Escalation Appeal. + If there is a concern that a TCK process issue has not been resolved satisfactorily, the https://www.eclipse.org/projects/dev_process/#6_5_Grievance_Handling[Eclipse Development Process Grievance Handling] procedure should be followed to escalate the resolution. Note that this is not a mechanism to attempt to handle implementation specific issues. [[CJAJECIE]][[specifications-for-technology]] 2.4 Specifications for {TechnologyFullName} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The {TechnologyFullName} specification is available from the specification project web-site: {SpecificationURL}. [[CJABAHGI]][[libraries-for-technology]] 2.5 Libraries for {TechnologyFullName} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following is a list of the packages comprising the required class libraries for {TechnologyShortName} {TechnologyVersion}: include::packages.inc[] For the latest list of packages, also see: {SpecificationURL} jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/rules.inc000066400000000000000000000073641451447132700270670ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////// NOTE TO WRITERS: Most technologies will only need the compatibility rules in rules.adoc. Some technologies will need additional rules. If they're needed, remove the comment block delimiters below and update the rules as appropriate. You may need to adjust the rule numbers to avoid gaps. The first comment block below is additional rules needed by JPA. The second comment block below is additional rules needed by JSP and Servlet. (And EJB, if it had a standalone TCK.) The third comment block below is additional rules that apply to any technology that defines deployment descriptors. The fourth comment block is special rules that apply only to JSP. NOTE: This set of examples is NOT complete, but should be. /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// *{techID}10* The Runtime must report an error when processing a Configuration Descriptor that does not conform to the Specifications. *{techID}11* An error must be reported when processing a configuration descriptor that includes a Java Persistence QL expression that does not conform to the Specifications. *{techID}12* The presence of an XML comment in a Configuration Descriptor, when processed by the Runtime, must not cause the functional programmatic behavior of the Runtime to vary from the functional programmatic behavior of the Runtime in the absence of that comment. /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// *{techID}10* Each Container must make technically accessible all Java SE Runtime interfaces and functionality, as defined by the Specifications, to programs running in the Container, except only as specifically exempted by these Rules. *{techID}10.1* Containers may impose security constraints, as defined by the Specifications. /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// *{techID}11* A Deployment Tool must report an error when processing a Configuration Descriptor that does not conform to the Specifications. *{techID}12* The presence of an XML comment in a Configuration Descriptor, when processed by a Deployment Tool, must not cause the functional programmatic behavior of the Deployment Tool to vary from the functional programmatic behavior of the Deployment Tool in the absence of that comment. /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// *{techID}11* A web Container must report an error, as defined by the Specifications, when processing a JSP Page that does not conform to the Specifications. *{techID}12* The presence of a Java language comment or Java language directive in a JSP Page that specifies ”java” as the scripting language, when processed by a web Container, must not cause the functional programmatic behavior of that JSP Page to vary from the functional programmatic behavior of that JSP Page in the absence of that Java language comment or Java language directive. *{techID}13* The contents of any fixed template data (defined by the Specifications) in a JSP Page, when processed by a web Container, must not affect the functional programmatic behavior of that JSP Page, except as defined by the Specifications. *{techID}14* The functional programmatic behavior of a JSP Page that specifies ”java” as the scripting language must be equivalent to the functional programmatic behavior of the JSP Page Implementation Class constructed from that JSP Page. /////////////////////////////////////////////////////////////////////// jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/tck-packages.inc000066400000000000000000000000001451447132700302460ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/title.adoc000066400000000000000000000021011451447132700271730ustar00rootroot00000000000000type=page status=published title=TCK User's Guide for Technology Implementors next=preface.html prev=toc.html ~~~~~~ include::attributes.conf[] TCK User's Guide for {TechnologyFullName}, Release {TechnologyVersion} for Jakarta EE ===================================================================================== [[eclipse-foundation]] Eclipse Foundation ------------------ Technology Compatibility Kit User's Guide for {TechnologyFullName} Release {TechnologyVersion} for Jakarta EE {ReleaseDate} [[sthref1]] ''''' Technology Compatibility Kit User's Guide for {TechnologyFullName}, Release {TechnologyVersion} for Jakarta EE Copyright © {CopyrightDates} Oracle and/or its affiliates. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v. 2.0, which is available at http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0 Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. include::title.inc[] jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/title.inc000066400000000000000000000011461451447132700270460ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////// NOTE TO WRITERS: This is included at the tail end of the Title page. The following section should be customized for the technology. This is provided to allow each technology to customize legacy acronym names that are used in this TCK. Be sure to customize LegacyAcronym in attributes.conf Add additional lines as needed for acronyms found in your TCK user guide. /////////////////////////////////////////////////////////////////////// References in this document to {LegacyAcronym} refer to the {TechnologyFullName} unless otherwise noted. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/toc.adoc000066400000000000000000000075331451447132700266550ustar00rootroot00000000000000type=page status=published title=TCK User's Guide for Technology Implementors next=title.html ~~~~~~ include::attributes.conf[] TCK User's Guide for Technology Implementors ============================================ [[contents]] Contents -------- * link:title.html#eclipse-foundation[Eclipse Foundation] link:preface.html#GBFTI[Preface] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:preface.html#GBFUS[Who Should Use This Book] ** link:preface.html#GBFPO[Before You Read This Book] ** link:preface.html#GBFWF[Typographic Conventions] ** link:preface.html#FWBSD[Shell Prompts in Command Examples] link:intro.html#GBFOW[1 Introduction] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:intro.html#GBFTK[1.1 Compatibility Testing] *** link:intro.html#GBFQN[1.1.1 Why Compatibility Testing is Important] *** link:intro.html#GBFPR[1.1.2 TCK Compatibility Rules] *** link:intro.html#GBFPW[1.1.3 TCK Overview] *** link:intro.html#GBFPB[1.1.4 Jakarta EE Specification Process (JESP) Program and Compatibility Testing] ** link:intro.html#GBFQR[1.2 About the TCK] *** link:intro.html#GBFQV[1.2.1 TCK Specifications and Requirements] *** link:intro.html#GBFSQ[1.2.2 TCK Components] *** link:intro.html#GBFRA[1.2.3 TCK Compatibility Test Suite] *** link:intro.html#GBFSH[1.2.4 Exclude Lists] *** link:intro.html#GBFRR[1.2.5 TCK Configuration] ** link:intro.html#GBFQW[1.3 Getting Started With the TCK] [[procedure-for-certification]] link:rules.html#GBFSN[2 Procedure for Certification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:rules.html#CJAFFDGI[2.1 Certification Overview] ** link:rules.html#CJAFGIGG[2.2 Compatibility Requirements] *** link:rules.html#definitions[2.2.1 Definitions] *** link:rules.html#sthref7[2.2.2 Rules for {TechnologyFullName} Products] ** link:rules.html#CJAIIBDJ[2.3 Test Appeals Process] *** link:rules.html#[2.3.1 Valid Challenges] *** link:rules.html#[2.3.2 Invalid Challenges] *** link:rules.html#CJAJEAEI[2.3.3 TCK Test Appeals Steps] ** link:rules.html#CJAJECIE[2.4 Specifications for {TechnologyFullName}] ** link:rules.html#CJABAHGI[2.5 Libraries for {TechnologyFullName}] link:install.html#GBFTP[3 Installation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:install.html#GBFUD[3.1 Obtaining a Compatible Implementation] ** link:install.html#GBFTS[3.2 Installing the Software] [[setup-and-configuration]] link:config.html#GBFVV[4 Setup and Configuration] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:config.html#GBFVU[4.1 Configuring Your Environment to Run the TCK Against the Compatible Implementation] ** link:config.html#GCLHU[4.2 Configuring Your Environment to Run the TCK Against the Vendor Implementation] ** link:config.html#GHGDG[4.3 Publishing the Test Applications] [[executing-tests]] link:using.html#GBFWO[5 Executing Tests] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:using.html#GBFUZ[5.1 Starting the tests] *** link:using.html#GBFVW[5.1.1 To Run All Tests] ** link:using.html#GBFWM[5.2 Running a Subset of the Tests] *** link:using.html#GBFWK[5.2.1 To Run a Single Test] *** link:using.html#GCMCA[5.2.2 To Run a Subset of Tests] *** link:using.html#GCMCU[5.2.3 To Run Signature Tests] ** link:using.html#GCLRR[5.3 Running the TCK Against another CI] ** link:using.html#GCLRZ[5.4 Running the TCK Against a Vendor's Implementation] ** link:using.html#GBFVK[5.5 Test Reports] [[debugging-test-problems]] link:debug.html#GBFUV[6 Debugging Test Problems] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:debug.html#GBFYP[6.1 Overview] ** link:debug.html#GBFYF[6.2 Configuration Failures] [[a-frequently-asked-questions]] link:faq.html#GBFYD[A Frequently Asked Questions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** link:faq.html#GBFYQ[A.1 Where do I start to debug a test failure?] ** link:faq.html#GBFYR[A.2 How do I restart a crashed test run?] ** link:faq.html#GBFWU[A.3 What would cause tests be added to the exclude list?] jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/using.adoc000066400000000000000000000121441451447132700272070ustar00rootroot00000000000000type=page status=published title=Executing Tests next=debug.html prev=config.html ~~~~~~ include::attributes.conf[] Executing Tests =============== [[GBFWO]] [[executing-tests]] 5 Executing Tests ----------------- The {TechnologyShortName} TCK uses the Junit framework to execute the tests. This chapter includes the following topics: * link:#GBFUZ[Running All Tests] * link:#GBFWM[Running a Subset of the Tests] * link:#GCLRR[Running the TCK Against your selected CI] * link:#GCLRZ[Running the TCK Against a Vendor's Implementation] * link:#GBFVK[Test Reports] [NOTE] ======================================================================= The instructions in this chapter assume that you have installed and configured your test environment as described in link:install.html#GBFTP[Chapter 3, "Installation,"] and link:config.html#GBFVV[Chapter 4, "Setup and Configuration,"], respectively. ======================================================================= ifdef::rebuild[] As explained in link:rebuild.html#GCLIZ[Appendix B, "Packaging the Test Applications in Servlet-Compliant WAR Files With VI-Specific Information,"] the {TechnologyShortName} TCK introduces the concept of repackaging the TCK tests. endif::rebuild[] [[GBFUZ]][[starting-javatest]] 5.1 Starting the tests ~~~~~~~~~~~~~~~~~~~~~~ The {TechnologyShortName} TCK can be run from the command line in your shell environment by executing tests from the TCK jar. [NOTE] ======================================================================= The `mvn` command referenced in the following two procedures and elsewhere in this guide is the Apache Maven build tool, which will need to be downloaded separately. ======================================================================= [[GBFVW]][[to-start-javatest-in-command-line-mode]] 5.1.1 To Run All Tests ^^^^^^^^^^^^^^^^^^^^^^ To run all tests, enter the following command: [source,subs="attributes"] ---- cd ${TechnologyTCKHomeEnv}/bin mvn verify ---- [[GBFWM]][[running-a-subset-of-the-tests]] 5.2 Running a Subset of the Tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Use the following modes to run a subset of the tests: * link:#GBFWK[Section 5.2.1, "To Run a Single Test"] * link:#GCMCA[Section 5.2.2, "To Run a Subset of Tests"] * link:#GCMCU[Section 5.2.3, "To Run Signature Tests"] [[GBFWK]][[to-run-a-single-test]] 5.2.1 To Run a Single Test ^^^^^^^^^^^^^^^^^^^^^^^^^^ To run a single test, enter the following command: [source,subs="attributes"] ---- cd ${TechnologyTCKHomeEnv}/bin mvn verify -Dtest={singleTestExample} ---- [[GCMCA]][[to-run-a-subset-of-tests]] 5.2.2 To Run a Subset of Tests ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To run a subset of tests, enter the following command: [source,subs="attributes"] ---- cd ${TechnologyTCKHomeEnv}/bin mvn verify -Dtest={subsetTestDirectoryExample} ---- [[GCMCU]][[to-run-signature-tests]] 5.2.3 To Run Signature Tests ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To run the {TechnologyShortName} TCK Signature Tests, enter the following command: [source,subs="attributes"] ---- cd ${TechnologyTCKHomeEnv}/bin mvn verify -Dtest={sigTestExample} ---- [[GCLRR]][[running-the-tck-against-the-ri]] 5.3 Running the TCK Against another CI ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some test scenarios are designed to ensure that the configuration and deployment of all the prebuilt {TechnologyShortName} TCK tests against one Compatible Implementation are successful operating with other compatible implementations, and that the TCK is ready for compatibility testing against the Vendor and Compatible Implementations. 1. Verify that you have followed the configuration instructions in link:config.html#GBFVU[Section 4.1, "Configuring Your Environment to Run the TCK Against the Compatible Implementation."] 2. Run the tests, as described in link:#GBFUZ[Section 5.1, "Starting the Tests"], and, if desired, link:#GBFWM[Section 5.2, "Running a Subset of the Tests."] .Example: [source,subs="attributes"] ---- cd ${TechnologyTCKHomeEnv}/bin mvn verify -Djsonp-impl.groupId=org.eclipse.parsson -Djsonp-impl.artifactId=parsson -Djsonp-impl.version=1.1.0 ---- [[GCLRZ]][[running-the-tck-against-a-vendors-implementation]] 5.4 Running the TCK Against a Vendor's Implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This test scenario is one of the compatibility test phases that all Vendors must pass. 1. Verify that you have followed the configuration instructions in link:config.html#GCLHU[Section 4.2, "Configuring Your Environment to Run the TCK Against the Vendor Implementation."] 2. Run the tests, as described in link:#GBFUZ[Section 5.1, "Starting the Tests"], and, if desired, link:#GBFWM[Section 5.2, "Running a Subset of the Tests."] .Example: [source,subs="attributes"] ---- cd ${TechnologyTCKHomeEnv}/bin mvn verify -Djsonp-api.groupId=jakarta.json -Djsonp-api.artifactId=jakarta.json-api -Djsonp-api.version=2.1.0 ---- [[GBFVK]][[test-reports]] 5.5 Test Reports ~~~~~~~~~~~~~~~~ A set of report files is created for every test run. These report files can be found in the target directory that the test is run. After a test run is completed, the Junit framework writes reports for the test run. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/content/using.inc000066400000000000000000000102211451447132700270440ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////// NOTE TO WRITERS: This include file allows for additional instructions for running the TCK. /////////////////////////////////////////////////////////////////////// [[sthref9]][[running-the-pluggability-tests]] 5.6 Running the Pluggability Tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Use the following modes to run the pluggability tests: * link:#BCGFHIDI[Section 5.6.1, "To Run the Pluggability Tests in GUI Mode"] * link:#BCGEGBGE[Section 5.6.2, "To Run the Pluggability Tests in Command-Line Mode"] [[BCGFHIDI]][[to-run-the-pluggability-tests-in-gui-mode]] 5.6.1 To Run the Pluggability Tests in GUI Mode ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When running JavaTest in GUI mode as described above, you are prompted to specify whether you want to run all or a subset of the test suite. Since the pluggability tests must be run separately from the other tests, select Yes. Select the tests you want to run from the displayed test tree, then select Next. You can select entire branches of the test tree, or use Ctrl+Click or Shift+Click to select multiple tests or ranges of tests, respectively. Select all tests except pluggability tests by unchecking the pluggability tests. After running the other tests, run the pluggability tests, which require a separate test run: 1. If the JavaTest GUI is running, exit the GUI. 2. Change to the `/bin` directory and reconfigure environment to use the `JsonProvider` class that is supplied with the test suite and restart the JavaTest GUI: + [source,oac_no_warn] ---- cd /bin ant enable.alternate.jsonp.provider ant gui ---- 3. Select Configure, then select Edit Configuration. 4. Select Tests to Run. 5. Select the tests you want to run from the displayed test tree, then select Next. + Select the pluggability tests only by unchecking all of the other tests. 6. Select Done. 7. Select Run Tests, then select Start. 8. Exit the JavaTest GUI when finished. 9. Disable the alternate JSON provider that you enabled in Step 2, before you initiated the test run for the pluggability tests: + [source,oac_no_warn] ---- cd /bin ant disable.alternate.jsonp.provider ---- [[BCGEGBGE]][[to-run-the-pluggability-tests-in-command-line-mode]] 5.6.2 To Run the Pluggability Tests in Command-Line Mode ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There are two ways to run the pluggability tests from the command line. It is highly recommended to use the first method, since it automatically calls the Ant targets to enable and disable the test provider. If you choose to use the second method, you will need to execute those Ant targets manually before and after you run the tests. The first method is by executing the `run.pluggability` target in Ant: 1. Execute the `run.pluggability` target using Ant: + [source,oac_no_warn] ---- cd /bin ant run.pluggability ---- The `run.pluggability` target calls Ant targets that enable the test provider, run the pluggability tests, then disable the test provider. The pluggability tests can also be run an alternate way, albeit one that requires more manual intervention: 1. Execute the `enable.alternate.jsonp.provider` target using Ant: + [source,oac_no_warn] ---- cd /bin ant enable.alternate.jsonp.provider ---- The `enable.alternate.jsonp.provider` target enables the alternate test provider. 2. Change to the `` directory: + [source,oac_no_warn] ---- cd ---- 3. Start the pluggability test run by executing the following command: + [source,oac_no_warn] ---- ant runclient ---- This will run just the pluggability tests under the <`TS_HOME/src/com/sun/ts/tests/jsonp/pluggability` directory, using a test-supplied `JsonProvider Class` for testing the SPI. All `JsonProvider` method calls will be invoked and verified by the tests to ensure SPI layer is working. 4. Execute the `disable.alternate.jsonp.provider` target using Ant: + [source,oac_no_warn] ---- cd /bin ant disable.alternate.jsonp.provider ---- The `disable.alternate.jsonp.provider` target disables the alternate test provider. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/jbake.properties000066400000000000000000000015451451447132700267550ustar00rootroot00000000000000# # Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved. # # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v. 2.0, which is available at # http://www.eclipse.org/legal/epl-2.0. # # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the # Eclipse Public License v. 2.0 are satisfied: GNU General Public License, # version 2 with the GNU Classpath Exception, which is available at # https://www.gnu.org/software/classpath/license.html. # # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 # site.host=http://jbake.org render.tags=false render.sitemap=false render.archive=false render.feed=false render.index=false asciidoctor.option.safe=0 asciidoctor.attributes.export=truejsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/templates/000077500000000000000000000000001451447132700255545ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/templates/footer.ftl000066400000000000000000000024111451447132700275570ustar00rootroot00000000000000<#-- a footer template fragment included in the page template -->
<#if content.prev??> <#if content.next??>
Previous Next Contents
Eclipse Foundation Logo  Copyright © 2017, 2022 Oracle and/or its affiliates. All rights reserved. jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/templates/header.ftl000066400000000000000000000030521451447132700275130ustar00rootroot00000000000000 <#-- a header template fragment included in the page template --> <#if (content.title)??><#escape x as x?xml>${content.title}</#escape></#if>
${content.title}

<#if content.prev??> <#if content.next??>
Previous Next Contents
jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/templates/menu.ftl000066400000000000000000000001031451447132700272210ustar00rootroot00000000000000<#-- a menu bar template fragment included in the page template -->jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/main/jbake/templates/page.ftl000066400000000000000000000002021451447132700271710ustar00rootroot00000000000000<#-- a top level page layout template --> <#include "header.ftl"> <#include "menu.ftl"> ${content.body} <#include "footer.ftl">jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/theme/000077500000000000000000000000001451447132700226605ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-docs/userguide/src/theme/jakartaee-theme.yml000066400000000000000000000241571451447132700264430ustar00rootroot00000000000000# # Following is the asciidoctor-pdf default theme [1], with small # customizations, mostly for header and footer, marked "EE". # # [1] https://github.com/asciidoctor/asciidoctor-pdf/blob/master/data/themes/default-theme.yml # font: catalog: # Noto Serif supports Latin, Latin-1 Supplement, Latin Extended-A, Greek, Cyrillic, Vietnamese & an assortment of symbols Noto Serif: normal: notoserif-regular-subset.ttf bold: notoserif-bold-subset.ttf italic: notoserif-italic-subset.ttf bold_italic: notoserif-bold_italic-subset.ttf # M+ 1mn supports ASCII and the circled numbers used for conums M+ 1mn: normal: mplus1mn-regular-ascii-conums.ttf bold: mplus1mn-bold-ascii.ttf italic: mplus1mn-italic-ascii.ttf bold_italic: mplus1mn-bold_italic-ascii.ttf # M+ 1p supports Latin, Latin-1 Supplement, Latin Extended, Greek, Cyrillic, Vietnamese, Japanese & an assortment of symbols # It also provides arrows for ->, <-, => and <= replacements in case these glyphs are missing from font M+ 1p Fallback: normal: mplus1p-regular-fallback.ttf bold: mplus1p-regular-fallback.ttf italic: mplus1p-regular-fallback.ttf bold_italic: mplus1p-regular-fallback.ttf fallbacks: - M+ 1p Fallback page: background_color: ffffff layout: portrait margin: [0.5in, 0.67in, 0.67in, 0.67in] # margin_inner and margin_outer keys are used for recto/verso print margins when media=prepress margin_inner: 0.75in margin_outer: 0.59in #size: A4 # EE size: Letter # EE base: align: justify # color as hex string (leading # is optional) font_color: 333333 # color as RGB array #font_color: [51, 51, 51] # color as CMYK array (approximated) #font_color: [0, 0, 0, 0.92] #font_color: [0, 0, 0, 92%] font_family: Noto Serif # choose one of these font_size/line_height_length combinations #font_size: 14 #line_height_length: 20 #font_size: 11.25 #line_height_length: 18 #font_size: 11.2 #line_height_length: 16 font_size: 10.5 #line_height_length: 15 # correct line height for Noto Serif metrics line_height_length: 12 #font_size: 11.25 #line_height_length: 18 line_height: $base_line_height_length / $base_font_size font_size_large: round($base_font_size * 1.25) font_size_small: round($base_font_size * 0.85) font_size_min: $base_font_size * 0.75 font_style: normal border_color: eeeeee border_radius: 4 border_width: 0.5 # FIXME vertical_rhythm is weird; we should think in terms of ems #vertical_rhythm: $base_line_height_length * 2 / 3 # correct line height for Noto Serif metrics (comes with built-in line height) vertical_rhythm: $base_line_height_length horizontal_rhythm: $base_line_height_length # QUESTION should vertical_spacing be block_spacing instead? vertical_spacing: $vertical_rhythm link: font_color: 428bca # literal is currently used for inline monospaced in prose and table cells literal: font_color: b12146 font_family: M+ 1mn menu_caret_content: " \u203a " heading: align: left #font_color: 181818 font_color: $base_font_color font_family: $base_font_family font_style: bold # h1 is used for part titles (book doctype) or the doctitle (article doctype) #h1_font_size: floor($base_font_size * 2.6) # EE h1_font_size: floor($base_font_size * 2.5) # EE, squeeze title onto one line # h2 is used for chapter titles (book doctype only) h2_font_size: floor($base_font_size * 2.15) h3_font_size: round($base_font_size * 1.7) h4_font_size: $base_font_size_large h5_font_size: $base_font_size h6_font_size: $base_font_size_small #line_height: 1.4 # correct line height for Noto Serif metrics (comes with built-in line height) line_height: 1 margin_top: $vertical_rhythm * 0.4 margin_bottom: $vertical_rhythm * 0.9 title_page: align: right logo: top: 10% title: top: 55% font_size: $heading_h1_font_size font_color: 999999 line_height: 0.9 subtitle: font_size: $heading_h3_font_size font_style: bold_italic line_height: 1 authors: margin_top: $base_font_size * 1.25 font_size: $base_font_size_large font_color: 181818 revision: margin_top: $base_font_size * 1.25 block: margin_top: 0 margin_bottom: $vertical_rhythm caption: align: left font_size: $base_font_size * 0.95 font_style: italic # FIXME perhaps set line_height instead of / in addition to margins? margin_inside: $vertical_rhythm / 3 #margin_inside: $vertical_rhythm / 4 margin_outside: 0 lead: font_size: $base_font_size_large line_height: 1.4 abstract: font_color: 5c6266 font_size: $lead_font_size line_height: $lead_line_height font_style: italic first_line_font_style: bold title: align: center font_color: $heading_font_color font_family: $heading_font_family font_size: $heading_h4_font_size font_style: $heading_font_style admonition: column_rule_color: $base_border_color column_rule_width: $base_border_width padding: [0, $horizontal_rhythm, 0, $horizontal_rhythm] #icon: # tip: # name: fa-lightbulb-o # stroke_color: 111111 # size: 24 label: text_transform: uppercase font_style: bold blockquote: font_color: $base_font_color font_size: $base_font_size_large border_color: $base_border_color border_width: 5 # FIXME disable negative padding bottom once margin collapsing is implemented padding: [0, $horizontal_rhythm, $block_margin_bottom * -0.75, $horizontal_rhythm + $blockquote_border_width / 2] cite_font_size: $base_font_size_small cite_font_color: 999999 # code is used for source blocks (perhaps change to source or listing?) code: font_color: $base_font_color font_family: $literal_font_family font_size: ceil($base_font_size) padding: $code_font_size line_height: 1.25 # line_gap is an experimental property to control how a background color is applied to an inline block element line_gap: 3.8 background_color: f5f5f5 border_color: cccccc border_radius: $base_border_radius border_width: 0.75 conum: font_family: M+ 1mn font_color: $literal_font_color font_size: $base_font_size line_height: 4 / 3 example: border_color: $base_border_color border_radius: $base_border_radius border_width: 0.75 background_color: ffffff # FIXME reenable padding bottom once margin collapsing is implemented padding: [$vertical_rhythm, $horizontal_rhythm, 0, $horizontal_rhythm] image: align: left prose: margin_top: $block_margin_top margin_bottom: $block_margin_bottom sidebar: background_color: eeeeee border_color: e1e1e1 border_radius: $base_border_radius border_width: $base_border_width # FIXME reenable padding bottom once margin collapsing is implemented padding: [$vertical_rhythm, $vertical_rhythm * 1.25, 0, $vertical_rhythm * 1.25] title: align: center font_color: $heading_font_color font_family: $heading_font_family font_size: $heading_h4_font_size font_style: $heading_font_style thematic_break: border_color: $base_border_color border_style: solid border_width: $base_border_width margin_top: $vertical_rhythm * 0.5 margin_bottom: $vertical_rhythm * 1.5 description_list: term_font_style: bold term_spacing: $vertical_rhythm / 4 description_indent: $horizontal_rhythm * 1.25 outline_list: indent: $horizontal_rhythm * 1.5 #marker_font_color: 404040 # NOTE outline_list_item_spacing applies to list items that do not have complex content item_spacing: $vertical_rhythm / 2 table: background_color: $page_background_color #head_background_color: #head_font_color: $base_font_color head_font_style: bold #body_background_color: body_stripe_background_color: f9f9f9 foot_background_color: f0f0f0 border_color: dddddd border_width: $base_border_width cell_padding: 3 toc: indent: $horizontal_rhythm line_height: 1.4 dot_leader: #content: ". " font_color: a9a9a9 #levels: 2 3 # NOTE in addition to footer, header is also supported footer: font_size: $base_font_size_small # NOTE if background_color is set, background and border will span width of page #border_color: dddddd # EE #border_width: 0.25 # EE height: $base_line_height_length * 2.5 line_height: 1 padding: [$base_line_height_length / 2, 1, 0, 1] vertical_align: top #image_vertical_align: or # additional attributes for content: # * {page-count} # * {page-number} # * {document-title} # * {document-subtitle} # * {chapter-title} # * {section-title} # * {section-or-chapter-title} recto: #columns: "<50% =0% >50%" right: #content: '{page-number}' # EE #content: '{section-or-chapter-title} | {page-number}' #content: '{document-title} | {page-number}' content: '{document-title}{nbsp}{nbsp}{nbsp} *{page-number}*' # EE #center: # content: '{page-number}' left: # EE content: '{status}' # EE verso: #columns: $footer_recto_columns left: #content: $footer_recto_right_content # EE #content: '{page-number} | {chapter-title}' content: '*{page-number}* {nbsp}{nbsp}{nbsp}{document-title}' # EE #center: # content: '{page-number}' right: # EE content: '{status}' # EE header: # EE font_size: $base_font_size_small # EE border_color: dddddd # EE border_width: 0.25 # EE height: $base_line_height_length * 2.5 # EE line_height: 1 # EE padding: [$base_line_height_length / 2, 1, 0, 1] # EE vertical_align: top # EE recto: # EE right: # EE content: '{section-or-chapter-title}' # EE verso: # EE left: # EE content: '{section-or-chapter-title}' # EE jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/000077500000000000000000000000001451447132700216775ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/pom.xml000066400000000000000000000043631451447132700232220ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT ../pom.xml jakarta.json-tck-tests-pluggability jar jakarta.json jakarta.json-tck-common org.apache.maven.plugins maven-javadoc-plugin none org.apache.maven.plugins maven-source-plugin attach-sources jar-no-fork jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/000077500000000000000000000000001451447132700224665ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/000077500000000000000000000000001451447132700234125ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/000077500000000000000000000000001451447132700243335ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/000077500000000000000000000000001451447132700247245ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/000077500000000000000000000000001451447132700263415ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/000077500000000000000000000000001451447132700271225ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/000077500000000000000000000000001451447132700302535ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/pluggability/000077500000000000000000000000001451447132700327475ustar00rootroot00000000000000jsonprovidertests/000077500000000000000000000000001451447132700364775ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/pluggabilityClientTests.java000066400000000000000000000431711451447132700416110ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/pluggability/jsonprovidertests/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.pluggability.jsonprovidertests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.Json; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonException; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonReader; import jakarta.json.JsonReaderFactory; import jakarta.json.JsonWriter; import jakarta.json.JsonWriterFactory; import jakarta.json.spi.JsonProvider; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonGeneratorFactory; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParserFactory; import ee.jakarta.tck.jsonp.provider.MyJsonGenerator; import ee.jakarta.tck.jsonp.provider.MyJsonProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final String MY_JSONPROVIDER_CLASS = "ee.jakarta.tck.jsonp.provider.MyJsonProvider"; private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); private String providerPath = null; @AfterEach public void after() { MyJsonProvider.clearCalls(); MyJsonGenerator.clearCalls(); } /* Tests */ /* * @testName: jsonProviderTest1 * * @assertion_ids: JSONP:JAVADOC:152; * * @test_Strategy: Test call of SPI provider method with signature: o public * static JsonProvider provider() */ @Test public void jsonProviderTest1() { boolean pass = true; try { // Load my provider JsonProvider provider = JsonProvider.provider(); String providerClass = provider.getClass().getName(); LOGGER.info("provider class=" + providerClass); if (providerClass.equals(MY_JSONPROVIDER_CLASS)) LOGGER.info("Current provider is my provider - expected."); else { LOGGER.warning("Current provider is not my provider - unexpected."); pass = false; ServiceLoader loader = ServiceLoader.load(JsonProvider.class); Iterator it = loader.iterator(); List providers = new ArrayList<>(); while(it.hasNext()) { providers.add(it.next()); } LOGGER.info("Providers: "+providers); } } catch (Exception e) { fail("jsonProviderTest1 Failed: ", e); } assertTrue(pass, "jsonProviderTest1 Failed"); } /* * @testName: jsonProviderTest2 * * @assertion_ids: JSONP:JAVADOC:144; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonGenerator createGenerator(Writer) */ @Test public void jsonProviderTest2() { boolean pass = true; String expString = "public JsonGenerator createGenerator(Writer)"; String expString2 = "public JsonGenerator writeStartArray()"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonGenerator generator = Json.createGenerator(new StringWriter()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); pass = JSONP_Util.assertEquals(expString, actString); generator.writeStartArray(); String actString2 = MyJsonGenerator.getCalls(); LOGGER.info("Verify SPI generator method was called: " + expString2); pass = JSONP_Util.assertEquals(expString2, actString2); } catch (Exception e) { fail("jsonProviderTest2 Failed: ", e); } assertTrue(pass, "jsonProviderTest2 Failed"); } /* * @testName: jsonProviderTest3 * * @assertion_ids: JSONP:JAVADOC:192; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonGenerator createGenerator(OutputStream) */ @Test public void jsonProviderTest3() { boolean pass = true; String expString = "public JsonGenerator createGenerator(OutputStream)"; String expString2 = "public JsonGenerator writeStartObject()"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonGenerator generator = Json .createGenerator(new ByteArrayOutputStream()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); pass = JSONP_Util.assertEquals(expString, actString); generator.writeStartObject(); String actString2 = MyJsonGenerator.getCalls(); LOGGER.info("Verify SPI generator method was called: " + expString2); pass = JSONP_Util.assertEquals(expString2, actString2); } catch (Exception e) { fail("jsonProviderTest3 Failed: ", e); } assertTrue(pass, "jsonProviderTest3 Failed"); } /* * @testName: jsonProviderTest4 * * @assertion_ids: JSONP:JAVADOC:146; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonParser createParser(Reader) */ @Test public void jsonProviderTest4() { String expString = "public JsonParser createParser(Reader)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonParser parser = Json.createParser(new StringReader("{}")); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest4 Failed"); } catch (Exception e) { fail("jsonProviderTest4 Failed: ", e); } } /* * @testName: jsonProviderTest5 * * @assertion_ids: JSONP:JAVADOC:196; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonParser createParser(InputStream) */ @Test public void jsonProviderTest5() { String expString = "public JsonParser createParser(InputStream)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonParser parser = Json .createParser(JSONP_Util.getInputStreamFromString("{}")); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest5 Failed"); } catch (Exception e) { fail("jsonProviderTest5 Failed: ", e); } } /* * @testName: jsonProviderTest6 * * @assertion_ids: JSONP:JAVADOC:465; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonParserFactory createParserFactory(Map) */ @Test public void jsonProviderTest6() { String expString = "public JsonParserFactory createParserFactory(Map)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest5 Failed"); } catch (Exception e) { fail("jsonProviderTest6 Failed: ", e); } } /* * @testName: jsonProviderTest7 * * @assertion_ids: JSONP:JAVADOC:426; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonParserFactory createParserFactory(Map) */ @Test public void jsonProviderTest7() { String expString = "public JsonParserFactory createParserFactory(Map)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonParserFactory parserFactory = Json .createParserFactory(new HashMap()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest7 Failed"); } catch (Exception e) { fail("jsonProviderTest7 Failed: ", e); } } /* * @testName: jsonProviderTest8 * * @assertion_ids: JSONP:JAVADOC:425; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonGeneratorFactory createGeneratorFactory(Map) */ @Test public void jsonProviderTest8() { String expString = "public JsonGeneratorFactory createGeneratorFactory(Map)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonGeneratorFactory generatorFactory = Json .createGeneratorFactory(new HashMap()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest8 Failed"); } catch (Exception e) { fail("jsonProviderTest8 Failed: ", e); } } /* * @testName: jsonProviderTest9 * * @assertion_ids: JSONP:JAVADOC:472; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonWriterFactory createWriterFactory(Map) */ @Test public void jsonProviderTest9() { String expString = "public JsonWriterFactory createWriterFactory(Map)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonWriterFactory factory = Json .createWriterFactory(JSONP_Util.getEmptyConfig()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest9 Failed"); } catch (Exception e) { fail("jsonProviderTest9 Failed: ", e); } } /* * @testName: jsonProviderTest10 * * @assertion_ids: JSONP:JAVADOC:223; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonParser createParser(InputStream) Tests the case where a JsonException * can be thrown. An InputStream of null will cause MyJsonProvider to throw * JsonException. */ @Test public void jsonProviderTest10() { String expString = "public JsonParser createParser(InputStream)"; try { LOGGER.info("Calling SPI provider method: " + expString); InputStream in = null; JsonParser parser = Json.createParser(in); fail("jsonProviderTest10 Failed"); } catch (JsonException e) { LOGGER.info("Caught expected JsonException: " + e); } catch (Exception e) { fail("jsonProviderTest10 Failed: ", e); } } /* * @testName: jsonProviderTest11 * * @assertion_ids: JSONP:JAVADOC:464; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonArrayBuilder createArrayBuilder() */ @Test public void jsonProviderTest11() { String expString = "public JsonArrayBuilder createArrayBuilder()"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest11 Failed"); } catch (Exception e) { fail("jsonProviderTest11 Failed: ", e); } } /* * @testName: jsonProviderTest12 * * @assertion_ids: JSONP:JAVADOC:466; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonObjectBuilder createObjectBuilder() */ @Test public void jsonProviderTest12() { String expString = "public JsonObjectBuilder createObjectBuilder()"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest12 Failed"); } catch (Exception e) { fail("jsonProviderTest12 Failed: ", e); } } /* * @testName: jsonProviderTest13 * * @assertion_ids: JSONP:JAVADOC:465; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonBuilderFactory createBuilderFactory(Map) */ @Test public void jsonProviderTest13() { String expString = "public JsonBuilderFactory createBuilderFactory(Map)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonBuilderFactory objectBuilder = Json .createBuilderFactory(JSONP_Util.getEmptyConfig()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest13 Failed"); } catch (Exception e) { fail("jsonProviderTest13 Failed: ", e); } } /* * @testName: jsonProviderTest14 * * @assertion_ids: JSONP:JAVADOC:467; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonReader createReader(Reader) */ @Test public void jsonProviderTest14() { String expString = "public JsonReader createReader(Reader)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonReader reader = Json.createReader(new StringReader("{}")); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest14 Failed"); } catch (Exception e) { fail("jsonProviderTest14 Failed: ", e); } } /* * @testName: jsonProviderTest15 * * @assertion_ids: JSONP:JAVADOC:468; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonReader createReader(InputStream) */ @Test public void jsonProviderTest15() { String expString = "public JsonReader createReader(InputStream)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonReader reader = Json .createReader(JSONP_Util.getInputStreamFromString("{}")); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest15 Failed"); } catch (Exception e) { fail("jsonProviderTest15 Failed: ", e); } } /* * @testName: jsonProviderTest16 * * @assertion_ids: JSONP:JAVADOC:470; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonWriter createWriter(Writer) */ @Test public void jsonProviderTest16() { String expString = "public JsonWriter createWriter(Writer)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonWriter writer = Json.createWriter(new StringWriter()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest16 Failed"); } catch (Exception e) { fail("jsonProviderTest16 Failed: ", e); } } /* * @testName: jsonProviderTest17 * * @assertion_ids: JSONP:JAVADOC:471; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonWriter createWriter(OutputStream) */ @Test public void jsonProviderTest17() { String expString = "public JsonWriter createWriter(OutputStream)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonWriter writer = Json.createWriter(new ByteArrayOutputStream()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest17 Failed"); } catch (Exception e) { fail("jsonProviderTest17 Failed: ", e); } } /* * @testName: jsonProviderTest18 * * @assertion_ids: JSONP:JAVADOC:469; * * @test_Strategy: Test call of SPI provider method with signature: o public * JsonReaderFactory createReaderFactory(Map) */ @Test public void jsonProviderTest18() { String expString = "public JsonReaderFactory createReaderFactory(Map)"; try { LOGGER.info("Calling SPI provider method: " + expString); JsonReaderFactory factory = Json .createReaderFactory(JSONP_Util.getEmptyConfig()); String actString = MyJsonProvider.getCalls(); LOGGER.info("Verify SPI provider method was called: " + expString); assertTrue(JSONP_Util.assertEquals(expString, actString), "jsonProviderTest18 Failed"); } catch (Exception e) { fail("jsonProviderTest18 Failed: ", e); } } } jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/000077500000000000000000000000001451447132700321055ustar00rootroot00000000000000MyJsonGenerator.java000066400000000000000000000156501451447132700357660ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.logging.Logger; import jakarta.json.*; import jakarta.json.stream.*; /* * MyJsonGenerator is a Json Test Generator used by the pluggability tests * to test the Json SPI layer. This generator tracks that the proper callback * methods are invoked within the generator when Json API methods are called. */ public class MyJsonGenerator implements JsonGenerator { private static final Logger LOGGER = Logger.getLogger(MyJsonGenerator.class.getName()); private Writer writer = null; private OutputStream out = null; private final Charset charset = Charset.forName("UTF-8"); private void dumpInstanceVars() { LOGGER.info("writer=" + writer); LOGGER.info("out=" + out); LOGGER.info("charset=" + charset); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonGenerator(Writer writer) { this.writer = writer; } public MyJsonGenerator(OutputStream out) { this.out = out; } @Override public void flush() { LOGGER.info("public void flush()"); addCalls("public void flush()"); } @Override public JsonGenerator writeStartObject() { LOGGER.info("public JsonGenerator writeStartObject()"); addCalls("public JsonGenerator writeStartObject()"); return null; } @Override public JsonGenerator writeStartObject(String name) { LOGGER.info("public JsonGenerator writeStartObject(String)"); addCalls("public JsonGenerator writeStartObject(String)"); return null; } @Override public JsonGenerator write(String name, String value) { LOGGER.info("public JsonGenerator write(String,String)"); addCalls("public JsonGenerator write(String,String)"); return null; } @Override public JsonGenerator write(String name, int value) { LOGGER.info("public JsonGenerator write(String,int)"); addCalls("public JsonGenerator write(String,int)"); return null; } @Override public JsonGenerator write(String name, long value) { LOGGER.info("public JsonGenerator write(String,long)"); addCalls("public JsonGenerator write(String,long)"); return null; } @Override public JsonGenerator write(String name, double value) { LOGGER.info("public JsonGenerator write(String,double)"); addCalls("public JsonGenerator write(String,double)"); return null; } @Override public JsonGenerator write(String name, BigInteger value) { LOGGER.info("public JsonGenerator write(String,BigInteger)"); addCalls("public JsonGenerator write(String,BigInteger)"); return null; } @Override public JsonGenerator write(String name, BigDecimal value) { LOGGER.info("public JsonGenerator write(String,BigDecimal)"); addCalls("public JsonGenerator write(String,BigDecimal)"); return null; } @Override public JsonGenerator write(String name, boolean value) { LOGGER.info("public JsonGenerator write(String,boolean)"); addCalls("public JsonGenerator write(String,boolean)"); return null; } @Override public JsonGenerator write(String name, JsonValue value) { LOGGER.info("public JsonGenerator write(String,JsonValue)"); addCalls("public JsonGenerator write(String,JsonValue)"); return null; } @Override public JsonGenerator writeNull(String name) { LOGGER.info("public JsonGenerator writeNull(String)"); addCalls("public JsonGenerator writeNull(String)"); return null; } @Override public JsonGenerator writeStartArray() { LOGGER.info("public JsonGenerator writeStartArray()"); addCalls("public JsonGenerator writeStartArray()"); return null; } @Override public JsonGenerator writeStartArray(String name) { LOGGER.info("public JsonGenerator writeStartArray(String)"); addCalls("public JsonGenerator writeStartArray(String)"); return null; } @Override public JsonGenerator write(String value) { LOGGER.info("public JsonGenerator write(String)"); addCalls("public JsonGenerator write(String)"); return null; } @Override public JsonGenerator write(int value) { LOGGER.info("public JsonGenerator write(int)"); addCalls("public JsonGenerator write(int)"); return null; } @Override public JsonGenerator write(long value) { LOGGER.info("public JsonGenerator write(long)"); addCalls("public JsonGenerator write(long)"); return null; } @Override public JsonGenerator write(double value) { LOGGER.info("public JsonGenerator write(double)"); addCalls("public JsonGenerator write(double)"); return null; } @Override public JsonGenerator write(BigInteger value) { LOGGER.info("public JsonGenerator write(BigInteger)"); addCalls("public JsonGenerator write(BigInteger)"); return null; } @Override public JsonGenerator write(BigDecimal value) { LOGGER.info("public JsonGenerator write(BigDecimal)"); addCalls("public JsonGenerator write(BigDecimal)"); return null; } @Override public JsonGenerator write(boolean value) { LOGGER.info("public JsonGenerator write(boolean)"); addCalls("public JsonGenerator write(boolean)"); return null; } @Override public JsonGenerator write(JsonValue value) { LOGGER.info("public JsonGenerator write(JsonValue)"); addCalls("public JsonGenerator write(JsonValue)"); return null; } @Override public JsonGenerator writeNull() { LOGGER.info("public JsonGenerator writeNull()"); addCalls("public JsonGenerator writeNull()"); return null; } @Override public JsonGenerator writeEnd() { LOGGER.info("public JsonGenerator writeEnd()"); addCalls("public JsonGenerator writeEnd()"); return null; } @Override public JsonGenerator writeKey(String name) { LOGGER.info("public JsonGenerator writeKey()"); addCalls("public JsonGenerator writeKey()"); return null; } @Override public void close() { LOGGER.info("public void close()"); addCalls("public void close()"); } } MyJsonGeneratorFactory.java000066400000000000000000000057061451447132700373170ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.stream.*; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.logging.Logger; /* * MyJsonGeneratorFactory is a Json Test GeneratorFactory used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonGeneratorFactory implements JsonGeneratorFactory { private static final Logger LOGGER = Logger.getLogger(MyJsonGeneratorFactory.class.getName()); private OutputStream out = null; private Writer writer = null; private Charset charset = Charset.forName("UTF-8"); private Map config = null; private void dumpInstanceVars() { LOGGER.info("writer=" + writer); LOGGER.info("out=" + out); LOGGER.info("charset=" + charset); LOGGER.info("config=" + config); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonGeneratorFactory(Map config) { this.config = config; } public Map getConfigInUse() { LOGGER.info("public Map getConfigInUse()"); addCalls("public Map getConfigInUse()"); return config; } public JsonGenerator createGenerator(OutputStream out) { LOGGER.info("public JsonGenerator createGenerator(OutputStream)"); addCalls("public JsonGenerator createGenerator(OutputStream)"); this.out = out; return null; } public JsonGenerator createGenerator(OutputStream out, Charset charset) { LOGGER.info( "public JsonGenerator createGenerator(OutputStream, Charset)"); addCalls("public JsonGenerator createGenerator(OutputStream, Charset)"); this.out = out; this.charset = charset; return null; } public JsonGenerator createGenerator(Writer writer) { LOGGER.info("public JsonGenerator createGenerator(Writer)"); addCalls("public JsonGenerator createGenerator(Writer)"); this.writer = writer; return null; } } MyJsonParser.java000066400000000000000000000060731451447132700352730ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.stream.*; import java.io.*; import java.math.BigDecimal; import java.util.logging.Logger; /* * MyJsonParser is a Json Test Parser used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonParser implements JsonParser { private static final Logger LOGGER = Logger.getLogger(MyJsonParser.class.getName()); private InputStream in = null; private Reader reader = null; private void dumpInstanceVars() { LOGGER.info("reader=" + reader); LOGGER.info("in=" + in); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonParser(InputStream in) { this.in = in; } public MyJsonParser(Reader reader) { this.reader = reader; } public void close() { LOGGER.info("public void close()"); addCalls("public void close()"); } public BigDecimal getBigDecimal() { LOGGER.info("public BigDecimal getBigDecimal()"); addCalls("public BigDecimal getBigDecimal()"); return null; } public int getInt() { LOGGER.info("public int getInt()"); addCalls("public int getInt()"); return -1; } public JsonLocation getLocation() { LOGGER.info("public JsonLocation getLocation()"); addCalls("public JsonLocation getLocation()"); return null; } public long getLong() { LOGGER.info("public long getLong()"); addCalls("public long getLong()"); return -1; } public boolean isIntegralNumber() { LOGGER.info("public boolean isIntegralNumber()"); addCalls("public boolean isIntegralNumber()"); return false; } public String getString() { LOGGER.info("public String getString()"); addCalls("public String getString()"); return null; } public boolean hasNext() { LOGGER.info("public boolean hasNext()"); addCalls("public boolean hasNext()"); return false; } public JsonParser.Event next() { LOGGER.info("public JsonParser.Event next()"); addCalls("public JsonParser.Event next()"); return null; } } MyJsonParserFactory.java000066400000000000000000000063721451447132700366250ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.*; import jakarta.json.stream.*; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.logging.Logger; /* * MyJsonParserFactory is a Json Test ParserFactory used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonParserFactory implements JsonParserFactory { private static final Logger LOGGER = Logger.getLogger(MyJsonParserFactory.class.getName()); private InputStream in = null; private Charset charset = null; private Reader reader = null; private Map config = null; private void dumpInstanceVars() { LOGGER.info("reader=" + reader); LOGGER.info("in=" + in); LOGGER.info("charset=" + charset); LOGGER.info("config=" + config); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonParserFactory(Map config) { this.config = config; } public Map getConfigInUse() { LOGGER.info("public Map getConfigInUse()"); addCalls("public Map getConfigInUse()"); return config; } public JsonParser createParser(InputStream in) { LOGGER.info("public JsonParser createParser(InputStream)"); addCalls("public JsonParser createParser(InputStream)"); this.in = in; return null; } public JsonParser createParser(InputStream in, Charset charset) { LOGGER.info("public JsonParser createParser(InputStream, Charset)"); addCalls("public JsonParser createParser(InputStream, Charset)"); this.in = in; this.charset = charset; return null; } public JsonParser createParser(Reader reader) { LOGGER.info("public JsonParser createParser(Reader)"); addCalls("public JsonParser createParser(Reader)"); this.reader = reader; return null; } public JsonParser createParser(JsonArray jsonArray) { LOGGER.info("public JsonParser createParser(JsonArray)"); addCalls("public JsonParser createParser(JsonArray)"); return null; } public JsonParser createParser(JsonObject jsonObject) { LOGGER.info("public JsonParser createParser(JsonObject)"); addCalls("public JsonParser createParser(JsonObject)"); return null; } } MyJsonProvider.java000066400000000000000000000150631451447132700356300ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.provider; import java.io.*; import java.util.*; import java.util.logging.Logger; import jakarta.json.*; import jakarta.json.spi.JsonProvider; import jakarta.json.stream.*; // $Id$ /* * MyJsonProvider is a Json Test Provider used by the pluggability tests * to test the Json SPI layer. This provider tracks that the proper callback * methods are invoked within the provider when Json API methods are called. */ public class MyJsonProvider extends JsonProvider { private static final Logger LOGGER = Logger.getLogger(MyJsonProvider.class.getName()); // Exception thrown when encoding or i/o error private final JsonException exception = new JsonException( "encoding or i/o error"); // call methods private static final StringBuilder CALLS = new StringBuilder(); public static String getCalls() { return CALLS.toString(); } public static void clearCalls() { CALLS.delete(0, CALLS.length()); } private static void addCalls(String s) { CALLS.append(s); } @Override public JsonArrayBuilder createArrayBuilder() { LOGGER.info("public JsonArrayBuilder createArrayBuilder()"); addCalls("public JsonArrayBuilder createArrayBuilder()"); return null; } @Override public JsonBuilderFactory createBuilderFactory(Map config) { LOGGER.info( "public JsonBuilderFactory createBuilderFactory(Map)"); addCalls("public JsonBuilderFactory createBuilderFactory(Map)"); return null; } @Override public JsonObjectBuilder createObjectBuilder() { LOGGER.info("public JsonObjectBuilder createObjectBuilder()"); addCalls("public JsonObjectBuilder createObjectBuilder()"); return null; } @Override public JsonReader createReader(Reader reader) { LOGGER.info("public JsonReader createReader(Reader)"); addCalls("public JsonReader createReader(Reader)"); return new MyJsonReader(reader); } @Override public JsonReader createReader(InputStream in) { LOGGER.info("public JsonReader createReader(InputStream)"); addCalls("public JsonReader createReader(InputStream)"); return new MyJsonReader(in); } @Override public JsonReaderFactory createReaderFactory(Map config) { LOGGER.info( "public JsonReaderFactory createReaderFactory(Map)"); addCalls("public JsonReaderFactory createReaderFactory(Map)"); return null; } @Override public JsonWriter createWriter(Writer writer) { LOGGER.info("public JsonWriter createWriter(Writer)"); addCalls("public JsonWriter createWriter(Writer)"); return new MyJsonWriter(writer); } @Override public JsonWriter createWriter(OutputStream out) { LOGGER.info("public JsonWriter createWriter(OutputStream)"); addCalls("public JsonWriter createWriter(OutputStream)"); return new MyJsonWriter(out); } @Override public JsonWriterFactory createWriterFactory(Map config) { LOGGER.info( "public JsonWriterFactory createWriterFactory(Map)"); addCalls("public JsonWriterFactory createWriterFactory(Map)"); return null; } @Override public JsonGenerator createGenerator(Writer writer) { LOGGER.info("public JsonGenerator createGenerator(Writer)"); addCalls("public JsonGenerator createGenerator(Writer)"); return new MyJsonGenerator(writer); } @Override public JsonGenerator createGenerator(OutputStream out) { LOGGER.info("public JsonGenerator createGenerator(OutputStream)"); addCalls("public JsonGenerator createGenerator(OutputStream)"); return new MyJsonGenerator(out); } @Override public JsonParser createParser(Reader reader) { LOGGER.info("public JsonParser createParser(Reader)"); addCalls("public JsonParser createParser(Reader)"); return new MyJsonParser(reader); } @Override public JsonParser createParser(InputStream in) { LOGGER.info("public JsonParser createParser(InputStream)"); addCalls("public JsonParser createParser(InputStream)"); if (in == null) throw exception; else return new MyJsonParser(in); } @Override public JsonParserFactory createParserFactory(Map config) { LOGGER.info( "public JsonParserFactory createParserFactory(Map)"); addCalls("public JsonParserFactory createParserFactory(Map)"); return null; } @Override public JsonGeneratorFactory createGeneratorFactory(Map config) { LOGGER.info( "public JsonGeneratorFactory createGeneratorFactory(Map)"); addCalls( "public JsonGeneratorFactory createGeneratorFactory(Map)"); return null; } @Override public JsonPatchBuilder createPatchBuilder() { throw new UnsupportedOperationException("Not supported yet."); // To change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonPatchBuilder createPatchBuilder(JsonArray ja) { throw new UnsupportedOperationException("Not supported yet."); // To change // body of // generated // methods, // choose // Tools | // Templates. } } MyJsonReader.java000066400000000000000000000044711451447132700352410ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.*; import java.io.*; import java.util.logging.Logger; /* * MyJsonReader is a Json Test Reader used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonReader implements JsonReader { private static final Logger LOGGER = Logger.getLogger(MyJsonReader.class.getName()); private InputStream in = null; private Reader reader = null; private void dumpInstanceVars() { LOGGER.info("reader=" + reader); LOGGER.info("in=" + in); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonReader() { } public MyJsonReader(InputStream in) { this.in = in; } public MyJsonReader(Reader reader) { this.reader = reader; } public void close() { LOGGER.info("public void close()"); addCalls("public void close()"); } public JsonStructure read() { LOGGER.info("public void read()"); addCalls("public void read()"); return null; } public JsonArray readArray() { LOGGER.info("public void readArray()"); addCalls("public void readArray()"); return null; } public JsonObject readObject() { LOGGER.info("public void readObject()"); addCalls("public void readObject()"); return null; } } MyJsonReaderFactory.java000066400000000000000000000055111451447132700365650ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.*; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.logging.Logger; /* * MyJsonReaderFactory is a Json Test ReaderFactory used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonReaderFactory implements JsonReaderFactory { private static final Logger LOGGER = Logger.getLogger(MyJsonReaderFactory.class.getName()); private InputStream in = null; private Charset charset = null; private Reader reader = null; private Map config = null; private void dumpInstanceVars() { LOGGER.info("reader=" + reader); LOGGER.info("in=" + in); LOGGER.info("charset=" + charset); LOGGER.info("config=" + config); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonReaderFactory(Map config) { this.config = config; } public Map getConfigInUse() { LOGGER.info("public Map getConfigInUse()"); addCalls("public Map getConfigInUse()"); return config; } public JsonReader createReader(InputStream in) { LOGGER.info("public JsonReader createReader(InputStream)"); addCalls("public JsonReader createReader(InputStream)"); this.in = in; return null; } public JsonReader createReader(InputStream in, Charset charset) { LOGGER.info("public JsonReader createReader(InputStream, Charset)"); addCalls("public JsonReader createReader(InputStream, Charset)"); this.in = in; this.charset = charset; return null; } public JsonReader createReader(Reader reader) { LOGGER.info("public JsonReader createReader(Reader)"); addCalls("public JsonReader createReader(Reader)"); this.reader = reader; return null; } } MyJsonWriter.java000066400000000000000000000047611451447132700353150ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.*; import java.io.*; import java.nio.charset.Charset; import java.util.logging.Logger; /* * MyJsonWriter is a Json Test Writer used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonWriter implements JsonWriter { private static final Logger LOGGER = Logger.getLogger(MyJsonWriter.class.getName()); private OutputStream out = null; private Writer writer = null; private Charset charset = Charset.forName("UTF-8"); private void dumpInstanceVars() { LOGGER.info("writer=" + writer); LOGGER.info("out=" + out); LOGGER.info("charset=" + charset); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonWriter() { } public MyJsonWriter(OutputStream out) { this.out = out; } public MyJsonWriter(Writer writer) { this.writer = writer; } public void close() { LOGGER.info("public void close()"); addCalls("public void close()"); } public void write(JsonStructure value) { LOGGER.info("public void write(JsonStructure)"); addCalls("public void write(JsonStructure)"); } public void writeArray(JsonArray array) { LOGGER.info("public void writeArray(JsonArray)"); addCalls("public void writeArray(JsonArray)"); } public void writeObject(JsonObject object) { LOGGER.info("public void writeObject(JsonObject)"); addCalls("public void writeObject(JsonObject)"); } } MyJsonWriterFactory.java000066400000000000000000000055321451447132700366420ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/java/ee/jakarta/tck/jsonp/provider/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.provider; import jakarta.json.*; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.logging.Logger; /* * MyJsonWriterFactory is a Json Test WriterFactory used by the pluggability tests * to test the Json SPI layer. This parser tracks that the proper callback * methods are invoked within the parser when Json API methods are called. */ public class MyJsonWriterFactory implements JsonWriterFactory { private static final Logger LOGGER = Logger.getLogger(MyJsonWriterFactory.class.getName()); private OutputStream out = null; private Writer writer = null; private Charset charset = null; private Map config = null; private void dumpInstanceVars() { LOGGER.info("writer=" + writer); LOGGER.info("out=" + out); LOGGER.info("charset=" + charset); LOGGER.info("config=" + config); } // call methods private static StringBuilder calls = new StringBuilder(); public static String getCalls() { return calls.toString(); } public static void clearCalls() { calls.delete(0, calls.length()); } private static void addCalls(String s) { calls.append(s); } public MyJsonWriterFactory(Map config) { this.config = config; } public Map getConfigInUse() { LOGGER.info("public Map getConfigInUse()"); addCalls("public Map getConfigInUse()"); return config; } public JsonWriter createWriter(OutputStream out) { LOGGER.info("public JsonWriter createWriter(OutputStream)"); addCalls("public JsonWriter createWriter(OutputStream)"); this.out = out; return null; } public JsonWriter createWriter(OutputStream out, Charset charset) { LOGGER.info("public JsonWriter createWriter(OutputStream, Charset)"); addCalls("public JsonWriter createWriter(OutputStream, Charset)"); this.out = out; this.charset = charset; return null; } public JsonWriter createWriter(Writer writer) { LOGGER.info("public JsonWriter createWriter(Writer)"); addCalls("public JsonWriter createWriter(Writer)"); this.writer = writer; return null; } } jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/resources/000077500000000000000000000000001451447132700254245ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/resources/META-INF/000077500000000000000000000000001451447132700265645ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/resources/META-INF/services/000077500000000000000000000000001451447132700304075ustar00rootroot00000000000000jakarta.json.spi.JsonProvider000066400000000000000000000000551451447132700360550ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests-pluggability/src/main/resources/META-INF/servicesee.jakarta.tck.jsonp.provider.MyJsonProvider jsonp-api-2.1.3-RELEASE/tck/tck-tests/000077500000000000000000000000001451447132700172055ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/pom.xml000066400000000000000000000043461451447132700205310ustar00rootroot00000000000000 4.0.0 jakarta.json jakarta.json-tck 2.1.0-SNAPSHOT ../pom.xml jakarta.json-tck-tests jar jakarta.json jakarta.json-tck-common org.apache.maven.plugins maven-javadoc-plugin none org.apache.maven.plugins maven-source-plugin attach-sources jar-no-fork jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/000077500000000000000000000000001451447132700177745ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/000077500000000000000000000000001451447132700207205ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/000077500000000000000000000000001451447132700216415ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/000077500000000000000000000000001451447132700222325ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/000077500000000000000000000000001451447132700236475ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/000077500000000000000000000000001451447132700244305ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/000077500000000000000000000000001451447132700255615ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/000077500000000000000000000000001451447132700263325ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/collectortests/000077500000000000000000000000001451447132700314035ustar00rootroot00000000000000CollectorTests.java000066400000000000000000000031441451447132700351420ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/collectortests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.collectortests; import ee.jakarta.tck.jsonp.api.common.TestResult; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; // $Id$ /** * JavaScript Object Notation (JSON) Pointer compatibility tests.
* Test {@link jakarta.json.stream.JsonCollectors} class implementation. */ public class CollectorTests { /** * Test JSON-P {@link jakarta.json.stream.JsonCollectors} class implementation. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonCollectorTest * @assertion_ids: JSONP:JAVADOC:668; JSONP:JAVADOC:669; JSONP:JAVADOC:670; * JSONP:JAVADOC:671; * @test_Strategy: Test all collectors returned by API. */ @Test public void jsonCollectorTest() { Collectors collectorTest = new Collectors(); final TestResult result = collectorTest.test(); result.eval(); } } Collectors.java000066400000000000000000000562111451447132700343050ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/collectortests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.collectortests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Map; import java.util.TreeSet; import java.util.function.Function; import java.util.logging.Logger; import java.util.stream.Collector; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; import jakarta.json.stream.JsonCollectors; import jakarta.json.stream.JsonParser; // $Id$ /** * JavaScript Object Notation (JSON) Pointer compatibility tests.
* Test {@link jakarta.json.stream.JsonCollectors} class implementation. This * class was added to resolve * {@see RFE: * Support JSON queries using JDK's stream operations}. */ public class Collectors { private static final Logger LOGGER = Logger.getLogger(Collectors.class.getName()); /** Tests input data with JsonArray instances. */ private static final JsonArray[] ARRAY_VALUES = new JsonArray[] { SimpleValues.createSimpleStringArray5(), // JsonArray with String SimpleValues.createSimpleIntArray5(), // JsonArray with int SimpleValues.createSimpleBoolArray5(), // JsonArray with boolean SimpleValues.createSimpleObjectArray5() // JsonArray with JsonObject }; /** Tests input data with JsonArray instances. */ private static final JsonObject[] OBJ_VALUES = new JsonObject[] { SimpleValues.createSimpleObjectWithStr(), // JsonObject with String SimpleValues.createSimpleObjectWithInt(), // JsonObject with int SimpleValues.createSimpleObjectWithBool(), // JsonObject with boolean SimpleValues.createCompoundObject() // JsonObject with JsonObject }; /** Test input data for {@code groupingBy} methods. */ private static final JsonArray OBJ_ARRAY_GROUP = Json.createArrayBuilder() .add(Json.createObjectBuilder().add("name", "Peter").add("office", "Green")) .add(Json.createObjectBuilder().add("name", "John").add("office", "Red")) .add(Json.createObjectBuilder().add("name", "Bob").add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Sarah").add("office", "Red")) .add(Json.createObjectBuilder().add("name", "Tom").add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Jane").add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Peggy").add("office", "Green")) .add(Json.createObjectBuilder().add("name", "Rick").add("office", "Red")) .build(); /** * Creates an instance of {@link jakarta.json.stream.JsonCollectors} class * implementation tests. */ Collectors() { super(); } /** * Test {@link jakarta.json.stream.JsonCollectors} class implementation. Suite * entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonCollectors class implementation"); LOGGER.info("JsonCollectors class implementation"); testToJsonArrayCollector(result); // testSimpleToJsonObjectCollector(result); testToJsonObjectCollector(result); testSimpleGroupingByCollector(result); testSortingGroupingByCollector(result); return result; } /** * Test collector returned by {@code toJsonArray()} method. This collector * packs {@code Stream} contend into a single JsonArray instance * which contains stream values in the same order at they were read. It can be * considered as {@link JsonParser#getArrayStream()} counterpart. * * @param result * Tests result record. */ private void testToJsonArrayCollector(final TestResult result) { LOGGER.info(" - Collector returned by toJsonArray()"); for (final JsonArray in : ARRAY_VALUES) { LOGGER.info(" - Input: " + JsonAssert.valueToString(in)); final Collector col = JsonCollectors .toJsonArray(); final JsonArray out = in.getValuesAs(JsonObject.class).stream() .collect(col); if (operationFailed(in, out)) { result.fail("toJsonArray()", "Output Stream value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(in)); } } } // TCK test for https://java.net/jira/browse/JSON_PROCESSING_SPEC-82 in case // it will be checked in. // /** // * Test collector returned by {@code toJsonObject()} method. // * This collector packs {@code Stream} contend into a single // JsonArray instance which contains // * stream values in the same order at they were read. It can be considered // as {@link JsonParser#getArrayStream()} // * counterpart. // * @param result Tests result record. // */ // private void testSimpleToJsonObjectCollector(final TestResult result) { // LOGGER.info(" - Collector returned by toJsonObject()"); // for (final JsonObject in : OBJ_VALUES) { // LOGGER.info(" - Input: " + valueToString(in)); // final Collector, JsonObjectBuilder, JsonObject> // col = JsonCollectors.toJsonObject(); // final JsonObject out = (in.entrySet()).stream().collect(col); // if (operationFailed(in, out)) { // result.fail("toJsonObject()", // "Output Stream value " + valueToString(out) + " shall be " + // valueToString(in)); // } // } // } /** * Test collector returned by * {@code toJsonObject(Function, Function)} * method. This collector does not pack content of * {@code Stream>} stream of * {@link JsonParser#getObjectStream()} output. So it's not counterpart of * this method. It works with {@code Stream}, which is * {@link JsonParser#getArrayStream()} output and uses two {@link Function} * implementations to build target object keys and values from * {@code JsonValue} in the {@code Stream}. * * @param result * Tests result record. */ private void testToJsonObjectCollector(final TestResult result) { LOGGER.info(" - Collector returned by toJsonObject(Function,Function)"); final JsonArray in = Json.createArrayBuilder() .add(Json.createObjectBuilder().add("key", SimpleValues.STR_NAME).add("value", SimpleValues.STR_VALUE)) .add(Json.createObjectBuilder().add("key", SimpleValues.INT_NAME).add("value", SimpleValues.INT_VALUE)) .add(Json.createObjectBuilder().add("key", SimpleValues.BOOL_NAME).add("value", SimpleValues.BOOL_VALUE)) .add(Json.createObjectBuilder().add("key", SimpleValues.OBJ_NAME).add("value", SimpleValues.OBJ_VALUE)) .build(); final JsonObject check = Json.createObjectBuilder().add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE) .add(SimpleValues.INT_NAME, SimpleValues.INT_VALUE).add(SimpleValues.BOOL_NAME, SimpleValues.BOOL_VALUE) .add(SimpleValues.OBJ_NAME, SimpleValues.OBJ_VALUE).build(); LOGGER.info(" Input: " + JsonAssert.valueToString(in)); final Collector col = JsonCollectors .toJsonObject( // Build key from stream value. (JsonValue v) -> { if (v.getValueType() == JsonValue.ValueType.OBJECT) return v.asJsonObject().getString("key"); throw new IllegalStateException("Value must be JsonObject"); }, // Build value from stream value. (JsonValue v) -> { if (v.getValueType() == JsonValue.ValueType.OBJECT) return v.asJsonObject().get("value"); throw new IllegalStateException("Value must be JsonObject"); }); final JsonObject out = in.getValuesAs(JsonObject.class).stream() .collect(col); if (operationFailed(out, check)) { result.fail("toJsonObject(Function,Function)", "Output Stream value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(check)); } } /** * Test collector returned by {@code groupingBy(Function)} * method. This collector allows grouping of {@code Stream} using * provided {@code Function)} function to define group * identifiers based on {@code JsonValue} content. Test just groups JSON * objects in the stream by {@code "office"} attribute. Default * {@code toJsonArray()} collector is used so output is unsorted. * * @param result * Tests result record. */ private void testSimpleGroupingByCollector(final TestResult result) { LOGGER.info(" - Collector returned by groupingBy(Function)"); final JsonObject check = Json.createObjectBuilder().add("Red", Json .createArrayBuilder() .add( Json.createObjectBuilder().add("name", "John").add("office", "Red")) .add(Json.createObjectBuilder().add("name", "Sarah").add("office", "Red")) .add( Json.createObjectBuilder().add("name", "Rick").add("office", "Red")) .build()) .add("Blue", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("name", "Bob").add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Tom").add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Jane") .add("office", "Blue")) .build()) .add("Green", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("name", "Peter") .add("office", "Green")) .add(Json.createObjectBuilder().add("name", "Peggy") .add("office", "Green")) .build()) .build(); LOGGER.info(" Input: " + JsonAssert.valueToString(OBJ_ARRAY_GROUP)); final Collector, JsonObject> col = JsonCollectors .groupingBy((JsonValue v) -> { if (v.getValueType() == JsonValue.ValueType.OBJECT) return v.asJsonObject().getString("office"); throw new IllegalStateException("Value must be JsonObject"); }); final JsonObject out = OBJ_ARRAY_GROUP.getValuesAs(JsonObject.class) .stream().collect(col); if (operationFailed(out, check)) { result.fail("groupingBy(Function)", "Output Stream value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(check)); } } /** * Builder to create sorted JsonArray with ordering by {@code "name"} * attribute of {@code JsonObject}. */ private class ValueBuilder implements JsonArrayBuilder { /** Sorted collection of values. */ private final TreeSet values; private ValueBuilder() { values = new TreeSet<>((JsonValue v1, JsonValue v2) -> { if (v1.getValueType() == JsonValue.ValueType.OBJECT && v1.getValueType() == JsonValue.ValueType.OBJECT) { return v1.asJsonObject().getString("name") .compareTo(v2.asJsonObject().getString("name")); } throw new IllegalStateException("Values must be JsonObject"); }); } /** * Builder accumulator method. * * @param value * Value to be added to {@code JsonArray}. * @return This builder instance. */ @Override public JsonArrayBuilder add(JsonValue value) { values.add(value); return this; } /** * Builder combiner method. * * @param builder * Builder containing values to be added to {@code JsonArray}. * @return This builder instance. */ public ValueBuilder addAll(ValueBuilder builder) { values.addAll(builder.values); return this; } /** * Builder finisher method. * * @return {@code JsonArray} from current builder content. */ @Override public JsonArray build() { JsonArrayBuilder builder = Json.createArrayBuilder(); for (JsonValue value : values) { builder.add(value); } return builder.build(); } @Override public JsonArrayBuilder add(String value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(BigDecimal value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(BigInteger value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(int value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(long value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(double value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(boolean value) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder addNull() { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(JsonObjectBuilder builder) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } @Override public JsonArrayBuilder add(JsonArrayBuilder builder) { throw new UnsupportedOperationException("Not supported yet."); // To // change // body of // generated // methods, // choose // Tools | // Templates. } } /** * Test collector returned by * {@code groupingBy(Function,Collector)} * method. This collector allows grouping of {@code Stream} using * provided {@code Function)} function to define group * identifiers based on {@code JsonValue} content and * {@code Collector)}. Test groups JSON * objects in the stream by {@code "office"} attribute. External collector is * building sorted {@code JsonArray} so arrays for each office group are * sorted. * * @param result * Tests result record. */ private void testSortingGroupingByCollector(final TestResult result) { LOGGER.info(" - Collector returned by groupingBy(Function,Collector)"); final JsonObject check = Json.createObjectBuilder().add("Red", Json .createArrayBuilder() .add( Json.createObjectBuilder().add("name", "John").add("office", "Red")) .add( Json.createObjectBuilder().add("name", "Rick").add("office", "Red")) .add(Json.createObjectBuilder().add("name", "Sarah").add("office", "Red")) .build()) .add("Blue", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("name", "Bob").add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Jane") .add("office", "Blue")) .add(Json.createObjectBuilder().add("name", "Tom").add("office", "Blue")) .build()) .add("Green", Json.createArrayBuilder() .add(Json.createObjectBuilder().add("name", "Peggy") .add("office", "Green")) .add(Json.createObjectBuilder().add("name", "Peter") .add("office", "Green")) .build()) .build(); Collector toArray = Collector.of( ValueBuilder::new, JsonArrayBuilder::add, JsonArrayBuilder::addAll, JsonArrayBuilder::build); LOGGER.info(" Input: " + JsonAssert.valueToString(OBJ_ARRAY_GROUP)); final Collector, JsonObject> col = JsonCollectors .groupingBy((JsonValue v) -> { if (v.getValueType() == JsonValue.ValueType.OBJECT) return v.asJsonObject().getString("office"); throw new IllegalStateException("Value must be JsonObject"); }, toArray); final JsonObject out = OBJ_ARRAY_GROUP.getValuesAs(JsonObject.class) .stream().collect(col); if (operationFailed(out, check)) { result.fail("groupingBy(Function,Collector)", "Output Stream value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(check)); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { LOGGER.info(" Checking " + JsonAssert.valueToString(out)); return out == null || !JsonAssert.assertEquals(check, out); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/000077500000000000000000000000001451447132700276225ustar00rootroot00000000000000ArrayBuilder.java000066400000000000000000000230141451447132700327730ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import java.math.BigDecimal; import java.math.BigInteger; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonValue; // $Id$ /** * {@link JsonArrayBuilder} manipulation helper. */ public class ArrayBuilder { /** * Add {@code value} to provided JSON array builder. * * @param builder * Target JSON array builder. * @param value * Value to be added at the end of the array. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder add(final JsonArrayBuilder builder, final Object value) { switch (JsonValueType.getType(value)) { case String: return builder.add((String) value); case Integer: return builder.add(((Integer) value).intValue()); case Long: return builder.add(((Long) value).intValue()); case BigInteger: return builder.add(((BigInteger) value)); case Double: return builder.add(((Double) value).doubleValue()); case BigDecimal: return builder.add(((BigDecimal) value)); case Boolean: return builder.add(((Boolean) value).booleanValue()); case JsonValue: return builder.add((JsonValue) value); case Null: return builder.addNull(); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Add {@code value} at specified index to provided JSON array builder. * * @param builder * Target JSON array builder. * @param index * Array index of value to be added. * @param value * Value to be added at the end of the array. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder add(final JsonArrayBuilder builder, final int index, final Object value) { switch (JsonValueType.getType(value)) { case String: return builder.add(index, (String) value); case Integer: return builder.add(index, ((Integer) value).intValue()); case Long: return builder.add(index, ((Long) value).longValue()); case BigInteger: return builder.add(index, ((BigInteger) value)); case Double: return builder.add(index, ((Double) value).doubleValue()); case BigDecimal: return builder.add(index, ((BigDecimal) value)); case Boolean: return builder.add(index, ((Boolean) value).booleanValue()); case JsonValue: return builder.add(index, (JsonValue) value); case Null: return builder.addNull(index); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Add {@code null} to provided JSON array builder. Every call shall throw an * exception which depends on selected type. * * @param builder * Target JSON array builder. * @param type * Type of method argument to use.. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder add(final JsonArrayBuilder builder, final JsonValueType type) { switch (type) { case String: return builder.add((String) null); case Integer: throw new UnsupportedOperationException( "Value null is not supported for int"); case Long: throw new UnsupportedOperationException( "Value null is not supported for long"); case BigInteger: return builder.add((BigInteger) null); case Double: throw new UnsupportedOperationException( "Value null is not supported for double"); case BigDecimal: return builder.add((BigDecimal) null); case Boolean: return builder.add((Boolean) null); case JsonValue: return builder.add((JsonValue) null); case Null: throw new UnsupportedOperationException( "Value null is not supported for addNull()"); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Add {@code null} to provided JSON array builder. Every call shall throw an * exception which depends on selected type. * * @param builder * Target JSON array builder. * @param index * Array index of value to be added. * @param type * Type of method argument to use.. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder add(final JsonArrayBuilder builder, final int index, final JsonValueType type) { switch (type) { case String: return builder.add(index, (String) null); case Integer: throw new UnsupportedOperationException( "Value null is not supported for int"); case Long: throw new UnsupportedOperationException( "Value null is not supported for long"); case BigInteger: return builder.add(index, (BigInteger) null); case Double: throw new UnsupportedOperationException( "Value null is not supported for double"); case BigDecimal: return builder.add(index, (BigDecimal) null); case Boolean: return builder.add(index, (Boolean) null); case JsonValue: return builder.add(index, (JsonValue) null); case Null: throw new UnsupportedOperationException( "Value null is not supported for addNull()"); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Set {@code value} at specified index to provided JSON array builder. * * @param builder * Target JSON array builder. * @param index * Array index of value to be added. * @param value * Value to be set at the end of the array. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder set(final JsonArrayBuilder builder, final int index, final Object value) { switch (JsonValueType.getType(value)) { case String: return builder.set(index, (String) value); case Integer: return builder.set(index, ((Integer) value).intValue()); case Long: return builder.set(index, ((Long) value).longValue()); case BigInteger: return builder.set(index, ((BigInteger) value)); case Double: return builder.set(index, ((Double) value).doubleValue()); case BigDecimal: return builder.set(index, ((BigDecimal) value)); case Boolean: return builder.set(index, ((Boolean) value).booleanValue()); case JsonValue: return builder.set(index, (JsonValue) value); case Null: return builder.setNull(index); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Set {@code null} to provided JSON array builder. Every call shall throw an * exception which depends on selected type. * * @param builder * Target JSON array builder. * @param index * Array index of value to be added. * @param type * Type of method argument to use.. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder set(final JsonArrayBuilder builder, final int index, final JsonValueType type) { switch (type) { case String: return builder.set(index, (String) null); case Integer: throw new UnsupportedOperationException( "Value null is not supported for int"); case Long: throw new UnsupportedOperationException( "Value null is not supported for long"); case BigInteger: return builder.set(index, (BigInteger) null); case Double: throw new UnsupportedOperationException( "Value null is not supported for double"); case BigDecimal: return builder.set(index, (BigDecimal) null); case Boolean: return builder.set(index, (Boolean) null); case JsonValue: return builder.set(index, (JsonValue) null); case Null: throw new UnsupportedOperationException( "Value null is not supported for addNull()"); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Remove {@code value} at specified index from provided JSON array builder. * * @param builder * Target JSON array builder. * @param index * Array index of value to be added. * @return JSON array builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonArrayBuilder remove(final JsonArrayBuilder builder, final int index) { return builder.remove(index); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/JsonAssert.java000066400000000000000000000150161451447132700325630ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.logging.Logger; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonNumber; import jakarta.json.JsonObject; import jakarta.json.JsonReader; import jakarta.json.JsonString; import jakarta.json.JsonValue; // $Id$ /** * JSON values assertions. */ public class JsonAssert { private static final Logger LOGGER = Logger.getLogger(JsonAssert.class.getName()); private static boolean assertEquals(final JsonObject expected, final JsonObject actual, final String message) { if (actual.equals(expected)) { return true; } else { LOGGER.info(" " + message); LOGGER.info(" Expected: " + JSONP_Util.toStringJsonObject(expected)); LOGGER.info(" Actual: " + JSONP_Util.toStringJsonObject(actual)); return false; } } private static boolean assertEquals(final JsonArray expected, final JsonArray actual, final String message) { if (actual.equals(expected)) { return true; } else { LOGGER.info(" " + message); LOGGER.info(" Expected: " + JSONP_Util.toStringJsonArray(expected)); LOGGER.info(" Actual: " + JSONP_Util.toStringJsonArray(actual)); return false; } } private static boolean assertEquals(final JsonString expected, final JsonString actual, final String message) { if (actual.equals(expected)) { return true; } else { LOGGER.info(" " + message); LOGGER.info(" Expected: " + expected.getString()); LOGGER.info(" Actual: " + actual.getString()); return false; } } private static boolean assertEquals(final JsonNumber expected, final JsonNumber actual, final String message) { if (actual.equals(expected)) { return true; } else { LOGGER.info(" " + message); LOGGER.info(" Expected: " + expected.toString()); LOGGER.info(" Actual: " + actual.toString()); return false; } } public static boolean assertEquals(final JsonValue expected, final JsonValue actual, final String message) { switch (expected.getValueType()) { case OBJECT: return assertEquals((JsonObject) expected, (JsonObject) actual, message); case ARRAY: return assertEquals((JsonArray) expected, (JsonArray) actual, message); case STRING: return assertEquals((JsonString) expected, (JsonString) actual, message); case NUMBER: return assertEquals((JsonNumber) expected, (JsonNumber) actual, message); case TRUE: case FALSE: if (expected == actual) { return true; } else { LOGGER.info(" " + message); LOGGER.info(" Expected: " + expected.toString()); LOGGER.info(" Actual: " + actual.toString()); return false; } default: if (actual.equals(expected)) { return true; } else { LOGGER.info(" " + message); LOGGER.info(" Expected: " + expected.toString()); LOGGER.info(" Actual: " + actual.toString()); return false; } } } public static boolean assertEquals(final JsonValue expected, final JsonValue actual) { return assertEquals(expected, actual, "JSON mismatch"); } /** * Operation result expected. * * @param expected * Expected modified JSON value. * @param actual * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ public static boolean assertEquals(final Object expected, final String actual) { if (actual == null) { return true; } try { switch (JsonValueType.getType(expected)) { case String: String exp = '\"' + (String) expected + '\"'; return exp.equals(actual); case Integer: return Integer.parseInt(actual) == (Integer) expected; case Long: return Long.parseLong(actual) == (Long) expected; case BigInteger: return (new BigInteger(actual)).equals(expected); case Double: return Double.parseDouble(actual) == (Double) expected; case BigDecimal: return (new BigDecimal(actual)).equals(expected); case Boolean: return Boolean.parseBoolean(actual) == (Boolean) expected; case JsonValue: try (final JsonReader reader = Json .createReader(new StringReader(actual))) { final JsonValue actVal = reader.readValue(); return assertEquals((JsonValue) expected, actVal); } case Null: try (final JsonReader reader = Json .createReader(new StringReader(actual))) { final JsonValue actVal = reader.readValue(); return assertEquals(JsonValue.NULL, actVal); } default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } catch (NumberFormatException ex) { return true; } } /** * Convert provided JSON value to human readable String. * * @param value * Value to be converted. * @return JSON value as human readable String. */ public static String valueToString(final JsonValue value) { switch (value.getValueType()) { case OBJECT: return JSONP_Util.toStringJsonObject((JsonObject) value); case ARRAY: return JSONP_Util.toStringJsonArray((JsonArray) value); case STRING: return ((JsonString) value).getString(); case NUMBER: return ((JsonNumber) value).toString(); case TRUE: return Boolean.toString(true); case FALSE: return Boolean.toString(false); case NULL: return "null"; default: throw new IllegalArgumentException("Unknown value type"); } } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/JsonIO.java000066400000000000000000000022571451447132700316340ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import java.io.StringReader; import jakarta.json.Json; import jakarta.json.JsonValue; // $Id$ /** * Read and write JSON values. */ public class JsonIO { /** * Reads JSON value from {@code String}. * * @param json * JSON value to be read. * @return JSON value from provided {@code String}. */ public static JsonValue read(final String json) { return Json.createReader(new StringReader(json)).readValue(); } } JsonValueType.java000066400000000000000000000076271451447132700331720ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import jakarta.json.JsonValue; // $Id$ /** * Identifiers of types used as JSON value. */ public enum JsonValueType { /** JsonValue is String. */ String, /** JsonValue is Integer. */ Integer, /** JsonValue is Long. */ Long, /** JsonValue is BigInteger. */ BigInteger, /** JsonValue is Double. */ Double, /** JsonValue is BigDecimal. */ BigDecimal, /** JsonValue is Boolean. */ Boolean, /** JsonValue is common JSON value. */ JsonValue, /** JsonValue is null. */ Null; /** Size of this enumeration. */ private static final int SIZE = JsonValueType.values().length; /** Name to value {@code Map}. */ private static final Map VALUES = new HashMap<>(SIZE); // Name to value Map initialization. static { for (int i = 0; i < SIZE; i++) VALUES.put(JsonValueType.values()[i].name(), JsonValueType.values()[i]); } /** * Returns JSON value identifier for provided class. * * @param c * JSON value class. * @return JSON value identifier for provided class. */ public static JsonValueType getType(final Class c) { JsonValueType type = VALUES.get(c.getSimpleName()); if (type != null) { return type; } // Interface hierarchy is a tree so stack machine is required to go trough // it. final LinkedList stack = new LinkedList(); for (final Class i : c.getInterfaces()) { stack.push(i); } while (!stack.isEmpty()) { final Class i = stack.pop(); type = VALUES.get(i.getSimpleName()); if (type != null) { return type; } for (final Class j : i.getInterfaces()) { stack.push(j); } } throw new IllegalArgumentException( "Unsupported JSON value type: " + c.getSimpleName()); } /** * Returns JSON value identifier for provided value. * * @param value * JSON value. * @return JSON value identifier for provided class. */ public static JsonValueType getType(final Object value) { return value != null ? getType(value.getClass()) : Null; } /** * Convert provided value to {@code String} which is part of JSON document. * * @param value * Value be be converted to {@code String}. * @return Value converted to {@code String}. */ public static String toStringValue(final Object value) { switch (getType(value)) { case String: return '"' + ((String) value) + '"'; case Integer: return ((Integer) value).toString(); case Long: return ((Long) value).toString(); case BigInteger: return ((BigInteger) value).toString(); case Double: return ((Double) value).toString(); case BigDecimal: return ((BigDecimal) value).toString(); case Boolean: return ((Boolean) value).toString(); case JsonValue: return JsonAssert.valueToString((JsonValue) value); case Null: return SimpleValues.NULL; default: throw new IllegalArgumentException( "Unsupported JSON value type: " + value.getClass().getSimpleName()); } } } MergeRFCObject.java000066400000000000000000000141611451447132700331320ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonValue; /* * $Id$ */ /** * {@see RFC 7396}: JavaScript * Object Notation (JSON) Merge Patch compatibility sample object.
* Object structure is defined in * {@see RFC 7396: 3. * Example}. */ public class MergeRFCObject { // Following values define JSON object keys from RFC 7396: 3. Example /** RFC 7396 sample JSON object key for {@code /title}. */ public static final String KEY_TITLE = "title"; /** RFC 7396 sample JSON object key for {@code /author/givenName}. */ public static final String KEY_GIVEN_NAME = "givenName"; /** RFC 7396 sample JSON object key for {@code /author/familyName}. */ public static final String KEY_FAMILY_NAME = "familyName"; /** RFC 7396 sample JSON object key for {@code /author}. */ public static final String KEY_AUTHOR = "author"; /** RFC 7396 sample JSON object key for {@code /tags}. */ public static final String KEY_TAGS = "tags"; /** RFC 7396 sample JSON object key for {@code /content}. */ public static final String KEY_CONTENT = "content"; /** RFC 7396 sample JSON object key for {@code /phoneNumber}. */ public static final String KEY_PHONE_NUMBER = "phoneNumber"; // Following values define JSON object source values from RFC 7396: 3. Example /** RFC 7396 sample JSON object source value for {@code /title}. */ public static final String VAL_SRC_TITLE = "Goodbye!"; /** RFC 7396 sample JSON object source value for {@code /author/givenName}. */ public static final String VAL_SRC_GIVEN_NAME = "John"; /** * RFC 7396 sample JSON object source value for {@code /author/familyName}. */ public static final String VAL_SRC_FAMILY_NAME = "Doe"; /** RFC 7396 sample JSON object source value for {@code /author}. */ public static final JsonObject VAL_SRC_AUTHOR = SimpleValues .createSimpleObject(new String[] { KEY_GIVEN_NAME, KEY_FAMILY_NAME }, new Object[] { VAL_SRC_GIVEN_NAME, VAL_SRC_FAMILY_NAME }); /** RFC 7396 sample JSON object source value for {@code /tags/0}. */ public static final String VAL_SRC_TAGS_0 = "example"; /** RFC 7396 sample JSON object source value for {@code /tags/1}. */ public static final String VAL_SRC_TAGS_1 = "sample"; /** RFC 7396 sample JSON object source value for {@code /tags}. */ public static final JsonArray VAL_SRC_TAGS = SimpleValues .createStringArray(new String[] { VAL_SRC_TAGS_0, VAL_SRC_TAGS_1 }); /** RFC 7396 sample JSON object source value for {@code /content}. */ public static final String VAL_SRC_CONTENT = "This will be unchanged"; // Following values define JSON object target values from RFC 7396: 3. Example /** RFC 7396 sample JSON object target value for {@code /title}. */ public static final String VAL_TRG_TITLE = "Hello!"; /** RFC 7396 sample JSON object target value for {@code /author}. */ public static final JsonObject VAL_TRG_AUTHOR = SimpleValues .createSimpleObject(new String[] { KEY_GIVEN_NAME }, new Object[] { VAL_SRC_GIVEN_NAME }); /** RFC 7396 sample JSON object target value for {@code /phoneNumber}. */ public static final String VAL_TRG_PHONE_NUMBER = "+01-123-456-7890"; /** RFC 7396 sample JSON object target value for {@code /tags/0}. */ public static final String VAL_TRG_TAGS_0 = "example"; /** RFC 7396 sample JSON object target value for {@code /tags}. */ public static final JsonArray VAL_TRG_TAGS = SimpleValues .createStringArray(new String[] { VAL_TRG_TAGS_0 }); // Following values define JSON object patch values from RFC 7396: 3. Example /** RFC 7396 sample JSON object patch value for {@code /author/familyName}. */ public static final JsonValue VAL_PATCH_FAMILY_NAME = JsonValue.NULL; /** RFC 7396 sample JSON object patch value for {@code /author}. */ public static final JsonObject VAL_PATCH_AUTHOR = SimpleValues .createSimpleObject(new String[] { KEY_FAMILY_NAME }, new Object[] { VAL_PATCH_FAMILY_NAME }); /** * Create {@see RFC * 7396 example} source JSON object. * * @return Source object from example. */ public static JsonObject createRFCSourceObject() { return Json.createObjectBuilder().add(KEY_TITLE, VAL_SRC_TITLE) .add(KEY_AUTHOR, VAL_SRC_AUTHOR).add(KEY_TAGS, VAL_SRC_TAGS) .add(KEY_CONTENT, VAL_SRC_CONTENT).build(); } /** * Create {@see RFC * 7396 example} target JSON object. * * @return Target object from example. */ public static JsonObject createRFCTargetObject() { return Json.createObjectBuilder().add(KEY_TITLE, VAL_TRG_TITLE) .add(KEY_AUTHOR, VAL_TRG_AUTHOR).add(KEY_TAGS, VAL_TRG_TAGS) .add(KEY_CONTENT, VAL_SRC_CONTENT) .add(KEY_PHONE_NUMBER, VAL_TRG_PHONE_NUMBER).build(); } /** * Create {@see RFC * 7396 example} patch JSON object. * * @return Patch object from example. */ public static JsonObject createRFCPatchObject() { return Json.createObjectBuilder().add(KEY_TITLE, VAL_TRG_TITLE) .add(KEY_PHONE_NUMBER, VAL_TRG_PHONE_NUMBER) .add(KEY_AUTHOR, VAL_PATCH_AUTHOR).add(KEY_TAGS, VAL_TRG_TAGS).build(); } } ObjectBuilder.java000066400000000000000000000043561451447132700331330ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import java.math.BigDecimal; import java.math.BigInteger; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; // $Id$ /** * {@link JsonObjectBuilder} manipulation helper. */ public class ObjectBuilder { /** * Add {@code value} with {@code name} to provided JSON object builder. * * @param builder * Target JSON object builder. * @param name * Name of value to be added. * @param value * Value to be added. * @return JSON object builder containing new {@code value}. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String name, final Object value) { switch (JsonValueType.getType(value)) { case String: return builder.add(name, (String) value); case Integer: return builder.add(name, ((Integer) value).intValue()); case Long: return builder.add(name, ((Long) value).intValue()); case BigInteger: return builder.add(name, ((BigInteger) value)); case Double: return builder.add(name, ((Double) value).doubleValue()); case BigDecimal: return builder.add(name, ((BigDecimal) value)); case Boolean: return builder.add(name, ((Boolean) value).booleanValue()); case JsonValue: return builder.add(name, (JsonValue) value); case Null: return builder.addNull(name); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } } PointerRFCObject.java000066400000000000000000000144621451447132700335170ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; /* * $Id$ */ /** * {@see RFC 6901}: JavaScript * Object Notation (JSON) Pointer compatibility sample object.
* Object structure is defined in * {@see RFC 6901: 5. * JSON String Representation}. */ public class PointerRFCObject { // Following values define JSON object from // RFC 6901: 5. JSON String Representation // https://tools.ietf.org/html/rfc6901#section-5 /** RFC 6901 sample JSON object key for the whole document. */ public static final String RFC_KEY_WHOLE = ""; /** RFC 6901 sample JSON object key for 1st value. */ public static final String RFC_KEY1 = "foo"; /** RFC 6901 sample JSON object pointer for 1st value. */ public static final String RFC_PTR1 = "/foo"; /** RFC 6901 sample JSON object pointer for 1st item of 1st value. */ public static final String RFC_PTR1_ITEM1 = "/foo/0"; /** RFC 6901 sample JSON object pointer for 2nd item of 1st value. */ public static final String RFC_PTR1_ITEM2 = "/foo/1"; /** RFC 6901 sample JSON object 1st value: array 1st item. */ public static final String RFC_VAL1_ITEM1 = "bar"; /** RFC 6901 sample JSON object 1st value: array 2nd item. */ public static final String RFC_VAL1_ITEM2 = "baz"; /** RFC 6901 sample JSON object 1st value. */ public static final JsonArray RFC_VAL1 = SimpleValues .createStringArray(RFC_VAL1_ITEM1, RFC_VAL1_ITEM2); /** RFC 6901 sample JSON object key for 2nd value. */ public static final String RFC_KEY2 = ""; /** RFC 6901 sample JSON object pointer for 2nd value. */ public static final String RFC_PTR2 = "/"; /** RFC 6901 sample JSON object 2nd value. */ public static final int RFC_VAL2 = 0; /** RFC 6901 sample JSON object key for 3rd value. */ public static final String RFC_KEY3 = "a/b"; /** RFC 6901 sample JSON object pointer for 3rd value. */ public static final String RFC_PTR3_ENC = "/a~1b"; /** RFC 6901 sample JSON object pointer for 3rd value. */ public static final String RFC_PTR3 = "/a/b"; /** RFC 6901 sample JSON object 3rd value. */ public static final int RFC_VAL3 = 1; /** RFC 6901 sample JSON object key for 4th value. */ public static final String RFC_KEY4 = "c%d"; /** RFC 6901 sample JSON object pointer for 4th value. */ public static final String RFC_PTR4 = "/c%d"; /** RFC 6901 sample JSON object 4th value. */ public static final int RFC_VAL4 = 2; /** RFC 6901 sample JSON object key for 5th value. */ public static final String RFC_KEY5 = "e^f"; /** RFC 6901 sample JSON object pointer for 5th value. */ public static final String RFC_PTR5 = "/e^f"; /** RFC 6901 sample JSON object 5th value. */ public static final int RFC_VAL5 = 3; /** RFC 6901 sample JSON object key for 6th value. */ public static final String RFC_KEY6 = "g|h"; /** RFC 6901 sample JSON object pointer for 6th value. */ public static final String RFC_PTR6 = "/g|h"; /** RFC 6901 sample JSON object 6th value. */ public static final int RFC_VAL6 = 4; /** RFC 6901 sample JSON object key for 7th value. */ public static final String RFC_KEY7 = "i\\j"; /** RFC 6901 sample JSON object pointer for 7th value. */ public static final String RFC_PTR7 = "/i\\j"; /** RFC 6901 sample JSON object 7th value. */ public static final int RFC_VAL7 = 5; /** RFC 6901 sample JSON object key for 8th value. */ public static final String RFC_KEY8 = "k\"l"; /** RFC 6901 sample JSON object pointer for 8th value. */ public static final String RFC_PTR8 = "/k\"l"; /** RFC 6901 sample JSON object 8th value. */ public static final int RFC_VAL8 = 6; /** RFC 6901 sample JSON object key for 9th value. */ public static final String RFC_KEY9 = " "; /** RFC 6901 sample JSON object pointer for 9th value. */ public static final String RFC_PTR9 = "/ "; /** RFC 6901 sample JSON object 9th value. */ public static final int RFC_VAL9 = 7; /** RFC 6901 sample JSON object key for 10th value. */ public static final String RFC_KEY10 = "m~n"; /** RFC 6901 sample JSON object encoded pointer for 10th value. */ public static final String RFC_KEY10_ENC = "/m~0n"; /** RFC 6901 sample JSON object pointer for 10th value. */ public static final String RFC_PTR10 = "/m~n"; /** RFC 6901 sample JSON object 10th value. */ public static final int RFC_VAL10 = 8; /** RFC 6901 sample JSON object key for 11th value. */ public static final String RFC_KEY11 = "o~1p"; /** RFC 6901 sample JSON object encoded pointer for 11th value. */ public static final String RFC_PTR11_ENC = "/o~01p"; /** RFC 6901 sample JSON object pointer for 11th value. */ public static final String RFC_PTR11 = "/o~1p"; /** RFC 6901 sample JSON object 11th value. */ public static final int RFC_VAL11 = 9; /** * Creates RFC 6901 sample JSON object. * {@see RFC 6901: 5. * JSON String Representation} * * @return RFC 6901 sample JSON object. */ public static JsonObject createRFC6901Object() { return Json.createObjectBuilder().add(RFC_KEY1, RFC_VAL1) .add(RFC_KEY2, RFC_VAL2).add(RFC_KEY3, RFC_VAL3).add(RFC_KEY4, RFC_VAL4) .add(RFC_KEY5, RFC_VAL5).add(RFC_KEY6, RFC_VAL6).add(RFC_KEY7, RFC_VAL7) .add(RFC_KEY8, RFC_VAL8).add(RFC_KEY9, RFC_VAL9) .add(RFC_KEY10, RFC_VAL10).add(RFC_KEY11, RFC_VAL11).build(); } /** * Create an instance of RFC 6901 object class is not allowed. */ private PointerRFCObject() { } } SimpleValues.java000066400000000000000000001107701451447132700330250ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.logging.Logger; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonPatch; import jakarta.json.JsonValue; import jakarta.json.JsonWriter; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Build various simple values for testing. */ public class SimpleValues { private static final Logger LOGGER = Logger.getLogger(SimpleValues.class.getName()); /** Name of JSON {@code String} value used in tests. */ public static final String STR_NAME = "address"; /** Path of JSON {@code String} value used in tests. */ public static final String STR_PATH = "/" + STR_NAME; /** JSON {@code String} value used in tests. */ public static final String STR_VALUE = "In a galaxy far far away"; /** JSON {@code String} second value used in tests. */ public static final String STR_VALUE2 = "In a land of myth"; /** Name of JSON {@code int} value used in tests. */ public static final String INT_NAME = "age"; /** Path of JSON {@code int} value used in tests. */ public static final String INT_PATH = "/" + INT_NAME; /** JSON {@code int} value used in tests. */ public static final int INT_VALUE = 42; /** JSON {@code int} second value used in tests. */ public static final int INT_VALUE2 = 32; /** Name of JSON {@code boolean} value used in tests. */ public static final String BOOL_NAME = "married"; /** Path of JSON {@code boolean} value used in tests. */ public static final String BOOL_PATH = "/" + BOOL_NAME; /** JSON {@code boolean} value used in tests. */ public static final boolean BOOL_VALUE = true; /** JSON {@code boolean} second value used in tests. */ public static final boolean BOOL_VALUE2 = false; /** Name of JSON {@code JsonObject} value used in tests. */ public static final String OBJ_NAME = "wife"; /** Path of JSON {@code JsonObject} value used in tests. */ public static final String OBJ_PATH = "/" + OBJ_NAME; /** JSON {@code JsonObject} value used in tests. */ public static final JsonObject OBJ_VALUE = createSimpleObject( new String[] { "name", "age" }, new Object[] { "Sarah Connor", 32 }); /** JSON {@code JsonObject} second value used in tests. */ public static final JsonObject OBJ_VALUE2 = createSimpleObject( new String[] { "name", "age" }, new Object[] { "Kyle Reese", 35 }); /** Name of JSON default value stored in simple object. */ public static final String DEF_NAME = "name"; /** Name of JSON default value stored in simple object. */ public static final String DEF_PATH = "/" + DEF_NAME; /** JSON default value stored in simple object. */ public static final String DEF_VALUE = "John Smith"; /** Name of JSON object stored in compound object. */ public static final String DEF_OBJ_NAME = "child"; /** Path of JSON object stored in compound object. */ public static final String DEF_OBJ_PATH = "/child"; /** JSON default object stored in simple object. */ public static final JsonObject DEF_OBJ_VALUE = createSimpleObject( new String[] { "name", "age" }, new Object[] { "John Connor", 6 }); /** JSON default object stored in simple object with name changed. */ public static final JsonObject DEF_OBJ_VALUE2 = createSimpleObject( new String[] { "name", "age" }, new Object[] { "John Smith", 6 }); /** Value of JSON {@code String} array at index 0. */ public static final String STR_VALUE_1 = "First value"; /** Value of JSON {@code String} array at index 1. */ public static final String STR_VALUE_2 = "Second value"; /** Value of JSON {@code String} array at index 2. */ public static final String STR_VALUE_3 = "Third value"; /** Value of JSON {@code String} array at index 3. */ public static final String STR_VALUE_4 = "Fourth value"; /** Value of JSON {@code String} array at index 4. */ public static final String STR_VALUE_5 = "Fifth value"; /** Value of JSON {@code String} array at index 5. */ public static final String STR_VALUE_6 = "Sixth value"; /** Value of JSON {@code String} array at index 6. */ public static final String STR_VALUE_7 = "Seventh value"; /** Value of JSON {@code int} array at index 0. */ public static final int INT_VALUE_1 = 1; /** Value of JSON {@code int} array at index 1. */ public static final int INT_VALUE_2 = 2; /** Value of JSON {@code int} array at index 2. */ public static final int INT_VALUE_3 = 3; /** Value of JSON {@code int} array at index 3. */ public static final int INT_VALUE_4 = 4; /** Value of JSON {@code int} array at index 4. */ public static final int INT_VALUE_5 = 5; /** Value of JSON {@code JsonObject} array at index 0. */ public static final JsonObject OBJ_VALUE_1 = createSimpleObject( new String[] { "first" }, new String[] { STR_VALUE_1 }); /** Value of JSON {@code JsonObject} array at index 1. */ public static final JsonObject OBJ_VALUE_2 = createSimpleObject( new String[] { "second" }, new String[] { STR_VALUE_2 }); /** Value of JSON {@code JsonObject} array at index 2. */ public static final JsonObject OBJ_VALUE_3 = createSimpleObject( new String[] { "third" }, new String[] { STR_VALUE_3 }); /** Value of JSON {@code JsonObject} array at index 3. */ public static final JsonObject OBJ_VALUE_4 = createSimpleObject( new String[] { "fourth" }, new String[] { STR_VALUE_4 }); /** Value of JSON {@code JsonObject} array at index 4. */ public static final JsonObject OBJ_VALUE_5 = createSimpleObject( new String[] { "fifth" }, new String[] { STR_VALUE_5 }); /** JSON {@code boolean} value: {@code true}. */ public static final boolean BOOL_TRUE = true; /** JSON {@code boolean} value: {@code false}. */ public static final boolean BOOL_FALSE = false; /** JSON {@code long} value used in tests. */ public static final long LNG_VALUE = Long.MAX_VALUE - 42; /** JSON {@code BigInteger} value used in tests. */ public static final BigInteger BIN_VALUE = new BigInteger( "123456789012345678901234567890"); /** JSON {@code double} value used in tests. */ public static final double DBL_VALUE = 0x1.f5c926b3a0942P+1014; /** JSON {@code BigDecimal} value used in tests. */ public static final BigDecimal BDC_VALUE = new BigDecimal( new BigInteger("1234567890123456789012345678901234567890"), 10); /** Message content: null String. */ public static final String NULL = "null"; /** * Creates empty JSON object. * * @return Empty JSON object. */ public static JsonObject createEmptyObject() { return Json.createObjectBuilder().build(); } /** * Creates empty JSON object after ADD STR_NAME STR_VALUE operation. * * @return Empty JSON object after ADD STR_NAME STR_VALUE operation. */ public static JsonObject createSimpleObjectStr() { return Json.createObjectBuilder().add(STR_NAME, STR_VALUE).build(); } /** * Creates empty JSON object after ADD INT_NAME INT_VALUE operation. * * @return Empty JSON object after ADD INT_NAME INT_VALUE operation. */ public static JsonObject createSimpleObjectInt() { return Json.createObjectBuilder().add(INT_NAME, INT_VALUE).build(); } /** * Creates empty JSON object after ADD BOOL_NAME BOOL_VALUE operation. * * @return Empty JSON object after ADD BOOL_NAME BOOL_VALUE operation. */ public static JsonObject createSimpleObjectBool() { return Json.createObjectBuilder().add(BOOL_NAME, BOOL_VALUE).build(); } /** * Creates empty JSON object after ADD OBJ_NAME OBJ_VALUE operation. * * @return Empty JSON object after ADD OBJ_NAME OBJ_VALUE operation. */ public static JsonObject createSimpleObjectObject() { return Json.createObjectBuilder().add(OBJ_NAME, OBJ_VALUE).build(); } /** * Creates JSON patch to remove STR_NAME attribute from object. * * @return JSON patch */ public static JsonObject createPatchRemoveStr() { return Json.createObjectBuilder().add(STR_NAME, JsonValue.NULL).build(); } /** * Creates JSON patch to remove INT_NAME attribute from object. * * @return JSON patch */ public static JsonObject createPatchRemoveInt() { return Json.createObjectBuilder().add(INT_NAME, JsonValue.NULL).build(); } /** * Creates JSON patch to remove BOOL_NAME attribute from object. * * @return JSON patch */ public static JsonObject createPatchRemoveBool() { return Json.createObjectBuilder().add(BOOL_NAME, JsonValue.NULL).build(); } /** * Creates JSON patch to remove OBJ_NAME attribute from object. * * @return JSON patch */ public static JsonObject createPatchRemoveObject() { return Json.createObjectBuilder().add(OBJ_NAME, JsonValue.NULL).build(); } /** * Creates empty JSON array. * * @return Empty JSON array. */ public static JsonArray createEmptyArray() { return Json.createArrayBuilder().build(); } /** * Creates empty JSON array after ADD STR_VALUE operation. * * @return Empty JSON array after ADD STR_VALUE operation. */ public static JsonArray createEmptyArrayWithStr() { return Json.createArrayBuilder().add(STR_VALUE).build(); } /** * Creates empty JSON array after ADD INT_VALUE operation. * * @return Empty JSON array after ADD INT_VALUE operation. */ public static JsonArray createEmptyArrayWithInt() { return Json.createArrayBuilder().add(INT_VALUE).build(); } /** * Creates empty JSON array after ADD BOOL_VALUE operation. * * @return Empty JSON array after ADD BOOL_VALUE operation. */ public static JsonArray createEmptyArrayWithBool() { return Json.createArrayBuilder().add(BOOL_VALUE).build(); } /** * Creates empty JSON array after ADD OBJ_VALUE operation. * * @return Empty JSON array after ADD OBJ_VALUE operation. */ public static JsonArray createEmptyArrayWithObject() { return Json.createArrayBuilder().add(OBJ_VALUE).build(); } /** * Creates simple JSON object. * * @return Simple JSON object. */ public static JsonObject createSimpleObject() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE).build(); } /** * Creates simple JSON object after ADD STR_NAME STR_VALUE operation. * * @return Simple JSON object after ADD STR_NAME STR_VALUE operation. */ public static JsonObject createSimpleObjectWithStr() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(STR_NAME, STR_VALUE).build(); } /** * Creates simple JSON object after REPLACE STR_NAME STR_VALUE operation. * * @return Simple JSON object after REPLACE STR_NAME STR_VALUE operation. */ public static JsonObject createSimpleObjectReplaceStr() { return Json.createObjectBuilder().add(STR_NAME, STR_VALUE2).build(); } /** * Creates simple JSON object after MOVE STR_NAME DEF_NAME operation. * * @return Simple JSON object after MOVE STR_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectMoveStr() { return Json.createObjectBuilder().add(DEF_NAME, STR_VALUE).build(); } /** * Creates simple JSON object after COPY STR_NAME DEF_NAME operation. * * @return Simple JSON object after COPY STR_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectCopyStr() { return Json.createObjectBuilder().add(STR_NAME, STR_VALUE) .add(DEF_NAME, STR_VALUE).build(); } /** * Creates simple JSON object after ADD INT_NAME INT_VALUE operation. * * @return Simple JSON object after ADD INT_NAME INT_VALUE operation. */ public static JsonObject createSimpleObjectWithInt() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(INT_NAME, INT_VALUE).build(); } /** * Creates simple JSON object after REPLACE INT_NAME INT_VALUE operation. * * @return Simple JSON object after REPLACE INT_NAME INT_VALUE operation. */ public static JsonObject createSimpleObjectReplaceInt() { return Json.createObjectBuilder().add(INT_NAME, INT_VALUE2).build(); } /** * Creates simple JSON object after MOVE INT_NAME DEF_NAME operation. * * @return Simple JSON object after MOVE INT_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectMoveInt() { return Json.createObjectBuilder().add(DEF_NAME, INT_VALUE).build(); } /** * Creates simple JSON object after COPY INT_NAME DEF_NAME operation. * * @return Simple JSON object after COPY INT_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectCopyInt() { return Json.createObjectBuilder().add(INT_NAME, INT_VALUE) .add(DEF_NAME, INT_VALUE).build(); } /** * Creates simple JSON object after ADD BOOL_NAME BOOL_VALUE operation. * * @return Simple JSON object after ADD BOOL_NAME BOOL_VALUE operation. */ public static JsonObject createSimpleObjectWithBool() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(BOOL_NAME, BOOL_VALUE).build(); } /** * Creates simple JSON object after REPLACE BOOL_NAME BOOL_VALUE operation. * * @return Simple JSON object after REPLACE BOOL_NAME BOOL_VALUE operation. */ public static JsonObject createSimpleObjectReplaceBool() { return Json.createObjectBuilder().add(BOOL_NAME, BOOL_VALUE2).build(); } /** * Creates simple JSON object after MOVE BOOL_NAME DEF_NAME operation. * * @return Simple JSON object after MOVE BOOL_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectMoveBool() { return Json.createObjectBuilder().add(DEF_NAME, BOOL_VALUE).build(); } /** * Creates simple JSON object after COPY BOOL_NAME DEF_NAME operation. * * @return Simple JSON object after COPY BOOL_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectCopyBool() { return Json.createObjectBuilder().add(BOOL_NAME, BOOL_VALUE) .add(DEF_NAME, BOOL_VALUE).build(); } /** * Creates simple JSON object. * * @return Simple JSON object. */ public static JsonObject createCompoundObject() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).build(); } /** * Creates simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. * * @return Simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. */ public static JsonObject createCompoundObjectWithObject() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).add(OBJ_NAME, OBJ_VALUE).build(); } /** * Creates simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. * * @return Simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. */ public static JsonObject createCompoundObjectReplaceObject() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).add(OBJ_NAME, OBJ_VALUE2).build(); } /** * Creates simple JSON object after MOVE DEF_PATH DEF_OBJ_PATH+DEF_PATH. * * @return Simple JSON object. */ public static JsonObject createCompoundObjectMoveValue() { return Json.createObjectBuilder().add(DEF_OBJ_NAME, DEF_OBJ_VALUE2).build(); } /** * Creates simple JSON object after COPY DEF_PATH DEF_OBJ_PATH+DEF_PATH. * * @return Simple JSON object. */ public static JsonObject createCompoundObjectCopyValue() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(DEF_OBJ_NAME, DEF_OBJ_VALUE2).build(); } /** * Creates simple JSON object after MOVE OBJ_NAME DEF_NAME operation. * * @return Simple JSON object after MOVE OBJ_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectMoveObject() { return Json.createObjectBuilder().add(DEF_NAME, OBJ_VALUE).build(); } /** * Creates simple JSON object after COPY OBJ_NAME DEF_NAME operation. * * @return Simple JSON object after COPY OBJ_NAME DEF_NAME operation. */ public static JsonObject createSimpleObjectCopyObject() { return Json.createObjectBuilder().add(OBJ_NAME, OBJ_VALUE) .add(DEF_NAME, OBJ_VALUE).build(); } /** * Creates compound JSON object after ADD DEF_OBJ_NAME, * createSimpleStringArray5(). * * @return compound JSON object with ADD operation applied. */ public static JsonObject createCompoundObjectWithObjectReplaced() { return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) .add(DEF_OBJ_NAME, createSimpleStringArray5()).build(); } /** * Creates simple JSON object with provided {@code name[i]} and * {@code value[i]} pairs. * * @param names * Names of JSON values to be added. Pairs of {@code names[i]} and * {@code values[i]} are used for add operations. * @param values * JSON values to be added for specified names. * @return Simple JSON object. */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonObject createSimpleObject(final String[] names, final Object[] values) { if (names.length != values.length) { throw new IllegalArgumentException( "Number of paths does not match number of indexes"); } JsonObjectBuilder builder = Json.createObjectBuilder(); for (int i = 0; i < names.length; i++) { switch (JsonValueType.getType(values[i].getClass())) { case String: builder = builder.add(names[i], (String) values[i]); break; case Integer: builder = builder.add(names[i], ((Integer) values[i]).intValue()); break; case Boolean: builder = builder.add(names[i], ((Boolean) values[i]).booleanValue()); break; case JsonValue: builder = builder.add(names[i], (JsonValue) values[i]); break; default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } return builder.build(); } /** * Creates simple JSON array with specified {@code String} values. * * @param values * JSON array {@code String} values. * @return Newly created JSON array. */ public static JsonArray createStringArray(final String... values) { JsonArrayBuilder builder = Json.createArrayBuilder(); if (values != null) { for (final String value : values) { builder = builder.add(value); } } return builder.build(); } /** * Creates simple JSON array with single {@code String}. * * @return Newly created JSON array. */ public static JsonArray createStringArray1() { return Json.createArrayBuilder().add(STR_VALUE_1).build(); } /** * Creates simple JSON array after ADD STR_VALUE operation before existing * element. * * @return Simple JSON array after ADD STR_VALUE operation before existing * element. */ public static JsonArray createSimpleStringArrayWithStrBefore() { return Json.createArrayBuilder().add(STR_VALUE).add(STR_VALUE_1).build(); } /** * Creates simple JSON array after ADD STR_VALUE operation after existing * element. * * @return Simple JSON array after ADD STR_VALUE operation after existing * element. */ public static JsonArray createSimpleStringArrayWithStrAfter() { return Json.createArrayBuilder().add(STR_VALUE_1).add(STR_VALUE).build(); } /** * Creates simple JSON array after REPLACE STR_VALUE operation on existing * element. * * @return Simple JSON array after REPLACE STR_VALUE operation on existing * element. */ public static JsonArray createSimpleStringArrayReplaceStr() { return Json.createArrayBuilder().add(STR_VALUE).build(); } /** * Creates simple JSON array with two {@code String} values. * * @return Newly created JSON array. */ public static JsonArray createStringArray2() { return Json.createArrayBuilder().add(STR_VALUE_2).add(STR_VALUE_4).build(); } /** * Creates simple JSON array with two {@code String} values in reversed order. * * @return Newly created JSON array. */ public static JsonArray createStringArray2R() { return Json.createArrayBuilder().add(STR_VALUE_4).add(STR_VALUE_2).build(); } /** * Creates simple JSON array with two {@code String} values to be inserted * into another array. * * @return Newly created JSON array. */ public static JsonArray createStringInnerArray2() { return Json.createArrayBuilder().add(STR_VALUE_6).add(STR_VALUE_7).build(); } /** * Creates simple JSON array with three {@code String} values as a result of * COPY 2nd element to the beginning of the array. * * @return Newly created JSON array. */ public static JsonArray createStringArray2Copy1to0() { return Json.createArrayBuilder().add(STR_VALUE_4).add(STR_VALUE_2) .add(STR_VALUE_4).build(); } /** * Creates simple JSON array with three {@code String} values as a result of * COPY 1st element to the end of the array. * * @return Newly created JSON array. */ public static JsonArray createStringArray2Copy0to2() { return Json.createArrayBuilder().add(STR_VALUE_2).add(STR_VALUE_4) .add(STR_VALUE_2).build(); } /** * Creates simple JSON array with three {@code String} values as a result of * COPY 1st element to the middle of the array. * * @return Newly created JSON array. */ public static JsonArray createStringArray2Copy0to1() { return Json.createArrayBuilder().add(STR_VALUE_2).add(STR_VALUE_2) .add(STR_VALUE_4).build(); } /** * Creates simple JSON array with five {@code String} values. * * @return Newly created JSON array. */ public static JsonArray createSimpleStringArray5() { return Json.createArrayBuilder().add(STR_VALUE_1).add(STR_VALUE_2) .add(STR_VALUE_3).add(STR_VALUE_4).add(STR_VALUE_5).build(); } /** * Creates simple JSON array with five {@code String} values in reversed * order. * * @return Newly created JSON array. */ public static JsonArray createSimpleStringArray5R() { return Json.createArrayBuilder().add(STR_VALUE_5).add(STR_VALUE_4) .add(STR_VALUE_3).add(STR_VALUE_2).add(STR_VALUE_1).build(); } /** * Creates simple JSON array after ADD [STR_VALUE_6, STR_VALUE_7] operation * between two existing elements. * * @return Simple JSON array after ADD operation. */ public static JsonArray createStringArray2WithStringArrayInTheMiddle() { return Json.createArrayBuilder().add(STR_VALUE_2) .add(createStringInnerArray2()).add(STR_VALUE_4).build(); } /** * Creates simple JSON array with single {@code int}. * * @return Newly created JSON array. */ public static JsonArray createIntArray1() { return Json.createArrayBuilder().add(INT_VALUE_1).build(); } /** * Creates simple JSON array after ADD INT_VALUE operation before existing * element. * * @return Simple JSON array after ADD INT_VALUE operation before existing * element. */ public static JsonArray createSimpleIntArrayWithIntBefore() { return Json.createArrayBuilder().add(INT_VALUE).add(INT_VALUE_1).build(); } /** * Creates simple JSON array after ADD INT_VALUE operation after existing * element. * * @return Simple JSON array after ADD INT_VALUE operation after existing * element. */ public static JsonArray createSimpleIntArrayWithIntAfter() { return Json.createArrayBuilder().add(INT_VALUE_1).add(INT_VALUE).build(); } /** * Creates simple JSON array after REPLACE INT_VALUE operation on existing * element. * * @return Simple JSON array after REPLACE INT_VALUE operation on existing * element. */ public static JsonArray createSimpleIntArrayReplaceInt() { return Json.createArrayBuilder().add(INT_VALUE).build(); } /** * Creates simple JSON array with two {@code int} values. * * @return Newly created JSON array. */ public static JsonArray createIntArray2() { return Json.createArrayBuilder().add(INT_VALUE_2).add(INT_VALUE_4).build(); } /** * Creates simple JSON array with two {@code int} values in reversed order. * * @return Newly created JSON array. */ public static JsonArray createIntArray2R() { return Json.createArrayBuilder().add(INT_VALUE_4).add(INT_VALUE_2).build(); } /** * Creates simple JSON array with three {@code int} values as a result of COPY * 2nd element to the beginning of the array. * * @return Newly created JSON array. */ public static JsonArray createIntArray2Copy1to0() { return Json.createArrayBuilder().add(INT_VALUE_4).add(INT_VALUE_2) .add(INT_VALUE_4).build(); } /** * Creates simple JSON array with three {@code int} values as a result of COPY * 1st element to the end of the array. * * @return Newly created JSON array. */ public static JsonArray createIntArray2Copy0to2() { return Json.createArrayBuilder().add(INT_VALUE_2).add(INT_VALUE_4) .add(INT_VALUE_2).build(); } /** * Creates simple JSON array with three {@code int} values as a result of COPY * 1st element to the middle of the array. * * @return Newly created JSON array. */ public static JsonArray createIntArray2Copy0to1() { return Json.createArrayBuilder().add(INT_VALUE_2).add(INT_VALUE_2) .add(INT_VALUE_4).build(); } /** * Creates simple JSON array with five {@code int} values. * * @return Newly created JSON array. */ public static JsonArray createSimpleIntArray5() { return Json.createArrayBuilder().add(INT_VALUE_1).add(INT_VALUE_2) .add(INT_VALUE_3).add(INT_VALUE_4).add(INT_VALUE_5).build(); } /** * Creates simple JSON array with five {@code int} values in reversed order. * * @return Newly created JSON array. */ public static JsonArray createSimpleIntArray5R() { return Json.createArrayBuilder().add(INT_VALUE_5).add(INT_VALUE_4) .add(INT_VALUE_3).add(INT_VALUE_2).add(INT_VALUE_1).build(); } /** * Creates simple JSON array with single {@code boolean}. * * @return Newly created JSON array. */ public static JsonArray createBoolArray1() { return Json.createArrayBuilder().add(BOOL_TRUE).build(); } /** * Creates simple JSON array after ADD BOOL_FALSE operation before existing * element (BOOL_TRUE). * * @return Simple JSON array after ADD BOOL_FALSE operation before existing * element. */ public static JsonArray createSimpleBoolArrayWithBoolBefore() { return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE).build(); } /** * Creates simple JSON array after ADD BOOL_FALSE operation after existing * element (BOOL_TRUE). * * @return Simple JSON array after ADD BOOL_FALSE operation after existing * element. */ public static JsonArray createSimpleBoolArrayWithBoolAfter() { return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE).build(); } /** * Creates simple JSON array after REPLACE BOOL_FALSE operation on existing * element. * * @return Simple JSON array after REPLACE BOOL_FALSE operation on existing * element. */ public static JsonArray createSimpleBoolArrayReplaceBool() { return Json.createArrayBuilder().add(BOOL_FALSE).build(); } /** * Creates simple JSON array with two {@code boolean} values. * * @return Newly created JSON array. */ public static JsonArray createBoolArray2() { return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE).build(); } /** * Creates simple JSON array with two {@code boolean} values in reverse order. * * @return Newly created JSON array. */ public static JsonArray createBoolArray2R() { return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE).build(); } /** * Creates simple JSON array with three {@code boolean} values as a result of * COPY 2nd element to the beginning of the array. * * @return Newly created JSON array. */ public static JsonArray createBoolArray2Copy1to0() { return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE) .add(BOOL_FALSE).build(); } /** * Creates simple JSON array with three {@code boolean} values as a result of * COPY 1st element to the end of the array. * * @return Newly created JSON array. */ public static JsonArray createBoolArray2Copy0to2() { return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE) .add(BOOL_TRUE).build(); } /** * Creates simple JSON array with three {@code boolean} values as a result of * COPY 1st element to the middle of the array. * * @return Newly created JSON array. */ public static JsonArray createBoolArray2Copy0to1() { return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_TRUE) .add(BOOL_FALSE).build(); } /** * Creates simple JSON array with five {@code boolean} values. * * @return Newly created JSON array. */ public static JsonArray createSimpleBoolArray5() { return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE) .add(BOOL_TRUE).add(BOOL_FALSE).add(BOOL_TRUE).build(); } /** * Creates simple JSON array with five {@code boolean} values in reversed * order. * * @return Newly created JSON array. */ public static JsonArray createSimpleBoolArray5R() { return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE) .add(BOOL_TRUE).add(BOOL_TRUE).add(BOOL_FALSE).build(); } /** * Creates simple JSON array with single {@code JsonObject}. * * @return Newly created JSON array. */ public static JsonArray createObjectArray1() { return Json.createArrayBuilder().add(OBJ_VALUE_1).build(); } /** * Creates simple JSON array after ADD OBJ_VALUE operation before existing * element. * * @return Simple JSON array after ADD OBJ_VALUE operation before existing * element. */ public static JsonArray createSimpleObjectArrayWithObjectBefore() { return Json.createArrayBuilder().add(OBJ_VALUE).add(OBJ_VALUE_1).build(); } /** * Creates simple JSON array after ADD OBJ_VALUE operation after existing * element. * * @return Simple JSON array after ADD OBJ_VALUE operation after existing * element. */ public static JsonArray createSimpleObjectArrayWithObjectAfter() { return Json.createArrayBuilder().add(OBJ_VALUE_1).add(OBJ_VALUE).build(); } /** * Creates simple JSON array after REPLACE OBJ_VALUE operation on existing * element. * * @return Simple JSON array after REPLACE OBJ_VALUE operation on existing * element. */ public static JsonArray createSimpleObjectArrayReplaceObject() { return Json.createArrayBuilder().add(OBJ_VALUE).build(); } /** * Creates simple JSON array with two {@code JsonObject} values. * * @return Newly created JSON array. */ public static JsonArray createObjectArray2() { return Json.createArrayBuilder().add(OBJ_VALUE_2).add(OBJ_VALUE_4).build(); } /** * Creates simple JSON array with two {@code JsonObject} values in reverse * order. * * @return Newly created JSON array. */ public static JsonArray createObjectArray2R() { return Json.createArrayBuilder().add(OBJ_VALUE_4).add(OBJ_VALUE_2).build(); } /** * Creates simple JSON array with three {@code JsonObject} values as a result * of COPY 2nd element to the beginning of the array. * * @return Newly created JSON array. */ public static JsonArray createObjectArray2Copy1to0() { return Json.createArrayBuilder().add(OBJ_VALUE_4).add(OBJ_VALUE_2) .add(OBJ_VALUE_4).build(); } /** * Creates simple JSON array with three {@code JsonObject} values as a result * of COPY 1st element to the end of the array. * * @return Newly created JSON array. */ public static JsonArray createObjectArray2Copy0to2() { return Json.createArrayBuilder().add(OBJ_VALUE_2).add(OBJ_VALUE_4) .add(OBJ_VALUE_2).build(); } /** * Creates simple JSON array with three {@code JsonObject} values as a result * of COPY 1st element to the middle of the array. * * @return Newly created JSON array. */ public static JsonArray createObjectArray2Copy0to1() { return Json.createArrayBuilder().add(OBJ_VALUE_2).add(OBJ_VALUE_2) .add(OBJ_VALUE_4).build(); } /** * Creates simple JSON array with five {@code JsonObject} values. * * @return Newly created JSON array. */ public static JsonArray createSimpleObjectArray5() { return Json.createArrayBuilder().add(OBJ_VALUE_1).add(OBJ_VALUE_2) .add(OBJ_VALUE_3).add(OBJ_VALUE_4).add(OBJ_VALUE_5).build(); } /** * Creates simple JSON array with five {@code JsonObject} values in reversed * order. * * @return Newly created JSON array. */ public static JsonArray createSimpleObjectArray5R() { return Json.createArrayBuilder().add(OBJ_VALUE_5).add(OBJ_VALUE_4) .add(OBJ_VALUE_3).add(OBJ_VALUE_2).add(OBJ_VALUE_1).build(); } /** * Convert provided {@code Object} instance to {@code JsonValue}. * * @param value * {@code Object} instance to be converted. * @return JsonValue instance containing provided {@code Object}; */ @SuppressWarnings("UnnecessaryUnboxing") public static JsonValue toJsonValue(final Object value) { if (value == null) { return JsonValue.NULL; } switch (JsonValueType.getType(value.getClass())) { case String: return Json.createValue((String) value); case Integer: return Json.createValue(((Integer) value).intValue()); case Long: return Json.createValue(((Long) value).longValue()); case BigInteger: return Json.createValue((BigInteger) value); case Double: return Json.createValue(((Double) value).doubleValue()); case BigDecimal: return Json.createValue((BigDecimal) value); case Boolean: return ((Boolean) value).booleanValue() ? JsonValue.TRUE : JsonValue.FALSE; case JsonValue: return (JsonValue) value; case Null: return JsonValue.NULL; default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Convert JSON value to {@code String} containing value stored in JSON * format. * * @param value * JSON value to be converted. * @return Provided value stored in JSON format. */ public static String jsonData(final JsonValue value) { final StringWriter strWriter = new StringWriter(); try (final JsonWriter writer = Json.createWriter(strWriter)) { writer.write(value); } catch (JsonException ex) { LOGGER.info( "Could not initialize JSON data: " + ex.getLocalizedMessage()); throw ex; } return strWriter.toString(); } /** * Apply patch on provided JSON {@code value} using {@code apply()} method of * {@code JsonPatch}. * * @param patch * {@code JsonPatch} with patch operations. * @param value * JSON {@code value} to be patched. * @return Result of JSON {@code value} patching. */ public static JsonValue patchApply(final JsonPatch patch, final JsonValue value) { switch (value.getValueType()) { case OBJECT: return patch.apply((JsonObject) value); case ARRAY: return patch.apply((JsonArray) value); default: throw new IllegalArgumentException( "Unsupported JSON value type to be pached"); } } /** * Convert {@code boolean} value to {@code JsonValue}. * * @param value * Source {@code boolean} value. * @return {@code JsonValue.TRUE} if provided {@code value} is {@code true} or * {@code JsonValue.FALSE} otherwise. */ public static JsonValue booleanValue(final boolean value) { return value ? JsonValue.TRUE : JsonValue.FALSE; } /** * Creates an instance of RFC 6902 operation test. */ private SimpleValues() { } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/TestFail.java000066400000000000000000000032571451447132700322070ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; /** * Test failure notification. */ public class TestFail { /** Test failure name and message separator. */ private static final String NM_SEP = ": "; /** Name of test that failed. */ private final String name; /** Error message. */ private final String message; /** * Creates an instance of test failure notification. * * @param name * Test name. * @param message * Error message. */ public TestFail(final String name, final String message) { this.name = name; this.message = message; } /** * Returns human readable content of test failure notification. * * @return Human readable content of test failure notification. */ @Override public String toString() { final StringBuilder sb = new StringBuilder( name.length() + message.length() + NM_SEP.length()); sb.append(name); sb.append(NM_SEP); sb.append(message); return sb.toString(); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/common/TestResult.java000066400000000000000000000036151451447132700326100ustar00rootroot00000000000000/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.common; import org.opentest4j.AssertionFailedError; import java.util.LinkedList; /** * Tests result record. */ public class TestResult { /** Name of test suite. */ private final String name; /** List of test failures. */ private final LinkedList fails; /** * Creates an instance of tests result record. * * @param name * Name of test suite. */ public TestResult(final String name) { this.name = name; this.fails = new LinkedList<>(); } /** * Records test failure. * * @param name * Test name. * @param message * Error message. */ public void fail(final String name, final String message) { fails.addLast(new TestFail(name, message)); } /** * Evaluate test results. * * @throws AssertionFailedError * when any test failed. */ public void eval() { if (fails.isEmpty()) { return; } final StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(" failed:"); for (TestFail fail : fails) { sb.append('\n'); sb.append(fail.toString()); } throw new AssertionFailedError(sb.toString()); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/exceptiontests/000077500000000000000000000000001451447132700314135ustar00rootroot00000000000000ClientTests.java000066400000000000000000000167241451447132700344520ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/exceptiontests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.exceptiontests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import ee.jakarta.tck.jsonp.common.MyJsonLocation; import jakarta.json.*; import jakarta.json.stream.*; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.*; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonExceptionConstructorTest1 * * @assertion_ids: JSONP:JAVADOC:37; * * @test_Strategy: Test API: JsonException ret = new JsonException(String) */ @Test public void jsonExceptionConstructorTest1() { try { String message = "This JSON is incorrect."; LOGGER.info("Test JsonException(String)"); JsonException exception = new JsonException(message); try { throw exception; } catch (JsonException e) { assertEquals(message, e.getMessage(), "jsonExceptionConstructorTest1 failed"); } } catch (Exception e) { fail("jsonExceptionConstructorTest1 Failed: ", e); } } /* * @testName: jsonExceptionConstructorTest2 * * @assertion_ids: JSONP:JAVADOC:38; * * @test_Strategy: Test API: JsonException ret = new JsonException(String, * Throwable) */ @Test public void jsonExceptionConstructorTest2() { try { String message = "This JSON is incorrect due to foo."; Exception foo = new Exception("This is a foo exception"); LOGGER.info("Test JsonException(String, Throwable)"); JsonException exception = new JsonException(message, foo); try { throw exception; } catch (JsonException e) { assertTrue(isPass(foo, e, message), "jsonExceptionConstructorTest2 failed"); } } catch (Exception e) { fail("jsonExceptionConstructorTest2 Failed: ", e); } } /* * @testName: jsonParsingExceptionConstructorTest1 * * @assertion_ids: JSONP:JAVADOC:285; JSONP:JAVADOC:478; JSONP:JAVADOC:474; * JSONP:JAVADOC:475; JSONP:JAVADOC:476; * * @test_Strategy: Test API: JsonParsingException ret = new * JsonParsingException(String, JsonLocation) */ @Test public void jsonParsingExceptionConstructorTest1() { boolean pass = true; try { String message = "This JSON is incorrect."; MyJsonLocation expLoc = new MyJsonLocation(10, 20, 30); LOGGER.info("MyJsonLocation"); JSONP_Util.dumpLocation(expLoc); LOGGER.info("Test JsonParsingException(String, JsonLocation)"); JsonParsingException exception = new JsonParsingException(message, expLoc); try { throw exception; } catch (JsonParsingException e) { if (!e.getMessage().equals(message)) { LOGGER.warning("Incorrect message: expected " + message + ", received " + e.getMessage()); pass = false; } } JsonLocation actLoc = exception.getLocation(); LOGGER.info("JsonParsingException.getLocation()"); JSONP_Util.dumpLocation(actLoc); if (!JSONP_Util.assertEquals(expLoc, actLoc)) pass = false; } catch (Exception e) { fail("jsonParsingExceptionConstructorTest1 Failed: ", e); } assertTrue(pass, "jsonParsingExceptionConstructorTest1 failed"); } /* * @testName: jsonParsingExceptionConstructorTest2 * * @assertion_ids: JSONP:JAVADOC:286; JSONP:JAVADOC:478; JSONP:JAVADOC:474; * JSONP:JAVADOC:475; JSONP:JAVADOC:476; * * @test_Strategy: Test API: JsonParsingException ret = new * JsonParsingException(String, Throwable, JsonLocation) */ @Test public void jsonParsingExceptionConstructorTest2() { boolean pass = true; try { String message = "This JSON is incorrect due to foo."; Exception foo = new Exception("This is a foo exception"); MyJsonLocation expLoc = new MyJsonLocation(10, 20, 30); LOGGER.info("MyJsonLocation"); JSONP_Util.dumpLocation(expLoc); LOGGER.info("Test JsonParsingException(String, Throwable)"); JsonParsingException exception = new JsonParsingException(message, foo, expLoc); try { throw exception; } catch (JsonParsingException e) { pass = isPass(foo, e, message); } JsonLocation actLoc = exception.getLocation(); LOGGER.info("JsonParsingException.getLocation()"); JSONP_Util.dumpLocation(actLoc); if (!JSONP_Util.assertEquals(expLoc, actLoc)) pass = false; } catch (Exception e) { fail("jsonParsingExceptionConstructorTest2 Failed: ", e); } assertTrue(pass, "jsonParsingExceptionConstructorTest2 failed"); } /* * @testName: jsonGenerationExceptionConstructorTest1 * * @assertion_ids: JSONP:JAVADOC:278; * * @test_Strategy: Test API: JsonGenerationException ret = new * JsonGenerationException(String) */ @Test public void jsonGenerationExceptionConstructorTest1() { try { String message = "This JSON is incorrect."; LOGGER.info("Test JsonGenerationException(String)"); JsonGenerationException exception = new JsonGenerationException(message); try { throw exception; } catch (JsonGenerationException e) { assertEquals(message, e.getMessage(), "jsonGenerationExceptionConstructorTest1 failed: Incorrect message"); } } catch (Exception e) { fail("jsonGenerationExceptionConstructorTest1 Failed: ", e); } } /* * @testName: jsonGenerationExceptionConstructorTest2 * * @assertion_ids: JSONP:JAVADOC:279; * * @test_Strategy: Test API: JsonGenerationException ret = new * JsonGenerationException(String, Throwable) */ @Test public void jsonGenerationExceptionConstructorTest2() { try { String message = "This JSON is incorrect due to foo."; Exception foo = new Exception("This is a foo exception"); LOGGER.info("Test JsonGenerationException(String, Throwable)"); JsonGenerationException exception = new JsonGenerationException(message, foo); try { throw exception; } catch (JsonGenerationException e) { assertTrue(isPass(foo, e, message), "jsonGenerationExceptionConstructorTest2 failed"); } } catch (Exception e) { fail("jsonGenerationExceptionConstructorTest2 Failed: ", e); } } private boolean isPass(Exception toCompare, Exception actual, String errorMessage) { boolean pass = true; if (!actual.getCause().equals(toCompare)) { LOGGER.warning("Incorrect cause: expected " + toCompare + ", received " + actual.getCause()); pass = false; } if (!actual.getMessage().equals(errorMessage)) { LOGGER.warning("Incorrect message: expected " + errorMessage + ", received " + actual.getMessage()); pass = false; } return pass; } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/000077500000000000000000000000001451447132700314255ustar00rootroot00000000000000ArrayBuildAdd.java000066400000000000000000000602661451447132700346720ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonarraytests; import ee.jakarta.tck.jsonp.api.common.ArrayBuilder; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonIO; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: * {@link JsonArrayBuilder} API add() methods added in JSON-P 1.1.
*/ public class ArrayBuildAdd extends ArrayCommon { private static final Logger LOGGER = Logger.getLogger(ArrayBuildAdd.class.getName()); /** * Creates an instance of {@link JsonArrayBuilder} API add() methods added in * JSON-P 1.1 test. */ ArrayBuildAdd() { super(); } /** * Test {@link JsonArrayBuilder} API add() methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonArrayBuilder API add() methods added in JSON-P 1.1."); LOGGER.info("JsonArrayBuilder API add() methods added in JSON-P 1.1."); testAdd(result); testAddNullBuilder(result); testAddOutOfBounds(result); testAddNull(result); testAddNullOutOfBounds(result); testAddArrayBuilder(result); testAddArrayBuilderNull(result); testAddArrayBuilderOutOfBounds(result); testAddObjectBuilder(result); testAddObjectBuilderNull(result); testAddObjectBuilderOutOfBounds(result); testAddAllString(result); testAddAllInt(result); testAddAllBool(result); testAddAllObject(result); testAddAllNull(result); return result; } /** * Test {@code default JsonArrayBuilder add(int, Object)} method on * {@code String} array. * * @param result * Test suite result. */ private void testAdd(final TestResult result) { final Object[] values = new Object[] { SimpleValues.OBJ_VALUE, // add(int,JsonValue) SimpleValues.STR_VALUE, // add(int,String) SimpleValues.INT_VALUE, // add(int,int) SimpleValues.LNG_VALUE, // add(int,long) SimpleValues.DBL_VALUE, // add(int,double) SimpleValues.BIN_VALUE, // add(int,BigInteger) SimpleValues.BDC_VALUE, // add(int,BigDecimal) SimpleValues.BOOL_VALUE // add(int,boolean) }; for (Object value : values) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - add(int," + typeName + ")"); final String json = "[" + JsonValueType.toStringValue(value) + "]"; final JsonValue check = JsonIO.read(json); final JsonArrayBuilder builder = createArrayBuilder(0, value); final JsonValue out = builder.build(); if (operationFailed(check, out)) { result.fail("add(" + typeName + ")", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } } /** * Test {@code JsonArrayBuilder add(int, Object)} method on {@code String} * array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testAddOutOfBounds(final TestResult result) { final Object[] values = new Object[] { SimpleValues.OBJ_VALUE, // add(int,JsonValue) SimpleValues.STR_VALUE, // add(int,String) SimpleValues.INT_VALUE, // add(int,int) SimpleValues.LNG_VALUE, // add(int,long) SimpleValues.DBL_VALUE, // add(int,double) SimpleValues.BIN_VALUE, // add(int,BigInteger) SimpleValues.BDC_VALUE, // add(int,BigDecimal) SimpleValues.BOOL_VALUE // add(int,boolean) }; final int[] indexes = new int[] { -1, 2, 3 }; for (Object value : values) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - add(int," + typeName + ")"); final String json = "[" + JsonValueType.toStringValue(value) + "]"; // Add value into the array for the first time to het array of size 1. JsonArrayBuilder builder = createArrayBuilder(value); for (int index : indexes) { try { // Add value on out of bounds index builder = updateOperationBuilder(builder, index, value); result.fail("add(int," + typeName + ")", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("add(int,(" + typeName + ")null)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } } /** * Test {@code JsonArrayBuilder add(int, Object)} method on {@code String} * array with null value. * * @param result * Test suite result. */ private void testAddNullBuilder(final TestResult result) { final JsonValueType[] types = new JsonValueType[] { JsonValueType.JsonValue, // add(int,(JsonValue)null) JsonValueType.String, // add(int,(String)null) JsonValueType.BigInteger, // add(int,(BigInteger)null) JsonValueType.BigDecimal // add(int,(BigDecimal)null) }; for (JsonValueType type : types) { final String typeName = type.name(); LOGGER.info(" - add(int,(" + typeName + ")null)"); try { ArrayBuilder.add(Json.createArrayBuilder(), 0, type); result.fail("add(int,(" + typeName + ")null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("add(int,(" + typeName + ")null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonArrayBuilder addNull(int)} method on {@code String} array. * * @param result * Test suite result. */ private void testAddNull(final TestResult result) { LOGGER.info(" - addNull(int)"); final Object value = null; final String json = "[" + JsonValueType.toStringValue(value) + "]"; final JsonValue check = JsonIO.read(json); final JsonArrayBuilder builder = createArrayBuilder(0, value); final JsonValue out = builder.build(); if (operationFailed(check, out)) { result.fail("addNull(int)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test {@code JsonArrayBuilder addNull(int)} method on {@code String} array * with index being out of range ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testAddNullOutOfBounds(final TestResult result) { final int[] indexes = new int[] { -1, 2, 3 }; LOGGER.info(" - addNull(int)"); final Object value = null; JsonArrayBuilder builder = createArrayBuilder(value); for (int index : indexes) { try { // Add value on out of bounds index builder = updateOperationBuilder(builder, index, value); result.fail("addNull(int)", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("addNull(int)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonArrayBuilder add(int,JsonArrayBuilder)} method on * {@code String} array. * * @param result * Test suite result. */ private void testAddArrayBuilder(final TestResult result) { LOGGER.info(" - add(int,JsonArrayBuilder)"); final JsonValue checkBeg = JsonIO .read("[[" + JsonValueType.toStringValue(SimpleValues.STR_VALUE_1) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_2) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_3) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_4) + "]," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_5) + "]"); final JsonValue checkEnd = JsonIO .read("[" + JsonValueType.toStringValue(SimpleValues.STR_VALUE_1) + ",[" + JsonValueType.toStringValue(SimpleValues.STR_VALUE_2) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_3) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_4) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_5) + "]]"); final JsonArrayBuilder inBeg = createArrayBuilder(SimpleValues.STR_VALUE_5); final JsonArrayBuilder inEnd = createArrayBuilder(SimpleValues.STR_VALUE_1); final JsonArrayBuilder argBeg = createArrayBuilder(SimpleValues.STR_VALUE_1) .add(SimpleValues.STR_VALUE_2).add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4); final JsonArrayBuilder argEnd = createArrayBuilder(SimpleValues.STR_VALUE_2) .add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4).add(SimpleValues.STR_VALUE_5); verifyAddBuilder(result, checkBeg, 0, argBeg, inBeg); verifyAddBuilder(result, checkEnd, 1, argEnd, inEnd); } /** * Test {@code JsonArrayBuilder add(int,(JsonArrayBuilder)null)} method on * {@code String} array. * * @param result * Test suite result. */ private void testAddArrayBuilderNull(final TestResult result) { LOGGER.info(" - add(int,(JsonArrayBuilder)null)"); final JsonArrayBuilder in = createArrayBuilder(SimpleValues.DEF_VALUE); final JsonArrayBuilder arg = null; try { in.add(0, arg); result.fail("add(int,(JsonArrayBuilder)null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("add(int,(JsonArrayBuilder)null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test {@code JsonArrayBuilder add(int,JsonArrayBuilder)} method on * {@code String} array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testAddArrayBuilderOutOfBounds(final TestResult result) { LOGGER.info(" - add(int,JsonArrayBuilder)"); final int[] indexes = new int[] { -1, 5, 6 }; final JsonArrayBuilder in = createArrayBuilder(SimpleValues.STR_VALUE_1).add(SimpleValues.STR_VALUE_2) .add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4); final JsonArrayBuilder arg = createArrayBuilder(SimpleValues.STR_VALUE_5); for (int index : indexes) { try { // Add value on out of bounds index in.add(index, arg); result.fail("add(int,JsonArrayBuilder)", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("add(int,JsonArrayBuilder)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonArrayBuilder add(int,JsonObjectBuilder)} method on * {@code String} array. * * @param result * Test suite result. */ private void testAddObjectBuilder(final TestResult result) { LOGGER.info(" - add(int,JsonObjectBuilder)"); final JsonValue checkBeg = JsonIO .read("[{" + JsonValueType.toStringValue(SimpleValues.STR_NAME) + ":" + JsonValueType.toStringValue(SimpleValues.STR_VALUE) + "}," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_1) + "]"); final JsonValue checkEnd = JsonIO .read("[" + JsonValueType.toStringValue(SimpleValues.STR_VALUE_1) + ",{" + JsonValueType.toStringValue(SimpleValues.STR_NAME) + ":" + JsonValueType.toStringValue(SimpleValues.STR_VALUE) + "}]"); final JsonArrayBuilder inBeg = createArrayBuilder(SimpleValues.STR_VALUE_1); final JsonArrayBuilder inEnd = createArrayBuilder(SimpleValues.STR_VALUE_1); final JsonObjectBuilder argBeg = Json.createObjectBuilder().add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); final JsonObjectBuilder argEnd = Json.createObjectBuilder().add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); verifyAddBuilder(result, checkBeg, 0, argBeg, inBeg); verifyAddBuilder(result, checkEnd, 1, argEnd, inEnd); } /** * Test {@code JsonArrayBuilder add(int,(JsonObjectBuilder)null)} method on * {@code String} array. * * @param result * Test suite result. */ private void testAddObjectBuilderNull(final TestResult result) { LOGGER.info(" - add(int,(JsonObjectBuilder)null)"); final JsonArrayBuilder in = createArrayBuilder(SimpleValues.DEF_VALUE); final JsonObjectBuilder arg = null; try { in.add(0, arg); result.fail("add(int,(JsonObjectBuilder)null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("add(int,(JsonObjectBuilder)null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test {@code JsonArrayBuilder add(int,JsonObjectBuilder)} method on * {@code String} array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testAddObjectBuilderOutOfBounds(final TestResult result) { LOGGER.info(" - add(int,JsonObjectBuilder)"); final int[] indexes = new int[] { -1, 5, 6 }; final JsonArrayBuilder in = createArrayBuilder(SimpleValues.STR_VALUE_1).add(SimpleValues.STR_VALUE_2) .add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4); final JsonObjectBuilder arg = Json.createObjectBuilder().add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); for (int index : indexes) { try { // Add value on out of bounds index in.add(index, arg); result.fail("add(int,JsonObjectBuilder)", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("add(int,JsonObjectBuilder)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on * {@code String} array. * * @param result * Test suite result. */ private void testAddAllString(final TestResult result) { LOGGER.info(" - addAll(JsonArrayBuilder) for String array"); final JsonArray check = SimpleValues.createSimpleStringArray5(); final String[] strings = new String[] { SimpleValues.STR_VALUE_1, SimpleValues.STR_VALUE_2, SimpleValues.STR_VALUE_3, SimpleValues.STR_VALUE_4, SimpleValues.STR_VALUE_5 }; verifyAddAll(result, check, strings); } /** * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on * {@code int) array. @param result Test suite result. */ private void testAddAllInt(final TestResult result) { LOGGER.info(" - addAll(JsonArrayBuilder) for int array"); final JsonArray check = SimpleValues.createSimpleIntArray5(); final Integer[] ints = new Integer[] { SimpleValues.INT_VALUE_1, SimpleValues.INT_VALUE_2, SimpleValues.INT_VALUE_3, SimpleValues.INT_VALUE_4, SimpleValues.INT_VALUE_5 }; verifyAddAll(result, check, ints); } /** * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on * {@code boolean) array. @param result Test suite result. */ private void testAddAllBool(final TestResult result) { LOGGER.info(" - addAll(JsonArrayBuilder) for boolean array"); final JsonArray check = SimpleValues.createSimpleBoolArray5(); final Boolean[] bools = new Boolean[] { SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE }; verifyAddAll(result, check, bools); } /** * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on * {@code JsonObject) array. @param result Test suite result. */ private void testAddAllObject(final TestResult result) { LOGGER.info(" - addAll(JsonArrayBuilder) for JsonObject array"); final JsonArray check = SimpleValues.createSimpleObjectArray5(); final JsonObject[] bools = new JsonObject[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_5 }; verifyAddAll(result, check, bools); } /** * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on * {@code null} builder argument. * * @param result * Test suite result. */ private void testAddAllNull(final TestResult result) { LOGGER.info(" - addAll(JsonArrayBuilder) for null builder argument"); JsonArrayBuilder builder = Json.createArrayBuilder(); try { builder.addAll((JsonArrayBuilder) null); result.fail("addAll(null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("addAll(null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test helper: Verify * {@code default JsonArrayBuilder addAll(JsonArrayBuilder)} method on * provided array. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param values * Values used to build JSON array builder. */ private void verifyAddAll(final TestResult result, final JsonArray check, final Object[] values) { JsonArrayBuilder builderIn = Json.createArrayBuilder(); for (Object value : values) { builderIn = updateOperationBuilder(builderIn, value); } final JsonArrayBuilder builderOut = Json.createArrayBuilder(); builderOut.addAll(builderIn); final JsonArray out = builderOut.build(); if (operationFailed(check, out)) { result.fail("addAll(JsonArrayBuilder)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test helper: Verify * {@code default JsonArrayBuilder add(int,JsonArrayBuilder)} method on * provided builders. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param src * Source builder (the one to be added). * @param target * Target builder (to which to add). */ private void verifyAddBuilder(final TestResult result, final JsonValue check, final int index, final JsonArrayBuilder src, final JsonArrayBuilder target) { final JsonArray out = target.add(index, src).build(); if (operationFailed(check, out)) { result.fail("add(int,JsonArrayBuilder)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test helper: Verify * {@code default JsonArrayBuilder add(int,JsonObjectBuilder)} method on * provided builders. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param src * Source builder (the one to be added). * @param target * Target builder (to which to add). */ private void verifyAddBuilder(final TestResult result, final JsonValue check, final int index, final JsonObjectBuilder src, final JsonArrayBuilder target) { final JsonArray out = target.add(index, src).build(); if (operationFailed(check, out)) { result.fail("add(int,JsonObjectBuilder)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Create and initialize array builder to contain single value. Child class * callback. * * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ @Override protected JsonArrayBuilder createArrayBuilder(final Object value) { return ArrayBuilder.add(Json.createArrayBuilder(), value); } /** * Create and initialize array builder to contain single value. Child class * callback. * * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ @Override protected JsonArrayBuilder createArrayBuilder(final int index, final Object value) { return ArrayBuilder.add(Json.createArrayBuilder(), index, value); } /** * Update array builder to contain next value. Child class callback. * * @param builder * JSON array builder to update. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ @Override protected JsonArrayBuilder updateOperationBuilder( final JsonArrayBuilder builder, final Object value) { return ArrayBuilder.add(builder, value); } /** * Update array builder to contain next value. Child class callback. * * @param builder * JSON array builder to update. * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ @Override protected JsonArrayBuilder updateOperationBuilder( final JsonArrayBuilder builder, final int index, final Object value) { return ArrayBuilder.add(builder, index, value); } } ArrayBuildRemove.java000066400000000000000000000170131451447132700354270ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonarraytests; import ee.jakarta.tck.jsonp.api.common.ArrayBuilder; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonIO; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: * {@link JsonArrayBuilder} API remove() methods added in JSON-P 1.1.
*/ public class ArrayBuildRemove extends ArrayCommon { private static final Logger LOGGER = Logger.getLogger(ArrayBuildRemove.class.getName()); /** * Creates an instance of {@link JsonArrayBuilder} API remove() methods added * in JSON-P 1.1 test. */ ArrayBuildRemove() { super(); } /** * {@link JsonArrayBuilder} API remove() methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonArrayBuilder API remove() methods added in JSON-P 1.1."); LOGGER.info("JsonArrayBuilder API remove() methods added in JSON-P 1.1."); testRemove(result); testRemoveOutOfBounds(result); return result; } /** * Test {@code default JsonArrayBuilder remove(int, Object)} method on * {@code String} array. * * @param result * Test suite result. */ private void testRemove(final TestResult result) { final Object[] values = new Object[] { SimpleValues.OBJ_VALUE, // remove(int,JsonValue) SimpleValues.STR_VALUE, // remove(int,String) SimpleValues.INT_VALUE, // remove(int,int) SimpleValues.LNG_VALUE, // remove(int,long) SimpleValues.DBL_VALUE, // remove(int,double) SimpleValues.BIN_VALUE, // remove(int,BigInteger) SimpleValues.BDC_VALUE, // remove(int,BigDecimal) SimpleValues.BOOL_VALUE // remove(int,boolean) }; for (Object value : values) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - remove(int," + typeName + ")"); final String json = "[]"; final JsonValue check = JsonIO.read(json); JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), value); builder = updateOperationBuilder(builder, 0, null); final JsonValue out = builder.build(); if (operationFailed(check, out)) { result.fail("remove(" + typeName + ")", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } } /** * Test {@code default JsonArrayBuilder remove(int, Object)} method on * {@code String} array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testRemoveOutOfBounds(final TestResult result) { final Object[] values = new Object[] { SimpleValues.OBJ_VALUE, // remove(int,JsonValue) SimpleValues.STR_VALUE, // remove(int,String) SimpleValues.INT_VALUE, // remove(int,int) SimpleValues.LNG_VALUE, // remove(int,long) SimpleValues.DBL_VALUE, // remove(int,double) SimpleValues.BIN_VALUE, // remove(int,BigInteger) SimpleValues.BDC_VALUE, // remove(int,BigDecimal) SimpleValues.BOOL_VALUE // remove(int,boolean) }; final int[] indexes = new int[] { -1, 2, 3 }; for (Object value : values) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - remove(int," + typeName + ")"); final String json = "[" + JsonValueType.toStringValue(value) + "]"; // Add value into the array for the first time to het array of size 1. JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), value); for (int index : indexes) { try { // Add value on out of bounds index builder = updateOperationBuilder(builder, index, null); result.fail("remove(int," + typeName + ")", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("remove(int,(" + typeName + ")null)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } } /** * Create and initialize array builder. Unsupported method call for remove() * method. * * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ @Override protected JsonArrayBuilder createArrayBuilder(Object value) { throw new UnsupportedOperationException( "Method remove is not implemented."); } /** * Create and initialize array builder. Unsupported method call for remove() * method. * * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ @Override protected JsonArrayBuilder createArrayBuilder(final int index, final Object value) { throw new UnsupportedOperationException( "Method remove is not implemented."); } /** * Update array builder. Unsupported method call for remove() method. * * @param builder * JSON array builder to update. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ @Override protected JsonArrayBuilder updateOperationBuilder(JsonArrayBuilder builder, Object value) { throw new UnsupportedOperationException( "Method remove is not implemented."); } /** * Update array builder with value removal at specified index. Child class * callback. * * @param builder * JSON array builder to update. * @param index * Position in the array where value is added. * @param value * JSON value argument is ignored. * @return JSON array builder with value updated. */ @Override protected JsonArrayBuilder updateOperationBuilder( final JsonArrayBuilder builder, final int index, final Object value) { return ArrayBuilder.remove(builder, index); } } ArrayBuildSet.java000066400000000000000000000455111451447132700347310ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonarraytests; import ee.jakarta.tck.jsonp.api.common.ArrayBuilder; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonIO; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: * {@link JsonArrayBuilder} API set() methods added in JSON-P 1.1.
*/ public class ArrayBuildSet extends ArrayCommon { private static final Logger LOGGER = Logger.getLogger(ArrayBuildSet.class.getName()); /** * Creates an instance of {@link JsonArrayBuilder} API set() methods added in * JSON-P 1.1 test. */ ArrayBuildSet() { super(); } /** * {@link JsonArrayBuilder} API set() methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonArrayBuilder API set() methods added in JSON-P 1.1."); LOGGER.info("JsonArrayBuilder API set() methods added in JSON-P 1.1."); testSet(result); testSetOutOfBounds(result); testSetNullBuilder(result); testSetNull(result); testSetNullOutOfBounds(result); testSetArrayBuilder(result); testSetArrayBuilderNull(result); testSetArrayBuilderOutOfBounds(result); testSetObjectBuilder(result); testSetObjectBuilderNull(result); testSetObjectBuilderOutOfBounds(result); return result; } /** * Test {@code default JsonArrayBuilder set(int, Object)} method on * {@code String} array. * * @param result * Test suite result. */ private void testSet(final TestResult result) { final Object[] values = new Object[] { SimpleValues.OBJ_VALUE, // set(int,JsonValue) SimpleValues.STR_VALUE, // set(int,String) SimpleValues.INT_VALUE, // set(int,int) SimpleValues.LNG_VALUE, // set(int,long) SimpleValues.DBL_VALUE, // set(int,double) SimpleValues.BIN_VALUE, // set(int,BigInteger) SimpleValues.BDC_VALUE, // set(int,BigDecimal) SimpleValues.BOOL_VALUE // set(int,boolean) }; for (Object value : values) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - set(int," + typeName + ")"); final String json = "[" + JsonValueType.toStringValue(value) + "]"; final JsonValue check = JsonIO.read(json); final JsonArrayBuilder builder = updateOperationBuilder( Json.createArrayBuilder().add(SimpleValues.DEF_OBJ_VALUE), 0, value); final JsonValue out = builder.build(); if (operationFailed(check, out)) { result.fail("set(" + typeName + ")", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } } /** * Test {@code default JsonArrayBuilder set(int, Object)} method on * {@code String} array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testSetOutOfBounds(final TestResult result) { final Object[] values = new Object[] { SimpleValues.OBJ_VALUE, // set(int,JsonValue) SimpleValues.STR_VALUE, // set(int,String) SimpleValues.INT_VALUE, // set(int,int) SimpleValues.LNG_VALUE, // set(int,long) SimpleValues.DBL_VALUE, // set(int,double) SimpleValues.BIN_VALUE, // set(int,BigInteger) SimpleValues.BDC_VALUE, // set(int,BigDecimal) SimpleValues.BOOL_VALUE // set(int,boolean) }; final int[] indexes = new int[] { -1, 2, 3 }; for (Object value : values) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - set(int," + typeName + ")"); final String json = "[" + JsonValueType.toStringValue(value) + "]"; JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), SimpleValues.DEF_OBJ_VALUE); for (int index : indexes) { try { builder = updateOperationBuilder( Json.createArrayBuilder().add(SimpleValues.DEF_OBJ_VALUE), index, value); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("set(int," + typeName + ")", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } } /** * Test {@code default JsonArrayBuilder set(int, Object)} method on * {@code String} array with null value. * * @param result * Test suite result. */ private void testSetNullBuilder(final TestResult result) { final JsonValueType[] types = new JsonValueType[] { JsonValueType.JsonValue, // set(int,(JsonValue)null) JsonValueType.String, // set(int,(String)null) JsonValueType.BigInteger, // set(int,(BigInteger)null) JsonValueType.BigDecimal // set(int,(BigDecimal)null) }; for (JsonValueType type : types) { final String typeName = type.name(); LOGGER.info(" - set(int,(" + typeName + ")null)"); try { ArrayBuilder.set(Json.createArrayBuilder(), 0, type); result.fail("set(int,(" + typeName + ")null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("set(int,(" + typeName + ")null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code default JsonArrayBuilder setNull(int)} method on {@code String} * array. * * @param result * Test suite result. */ private void testSetNull(final TestResult result) { LOGGER.info(" - setNull(int)"); final Object value = null; final String json = "[" + JsonValueType.toStringValue(null) + "]"; final JsonValue check = JsonIO.read(json); final JsonArrayBuilder builder = ArrayBuilder .set(Json.createArrayBuilder().add(SimpleValues.DEF_OBJ_VALUE), 0, value); final JsonValue out = builder.build(); if (operationFailed(check, out)) { result.fail("setNull(int)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test {@code default JsonArrayBuilder setNull(int)} method on {@code String} * array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testSetNullOutOfBounds(final TestResult result) { final int[] indexes = new int[] { -1, 2, 3 }; LOGGER.info(" - setNull(int)"); final Object value = null; JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), value); for (int index : indexes) { try { // Add value on out of bounds index builder = updateOperationBuilder(builder, index, value); result.fail("setNull(int)", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("setNull(int)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code default JsonArrayBuilder set(int,JsonArrayBuilder)} method on * {@code String} array. * * @param result * Test suite result. */ private void testSetArrayBuilder(final TestResult result) { LOGGER.info(" - set(int,JsonArrayBuilder)"); final JsonValue check = JsonIO .read("[[" + JsonValueType.toStringValue(SimpleValues.STR_VALUE_1) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_2) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_3) + "," + JsonValueType.toStringValue(SimpleValues.STR_VALUE_4) + "]]"); final JsonArrayBuilder in = Json.createArrayBuilder().add(SimpleValues.STR_VALUE_5); final JsonArrayBuilder arg = Json.createArrayBuilder().add(SimpleValues.STR_VALUE_1) .add(SimpleValues.STR_VALUE_2).add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4); verifySetBuilder(result, check, 0, arg, in); } /** * Test {@code default JsonArrayBuilder set(int,(JsonArrayBuilder)null)} * method on {@code String} array. * * @param result * Test suite result. */ private void testSetArrayBuilderNull(final TestResult result) { LOGGER.info(" - set(int,(JsonArrayBuilder)null)"); final JsonArrayBuilder in = Json.createArrayBuilder().add(SimpleValues.DEF_VALUE); final JsonArrayBuilder arg = null; try { in.set(0, arg); result.fail("set(int,(JsonArrayBuilder)null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("set(int,(JsonArrayBuilder)null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test {@code default JsonArrayBuilder set(int,JsonArrayBuilder)} method on * {@code String} array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testSetArrayBuilderOutOfBounds(final TestResult result) { LOGGER.info(" - set(int,JsonArrayBuilder)"); final int[] indexes = new int[] { -1, 5, 6 }; final JsonArrayBuilder in = Json.createArrayBuilder().add(SimpleValues.STR_VALUE_1) .add(SimpleValues.STR_VALUE_2).add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4); final JsonArrayBuilder arg = Json.createArrayBuilder().add(SimpleValues.STR_VALUE_5); for (int index : indexes) { try { // Add value on out of bounds index in.set(index, arg); result.fail("set(int,JsonArrayBuilder)", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("set(int,JsonArrayBuilder)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code default JsonArrayBuilder set(int,JsonObjectBuilder)} method on * {@code String} array. * * @param result * Test suite result. */ private void testSetObjectBuilder(final TestResult result) { LOGGER.info(" - set(int,JsonObjectBuilder)"); final JsonValue check = JsonIO .read("[{" + JsonValueType.toStringValue(SimpleValues.STR_NAME) + ":" + JsonValueType.toStringValue(SimpleValues.STR_VALUE) + "}]"); final JsonArrayBuilder in = Json.createArrayBuilder().add(SimpleValues.STR_VALUE_1); final JsonObjectBuilder arg = Json.createObjectBuilder().add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); verifySetBuilder(result, check, 0, arg, in); } /** * Test {@code default JsonArrayBuilder set(int,(JsonObjectBuilder)null)} * method on {@code String} array. * * @param result * Test suite result. */ private void testSetObjectBuilderNull(final TestResult result) { LOGGER.info(" - set(int,(JsonObjectBuilder)null)"); final JsonArrayBuilder in = Json.createArrayBuilder().add(SimpleValues.DEF_VALUE); final JsonObjectBuilder arg = null; try { in.set(0, arg); result.fail("set(int,(JsonObjectBuilder)null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("set(int,(JsonObjectBuilder)null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test {@code default JsonArrayBuilder set(int,JsonObjectBuilder)} method on * {@code String} array with index being out of range * ({@code index < 0 || index > array size}). * * @param result * Test suite result. */ private void testSetObjectBuilderOutOfBounds(final TestResult result) { LOGGER.info(" - set(int,JsonObjectBuilder)"); final int[] indexes = new int[] { -1, 5, 6 }; final JsonArrayBuilder in = Json.createArrayBuilder().add(SimpleValues.STR_VALUE_1) .add(SimpleValues.STR_VALUE_2).add(SimpleValues.STR_VALUE_3).add(SimpleValues.STR_VALUE_4); final JsonObjectBuilder arg = Json.createObjectBuilder().add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); for (int index : indexes) { try { // Add value on out of bounds index in.set(index, arg); result.fail("set(int,JsonObjectBuilder)", "Calling method with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info(" - Expected exception for index=" + index + ": " + e.getMessage()); } catch (Throwable t) { result.fail("set(int,JsonObjectBuilder)", "Calling method with with out of bounds index=" + index + " argument shall throw IndexOutOfBoundsException, not " + t.getClass().getSimpleName()); } } } /** * Test helper: Verify * {@code default JsonArrayBuilder set(int,JsonArrayBuilder)} method on * provided builders. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param src * Source builder (the one to be added). * @param target * Target builder (to which to add). */ private void verifySetBuilder(final TestResult result, final JsonValue check, final int index, final JsonArrayBuilder src, final JsonArrayBuilder target) { final JsonArray out = target.set(index, src).build(); if (operationFailed(check, out)) { result.fail("set(int,JsonArrayBuilder)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test helper: Verify * {@code default JsonArrayBuilder set(int,JsonObjectBuilder)} method on * provided builders. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param src * Source builder (the one to be added). * @param target * Target builder (to which to add). */ private void verifySetBuilder(final TestResult result, final JsonValue check, final int index, final JsonObjectBuilder src, final JsonArrayBuilder target) { final JsonArray out = target.set(index, src).build(); if (operationFailed(check, out)) { result.fail("set(int,JsonObjectBuilder)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Create and initialize array builder to contain single value. Unsupported * method call for set() method. * * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ @Override protected JsonArrayBuilder createArrayBuilder(Object value) { throw new UnsupportedOperationException("Method set is not implemented."); } /** * Create and initialize array builder to contain single value. Child class * callback. * * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ @Override protected JsonArrayBuilder createArrayBuilder(final int index, final Object value) { return ArrayBuilder.set(Json.createArrayBuilder(), index, value); } /** * Update array builder to contain next value. Unsupported method call for * set() method. * * @param builder * JSON array builder to update. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ @Override protected JsonArrayBuilder updateOperationBuilder(JsonArrayBuilder builder, Object value) { throw new UnsupportedOperationException("Method set is not implemented."); } /** * Update array builder to contain next value. Child class callback. * * @param builder * JSON array builder to update. * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ @Override protected JsonArrayBuilder updateOperationBuilder( final JsonArrayBuilder builder, final int index, final Object value) { return ArrayBuilder.set(builder, index, value); } } ArrayBuilders.java000066400000000000000000000136341451447132700347700ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonarraytests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.util.ArrayList; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonString; import jakarta.json.JsonValue; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import jakarta.json.JsonNumber; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: * {@link JsonArrayBuilder} API factory methods added in JSON-P 1.1.
*/ public class ArrayBuilders { private static final Logger LOGGER = Logger.getLogger(ArrayBuilders.class.getName()); /** * Creates an instance of {@link JsonArrayBuilder} API factory methods added * in JSON-P 1.1 test. */ ArrayBuilders() { super(); } /** * Test {@link JsonArrayBuilder} factory method added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonArrayBuilder API factory methods added in JSON-P 1.1."); LOGGER.info("JsonArrayBuilder API factory methods added in JSON-P 1.1."); testCreateFromCollection(result); testCreateFromJsonArray(result); testGetStringValuesAs(result); testGetIntValuesAs(result); return result; } /** * Test {@link Json#createArrayBuilder(Collection)} method. * * @param result * Test suite result. */ private void testCreateFromCollection(final TestResult result) { LOGGER.info(" - Json#createArrayBuilder(Collection)"); final JsonArray check = SimpleValues.createSimpleStringArray5(); final ArrayList values = new ArrayList<>(check.size()); for (final JsonValue value : check) { values.add(((JsonString) value).getString()); } final JsonArrayBuilder builder = Json.createArrayBuilder(values); final JsonArray out = builder.build(); if (operationFailed(check, out)) { result.fail("createArrayBuilder(Collection)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test {@link Json#createArrayBuilder(JsonArray)} method. * * @param result * Test suite result. */ private void testCreateFromJsonArray(final TestResult result) { LOGGER.info(" - Json#createArrayBuilder(JsonArray)"); final JsonArray check = SimpleValues.createSimpleStringArray5(); final JsonArrayBuilder builder = Json.createArrayBuilder(check); final JsonArray out = builder.build(); if (operationFailed(check, out)) { result.fail("createArrayBuilder(JsonArray)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test {@code default JsonArray#getValuesAs(Function)} method on * {@code String} values. * * @param result * Test suite result. */ private void testGetStringValuesAs(final TestResult result) { LOGGER.info(" - getValuesAs(Function on String array"); final JsonArray in = SimpleValues.createStringArray2(); final List out = in.getValuesAs(JsonString::getString); boolean failed = in.size() != out.size(); if (!failed) { final Iterator inIt = in.iterator(); final Iterator outIt = out.iterator(); while (!failed && inIt.hasNext()) { final JsonValue inVal = inIt.next(); final String outVal = outIt.next(); failed = !((JsonString) inVal).getString().equals(outVal); } } if (failed) { result.fail("getValuesAs(Function)", "Returned Array " + out.toString() + " content shall match " + JsonAssert.valueToString(in)); } } /** * Test {@code default JsonArray#getValuesAs(Function)} method on * {@code int} values. * * @param result * Test suite result. */ private void testGetIntValuesAs(final TestResult result) { LOGGER.info(" - getValuesAs(Function on int array"); final JsonArray in = SimpleValues.createIntArray2(); final List out = in.getValuesAs(JsonNumber::intValue); boolean failed = in.size() != out.size(); if (!failed) { final Iterator inIt = in.iterator(); final Iterator outIt = out.iterator(); while (!failed && inIt.hasNext()) { final JsonValue inVal = inIt.next(); final Integer outVal = outIt.next(); failed = ((JsonNumber) inVal).intValue() != outVal; } } if (failed) { result.fail("getValuesAs(Function)", "Returned Array " + out.toString() + " content shall match " + JsonAssert.valueToString(in)); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } ArrayCommon.java000066400000000000000000000064251451447132700344470ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonarraytests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonValue; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for {@link JsonArray} * and {@link JsonArrayBuilder}. */ public abstract class ArrayCommon { /** * Create and initialize array builder to contain single value. Child class * callback. * * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ protected abstract JsonArrayBuilder createArrayBuilder(final Object value); /** * Create and initialize array builder to contain single value. Child class * callback. * * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder containing value. */ protected abstract JsonArrayBuilder createArrayBuilder(final int index, final Object value); /** * Update array builder to contain next value. Child class callback. * * @param builder * JSON array builder to update. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ protected abstract JsonArrayBuilder updateOperationBuilder( final JsonArrayBuilder builder, final Object value); /** * Update array builder to contain next value. Child class callback. * * @param builder * JSON array builder to update. * @param index * Position in the array where value is added. * @param value * JSON value stored in the builder. Value of {@code null} is stored * as JSON {@code null} keyword. * @return JSON array builder with value updated. */ protected abstract JsonArrayBuilder updateOperationBuilder( final JsonArrayBuilder builder, final int index, final Object value); /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } ClientTests.java000066400000000000000000001544301451447132700344610ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonarraytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonarraytests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Data; import ee.jakarta.tck.jsonp.common.JSONP_Util; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import jakarta.json.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; //$Id$ public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonArrayTest1 * * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:10; * JSONP:JAVADOC:12; JSONP:JAVADOC:14; JSONP:JAVADOC:16; JSONP:JAVADOC:18; * JSONP:JAVADOC:25; JSONP:JAVADOC:21; JSONP:JAVADOC:400; JSONP:JAVADOC:401; * JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; JSONP:JAVADOC:406; * JSONP:JAVADOC:408; JSONP:JAVADOC:409; * * @test_Strategy: Tests JsonArray/JsonArrayBuilder API's. Build a JsonArray * using the JsonArrayBuilder API's then verify that the list of JsonArray * values matches the expected list of JsonArray values. */ @Test public void jsonArrayTest1() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject object = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); JsonArray array = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create the expected list of JsonArray values"); List expList = new ArrayList<>(); expList.add(JsonValue.FALSE); expList.add(JsonValue.TRUE); expList.add(JsonValue.NULL); expList.add(JSONP_Util.createJsonNumber(Double.MIN_VALUE)); expList.add(JSONP_Util.createJsonNumber(Double.MAX_VALUE)); expList.add(JSONP_Util.createJsonNumber(Integer.MIN_VALUE)); expList.add(JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); expList.add(JSONP_Util.createJsonNumber(Long.MIN_VALUE)); expList.add(JSONP_Util.createJsonNumber(Long.MAX_VALUE)); expList.add( JSONP_Util.createJsonNumber(BigDecimal.valueOf(123456789.123456789))); expList.add(JSONP_Util.createJsonNumber(new BigInteger("123456789"))); expList.add(JSONP_Util.createJsonString("string1")); expList.add(object); expList.add(array); JSONP_Util.dumpList(expList, "Expected List"); LOGGER.info("Create JsonArray using all JsonArrayBuilder API's"); JsonArray myJsonArray = Json.createArrayBuilder() // Indices .add(JsonValue.FALSE) // 0 .add(JsonValue.TRUE) // 1 .add(JsonValue.NULL) // 2 .add(Double.MIN_VALUE) // 3 .add(Double.MAX_VALUE) // 4 .add(Integer.MIN_VALUE) // 5 .add(Integer.MAX_VALUE) // 6 .add(Long.MIN_VALUE) // 7 .add(Long.MAX_VALUE) // 8 .add(BigDecimal.valueOf(123456789.123456789)) // 9 .add(new BigInteger("123456789")) // 10 .add("string1") // 11 .add(object) // 12 .add(array) // 13 .build(); List actualList = myJsonArray; JSONP_Util.dumpList(actualList, "Actual List"); LOGGER.info( "Compare actual list of JsonArray values with expected list of JsonArray values"); assertTrue(JSONP_Util.assertEqualsList(expList, actualList), "jsonArrayTest1 Failed"); } catch (Exception e) { fail("jsonArrayTest1 Failed: ", e); } } /* * @testName: jsonArrayTest2 * * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:10; * JSONP:JAVADOC:12; JSONP:JAVADOC:14; JSONP:JAVADOC:16; JSONP:JAVADOC:18; * JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:108; JSONP:JAVADOC:96; * JSONP:JAVADOC:97; JSONP:JAVADOC:21; JSONP:JAVADOC:25; JSONP:JAVADOC:184; * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; * JSONP:JAVADOC:404; JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; * * * @test_Strategy: Tests JsonArray/JsonArrayBuilder API's. Build a JsonArray * using the JsonArrayBuilder API's. Write the JsonArray to a JsonWriter and * read it back using a JsonReader. Verify that JsonArray written to the * JsonWriter and then read back using the JsonReader are equal. */ @Test public void jsonArrayTest2() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject object = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); JsonArray array = JSONP_Util.createSampleJsonArray(); LOGGER.info( "Create JsonArray 'myJsonArray1' using all JsonArrayBuilder API's"); JsonArray myJsonArray1 = Json.createArrayBuilder() // Indices .add(JsonValue.FALSE) // 0 .add(JsonValue.TRUE) // 1 .add(JsonValue.NULL) // 2 .add(Double.MIN_VALUE) // 3 .add(Double.MAX_VALUE) // 4 .add(Integer.MIN_VALUE) // 5 .add(Integer.MAX_VALUE) // 6 .add(Long.MIN_VALUE) // 7 .add(Long.MAX_VALUE) // 8 .add(BigDecimal.valueOf(123456789.123456789)) // 9 .add(new BigInteger("123456789")) // 10 .add("string1") // 11 .add(object) // 12 .add(array) // 13 .build(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); StringWriter sw = new StringWriter(); try (JsonWriter writer = Json.createWriter(sw)) { writer.writeArray(myJsonArray1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sw.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info("Read the JsonArray back into 'myJsonArray2' using a JsonReader"); JsonArray myJsonArray2; try (JsonReader reader = Json.createReader(new StringReader(contents))) { myJsonArray2 = reader.readArray(); } LOGGER.info("Dump contents of JsonArray read from String Contents"); JSONP_Util.dumpJsonValue(myJsonArray2); LOGGER.info("Compare myJsonArray1 and myJsonArray2 for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(myJsonArray1, myJsonArray2), "jsonArrayTest2 Failed"); } catch (Exception e) { fail("jsonArrayTest2 Failed: ", e); } } /* * @testName: jsonArrayTest3 * * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:10; * JSONP:JAVADOC:430; JSONP:JAVADOC:12; JSONP:JAVADOC:14; JSONP:JAVADOC:16; * JSONP:JAVADOC:18; JSONP:JAVADOC:40; JSONP:JAVADOC:41; JSONP:JAVADOC:42; * JSONP:JAVADOC:44; JSONP:JAVADOC:45; JSONP:JAVADOC:46; JSONP:JAVADOC:48; * JSONP:JAVADOC:49; JSONP:JAVADOC:51; JSONP:JAVADOC:21; JSONP:JAVADOC:25; * JSONP:JAVADOC:101; JSONP:JAVADOC:102; JSONP:JAVADOC:262; JSONP:JAVADOC:263; * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; * JSONP:JAVADOC:404; JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; * JSONP:JAVADOC:433; JSONP:JAVADOC:434; JSONP:JAVADOC:435; JSONP:JAVADOC:490; * JSONP:JAVADOC:493; JSONP:JAVADOC:496; JSONP:JAVADOC:499; JSONP:JAVADOC:506; * * @test_Strategy: Tests JsonArray/JsonArrayBuilder API's. Build a JsonArray * using the JsonArrayBuilder API's. Verify contents of JsonArray using * JsonArray().getJsonNumber(int), JsonArray().getJsonString(int), * JsonArray().getJsonArray(int), JsonArray().getJsonObject(). * * This also covers testing the following additional API's: * * JsonString.getString(), JsonNumber.bigDecimalValue(), * JsonNumber.bigIntegerValue(), JsonNumber.doubleValue(), * JsonNumber.intValue(), JsonNumber.longValue(), JsonNumber.isIntegral(), * JsonNumber.longValueExact(), JsonNumber.intValueExact(), * JsonNumber.bigIntegerValueExact(), JsonArray.getInt(int), * JsonArray.getString(int), JsonArrau.getBoolean(int), * JsonArray.getBoolean(int, boolean), JsonArray.getInt(int, int), * JsonArray.getString(int, String) */ @SuppressWarnings("SuspiciousIndentAfterControlStatement") @Test public void jsonArrayTest3() { boolean pass = true; try { LOGGER.info("Create sample JsonObject for testing"); JsonObject object = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); JsonArray array = JSONP_Util.createSampleJsonArray(); int expInt[] = { -1, 1, 1, -1000, 1000, 1000, -2000, 2000, 2000, Integer.MAX_VALUE, Integer.MIN_VALUE }; long expLong[] = { Long.MAX_VALUE, Long.MIN_VALUE }; double expDouble[] = { Double.MAX_VALUE, Double.MIN_VALUE }; LOGGER.info("Create myArray Jsonarray of 23 elements"); JsonArray myArray = Json.createArrayBuilder() // Indices .add(-1).add(+1).add(1) // 0,1,2 .add(-1e3).add(+1e3).add(1e3) // 3,4,5 .add(-2E3).add(+2E3).add(2E3) // 6,7,8 .add(Integer.MAX_VALUE) // 9 .add(Integer.MIN_VALUE) // 10 .add(Long.MAX_VALUE) // 11 .add(Long.MIN_VALUE) // 12 .add(Double.MAX_VALUE) // 13 .add(Double.MIN_VALUE) // 14 .add(BigDecimal.valueOf(123456789.123456789)) // 15 .add(new BigInteger("123456789")) // 16 .add(JsonValue.TRUE) // 17 .add(JsonValue.FALSE) // 18 .add(JsonValue.NULL) // 19 .add(JSONP_Data.asciiCharacters) // 20 .add(object) // 21 .add(array) // 22 .build(); LOGGER.info("Array size=" + myArray.size()); // Following array is used to test for Ints that could be one of following // types: boolean expectedIntTypes[] = { JSONP_Util.INTEGRAL, JSONP_Util.NON_INTEGRAL }; // Verify JsonValueType=NUMBER and integer value equals expectedIntValue for (int i = 0; i < 11; i++) { LOGGER.info("Checking getValue(" + i + ") for correctness"); LOGGER.info("Retrieve and verify (JsonValueType=NUMBER)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, myArray.getJsonNumber(i).getValueType())) pass = false; LOGGER.info("Retrieve and (expect JsonNumber NumberType be one of " + JSONP_Util.toStringJsonNumberTypes(expectedIntTypes) + ")"); if (!JSONP_Util.assertEqualsJsonNumberTypes(expectedIntTypes, myArray.getJsonNumber(i).isIntegral())) pass = false; LOGGER.info("Retrieve and verify integer value via JsonNumber.intValue()"); if (!JSONP_Util.assertEquals(expInt[i], myArray.getJsonNumber(i).intValue())) pass = false; LOGGER.info("Retrieve and verify integer value via JsonArray.getInt"); if (!JSONP_Util.assertEquals(expInt[i], myArray.getInt(i))) pass = false; LOGGER.info( "Retrieve and verify integer value via JsonNumber.intValueExact()"); if (!JSONP_Util.assertEquals(expInt[i], myArray.getJsonNumber(i).intValueExact())) pass = false; } // Verify JsonValueType=NUMBER and long value equals expectedLongValue for (int i = 11, j = 0; i < 13; i++, j++) { LOGGER.info("Checking getValue(" + i + ") for correctness"); LOGGER.info("Retrieve and verify (JsonValueType=NUMBER)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, myArray.getJsonNumber(i).getValueType())) pass = false; LOGGER.info("Retrieve and (expect JsonNumber NumberType be INTEGRAL)"); if (!JSONP_Util.assertEqualsJsonNumberType(JSONP_Util.INTEGRAL, myArray.getJsonNumber(i).isIntegral())) pass = false; LOGGER.info("Retrieve and verify long value via JsonNumber.longValue()"); if (!JSONP_Util.assertEquals(expLong[j], myArray.getJsonNumber(i).longValue())) pass = false; LOGGER.info( "Retrieve and verify long value via JsonNumber.longValueExact()"); if (!JSONP_Util.assertEquals(expLong[j], myArray.getJsonNumber(i).longValueExact())) pass = false; } // Following array is used to test for Doubles that could be one of // following types: boolean expectedDoubleTypes[] = { JSONP_Util.INTEGRAL, JSONP_Util.NON_INTEGRAL }; // Verify JsonValueType=NUMBER and double value equals expectedDoubleValue for (int i = 13, j = 0; i < 15; i++, j++) { LOGGER.info("Checking getValue(" + i + ") for correctness"); LOGGER.info("Retrieve and verify (JsonValueType=NUMBER)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, myArray.getJsonNumber(i).getValueType())) pass = false; LOGGER.info("Retrieve and (expect JsonNumber NumberType be one of " + JSONP_Util.toStringJsonNumberTypes(expectedDoubleTypes) + ")"); if (!JSONP_Util.assertEqualsJsonNumberTypes(expectedDoubleTypes, myArray.getJsonNumber(i).isIntegral())) pass = false; LOGGER.info("Retrieve and verify double value via JsonNumber.doubleValue()"); if (!JSONP_Util.assertEquals(expDouble[j], myArray.getJsonNumber(i).doubleValue())) pass = false; } // Verify JsonValueType=NUMBER and BigDecimalValue equals // expectedBigDecimal LOGGER.info("Checking getValue(15) for correctness"); LOGGER.info("Retrieve and verify (JsonValueType=NUMBER)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, myArray.getJsonNumber(15).getValueType())) pass = false; LOGGER.info("Retrieve and (expect JsonNumber NumberType be one of " + JSONP_Util.toStringJsonNumberTypes(expectedDoubleTypes) + ")"); if (!JSONP_Util.assertEqualsJsonNumberTypes(expectedDoubleTypes, myArray.getJsonNumber(15).isIntegral())) pass = false; LOGGER.info( "Retrieve and verify BigDecimal value via JsonNumber.bigDecimalValue()"); if (!JSONP_Util.assertEquals(BigDecimal.valueOf(123456789.123456789), myArray.getJsonNumber(15).bigDecimalValue())) pass = false; // Verify JsonValueType=NUMBER and BigIntegerValue equals // expectedBigInteger LOGGER.info("Checking getValue(16) for correctness"); LOGGER.info("Retrieve and verify (JsonValueType=NUMBER)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, myArray.getJsonNumber(16).getValueType())) pass = false; LOGGER.info("Retrieve and (expect JsonNumber NumberType be INTEGRAL)"); if (!JSONP_Util.assertEqualsJsonNumberType(JSONP_Util.INTEGRAL, myArray.getJsonNumber(16).isIntegral())) pass = false; LOGGER.info( "Retrieve and verify BigInteger value via JsonNumber.bigIntegerValue()"); if (!JSONP_Util.assertEquals(new BigInteger("123456789"), myArray.getJsonNumber(16).bigIntegerValue())) pass = false; LOGGER.info( "Retrieve and verify BigInteger value via JsonNumber.bigIntegerValueExact()"); if (!JSONP_Util.assertEquals(new BigInteger("123456789"), myArray.getJsonNumber(16).bigIntegerValueExact())) pass = false; // Verify getBoolean(int)=true LOGGER.info("Retrieve and verify true value via JsonArray.getBoolean(int)"); if (!JSONP_Util.assertEquals(true, myArray.getBoolean(17))) pass = false; // Verify getBoolean(int)=false LOGGER.info("Retrieve and verify false value via JsonArray.getBoolean(int)"); if (!JSONP_Util.assertEquals(false, myArray.getBoolean(18))) pass = false; // Verify isNull(int)=true LOGGER.info("Retrieve and verify null value via JsonArray.isNull(int)"); if (!JSONP_Util.assertEquals(true, myArray.isNull(19))) pass = false; // Verify isNull(int)=false LOGGER.info("Retrieve and verify non-null value via JsonArray.isNull(int)"); if (!JSONP_Util.assertEquals(false, myArray.isNull(20))) pass = false; // Verify JsonValueType=STRING and getJsonString()=expectedString LOGGER.info("Checking getValue(20) for correctness"); LOGGER.info("Retrieve and (expect JsonValueType=STRING)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.STRING, myArray.getJsonString(20).getValueType())) pass = false; LOGGER.info("Retrieve and verify string value via JsonString.getString()"); if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, myArray.getJsonString(20).getString())) pass = false; LOGGER.info("Retrieve and verify string value via JsonArray.getString()"); if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, myArray.getString(20))) pass = false; // Verify JsonValueType=OBJECT and getJsonObject()=expectedObject LOGGER.info("Checking getJsonObject(21) for correctness"); LOGGER.info("Retrieve and (expect JsonValueType=OBJECT)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.OBJECT, myArray.getJsonObject(21).getValueType())) pass = false; LOGGER.info( "Retrieve and verify object value via JsonArray.getJsonObject(int)"); if (!JSONP_Util.assertEqualsJsonObjects(object, myArray.getJsonObject(21))) pass = false; // Verify JsonValueType=ARRAY and getJsonArray()=expectedArray LOGGER.info("Checking getJsonArray(22) for correctness"); LOGGER.info("Retrieve and (expect JsonValueType=ARRAY)"); if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.ARRAY, myArray.getJsonArray(22).getValueType())) pass = false; LOGGER.info("Retrieve and verify array value via JsonArray.getJsonArray(int)"); if (!JSONP_Util.assertEqualsJsonArrays(array, myArray.getJsonArray(22))) pass = false; // Verify calls to JsonArray.getBoolean(int) if (!JSONP_Util.assertEquals(true, myArray.getBoolean(17))) pass = false; if (!JSONP_Util.assertEquals(false, myArray.getBoolean(18))) pass = false; // Verify calls to JsonArray.getBoolean(int, boolean) LOGGER.info( "Testing JsonArray.getBoolean(int, boolean) with/without default value setting."); if (!JSONP_Util.assertEquals(true, myArray.getBoolean(17, false))) pass = false; if (!JSONP_Util.assertEquals(false, myArray.getBoolean(0, false))) pass = false; if (!JSONP_Util.assertEquals(false, myArray.getBoolean(19, false))) pass = false; if (!JSONP_Util.assertEquals(false, myArray.getBoolean(20, false))) pass = false; if (!JSONP_Util.assertEquals(false, myArray.getBoolean(21, false))) pass = false; if (!JSONP_Util.assertEquals(false, myArray.getBoolean(22, false))) pass = false; // Verify calls to JsonArray.getInt(int, int) LOGGER.info( "Testing JsonArray.getInt(int, int) with/without default value setting."); if (!JSONP_Util.assertEquals(-1, myArray.getInt(0, 10))) pass = false; if (!JSONP_Util.assertEquals(10, myArray.getInt(17, 10))) pass = false; if (!JSONP_Util.assertEquals(10, myArray.getInt(19, 10))) pass = false; if (!JSONP_Util.assertEquals(10, myArray.getInt(20, 10))) pass = false; if (!JSONP_Util.assertEquals(10, myArray.getInt(21, 10))) pass = false; if (!JSONP_Util.assertEquals(10, myArray.getInt(22, 10))) pass = false; // Verify calls to JsonArray.getString(int, String) LOGGER.info( "Testing JsonArray.getString(int, String) with/without default value setting."); if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, myArray.getString(20, "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myArray.getString(17, "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myArray.getString(19, "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myArray.getString(2, "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myArray.getString(21, "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myArray.getString(22, "foo"))) pass = false; } catch (Exception e) { fail("jsonArrayTest3 Failed: ", e); } assertTrue(pass, "jsonArrayTest3 Failed"); } /* * @testName: jsonArrayTest4 * * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:14; * JSONP:JAVADOC:16; JSONP:JAVADOC:18; JSONP:JAVADOC:21; JSONP:JAVADOC:25; * JSONP:JAVADOC:106; JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; * JSONP:JAVADOC:403; JSONP:JAVADOC:404; JSONP:JAVADOC:406; JSONP:JAVADOC:409; * * @test_Strategy: Build a JsonArray and than write the JsonArray. Compare the * Json text from the writer contents with the expected Json text output * expected based on the JsonArray. */ @Test public void jsonArrayTest4() { try { LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); StringWriter sw = new StringWriter(); try (JsonWriter writer = Json.createWriter(sw)) { writer.writeArray(myJsonArray1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sw.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info("Remove whitespace from contents."); String actJsonText = JSONP_Util.removeWhitespace(contents); LOGGER.info( "Compare expected JsonArray text with actual JsonArray text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonText), "jsonArrayTest4 Failed"); } catch (Exception e) { fail("jsonArrayTest4 Failed: ", e); } } /* * @testName: jsonArrayGetValuesAsTest * * @assertion_ids: JSONP:JAVADOC:403; JSONP:JAVADOC:481; JSONP:JAVADOC:8; * JSONP:JAVADOC:14; * * @test_Strategy: Build a Json array of values of the same type. Get the * values as a list for that type. Compare results in list to what is expected * for equality. * * APIs called: JsonArray array = Json.createArrayBuilder().add(...).build() * List JsonArray.getValuesAs(Class) */ @SuppressWarnings("SuspiciousIndentAfterControlStatement") @Test public void jsonArrayGetValuesAsTest() { boolean pass = true; try { LOGGER.info("Create sample JsonArray of JsonNumber types for testing"); JsonArray jsonArr = Json.createArrayBuilder().add(100).add(500).build(); LOGGER.info("Create the expected list of JsonArray values"); List expList = new ArrayList<>(); expList.add(JSONP_Util.createJsonNumber(100)); expList.add(JSONP_Util.createJsonNumber(500)); JSONP_Util.dumpList(expList, "Expected List"); LOGGER.info("Create the JsonNumber list of JsonArray values"); List numList = jsonArr.getValuesAs(JsonNumber.class); LOGGER.info("Create the actual list of JsonArray values"); List actList = new ArrayList<>(); for (JsonNumber num : numList) actList.add(num); LOGGER.info("Compare actual list with expected list for equality"); pass = JSONP_Util.assertEqualsList(expList, actList); LOGGER.info("Create sample JsonArray of JsonString types for testing"); jsonArr = Json.createArrayBuilder().add("hello").add("world").build(); LOGGER.info("Create the list of JsonString values"); List strList = jsonArr.getValuesAs(JsonString.class); LOGGER.info("Comparing JsonString list elements to expected values."); if (!JSONP_Util.assertEquals(jsonArr.getString(0), strList.get(0).getString())) pass = false; if (!JSONP_Util.assertEquals(jsonArr.getString(1), strList.get(1).getString())) pass = false; } catch (Exception e) { fail("jsonArrayGetValuesAsTest Failed: ", e); } assertTrue(pass, "jsonArrayGetValuesAsTest Failed"); } /* * @testName: jsonArrayExceptionTests * * @assertion_ids: JSONP:JAVADOC:43; JSONP:JAVADOC:47; JSONP:JAVADOC:50; * JSONP:JAVADOC:20; JSONP:JAVADOC:377; JSONP:JAVADOC:432; JSONP:JAVADOC:379; * JSONP:JAVADOC:378; JSONP:JAVADOC:380; JSONP:JAVADOC:431; JSONP:JAVADOC:400; * JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; JSONP:JAVADOC:491; * JSONP:JAVADOC:492; JSONP:JAVADOC:494; JSONP:JAVADOC:495; JSONP:JAVADOC:497; * JSONP:JAVADOC:498; JSONP:JAVADOC:500; JSONP:JAVADOC:501; JSONP:JAVADOC:507; * * @test_Strategy: Test JsonArray exception conditions. Trips the exceptions: * java.lang.IndexOutOfBoundsException java.lang.ArithmeticException * java.lang.NumberFormatException java.lang.ClassCastException * java.lang.UnsupportedOperationException */ @Test public void jsonArrayExceptionTests() { boolean pass = true; JsonObject testObject = null; JsonArray testArray = null; try { LOGGER.info("Create sample JsonObject for testing"); testObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); testArray = JSONP_Util.createSampleJsonArray(); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonNumber via getJsonNumber(int)"); JsonNumber value = testArray.getJsonNumber(0); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to JsonNumber via getJsonNumber(int)"); JsonNumber value = testArray.getJsonNumber(15); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonNumber to JsonString via getJsonString(int)"); JsonString value = testArray.getJsonString(4); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonString to JsonNumber via getJsonNumber(int)"); JsonNumber value = testArray.getJsonNumber(6); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonValue.TRUE to JsonNumber via getJsonNumber(int)"); JsonNumber value = testArray.getJsonNumber(1); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonArray via getJsonArray(int)"); JsonArray value = testArray.getJsonArray(0); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to JsonObject via getJsonObject(int)"); JsonObject value = testArray.getJsonObject(15); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonNumber via getInt(int)"); int value = testArray.getInt(0); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonString via getString(int)"); String value = testArray.getString(0); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to JsonString via getString(int)"); String value = testArray.getString(15); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to boolean via getBoolean(int)"); boolean value = testArray.getBoolean(0); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to boolean via getBoolean(int)"); boolean value = testArray.getBoolean(13); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonString to boolean via getBoolean(int)"); boolean value = testArray.getBoolean(6); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonNumber to boolean via getBoolean(int)"); boolean value = testArray.getBoolean(4); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getJsonNumber(int)"); int myInt = testArray.getJsonNumber(-1).intValue(); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getJsonNumber(int)"); JsonValue myJsonValue = testArray.getJsonNumber(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getJsonArray(int)"); JsonValue myJsonValue = testArray.getJsonArray(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getJsonArray(int)"); JsonValue myJsonValue = testArray.getJsonArray(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getJsonObject(int)"); JsonValue myJsonValue = testArray.getJsonObject(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getJsonObject(int)"); JsonValue myJsonValue = testArray.getJsonObject(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getJsonString(int)"); JsonValue myJsonValue = testArray.getJsonString(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getJsonString(int)"); JsonValue myJsonValue = testArray.getJsonString(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getInt(int)"); int myInt = testArray.getInt(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getInt(int)"); int myInt = testArray.getInt(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getString(int)"); String myString = testArray.getString(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getString(int)"); String myString = testArray.getString(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to getBoolean(int)"); boolean myBoolean = testArray.getBoolean(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to getBoolean(int)"); boolean myBoolean = testArray.getBoolean(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing -1 as index to isNull(int)"); boolean myBoolean = testArray.isNull(-1); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip IndexOutOfBoundsException try { LOGGER.info( "Trip IndexOutOfBoundsException passing 10000 as index to isNull(int)"); boolean myBoolean = testArray.isNull(10000); pass = false; LOGGER.warning("Failed to throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { LOGGER.info("Got expected IndexOutOfBoundsException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NumberFormatException calling add(Double.NaN) try { LOGGER.info("Trip NumberFormatException calling add(Double.NaN)"); JsonArray array = Json.createArrayBuilder().add(Double.NaN).build(); pass = false; LOGGER.warning("Failed to throw NumberFormatException"); } catch (NumberFormatException e) { LOGGER.info("Got expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NumberFormatException calling add(Double.NEGATIVE_INFINITY) try { LOGGER.info( "Trip NumberFormatException calling add(Double.NEGATIVE_INFINITY)"); JsonArray array = Json.createArrayBuilder().add(Double.NEGATIVE_INFINITY) .build(); pass = false; LOGGER.warning("Failed to throw NumberFormatException"); } catch (NumberFormatException e) { LOGGER.info("Got expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NumberFormatException calling add(Double.POSITIVE_INFINITY) try { LOGGER.info( "Trip NumberFormatException calling add(Double.POSITIVE_INFINITY)"); JsonArray array = Json.createArrayBuilder().add(Double.POSITIVE_INFINITY) .build(); pass = false; LOGGER.warning("Failed to throw NumberFormatException"); } catch (NumberFormatException e) { LOGGER.info("Got expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test for ArithmeticException try { LOGGER.info( "Trip ArithmeticException calling add(12345.12345) and attempting to extract as an exact integer value"); JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); LOGGER.info("Call JsonArray.getJsonNumber(0).intValueExact()"); int value = array.getJsonNumber(0).intValueExact(); pass = false; LOGGER.warning("Failed to throw ArithmeticException"); } catch (ArithmeticException e) { LOGGER.info("Got expected ArithmeticException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test for ArithmeticException try { LOGGER.info( "Trip ArithmeticException calling add(12345.12345) and attempting to extract as an exact long value"); JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); LOGGER.info("Call JsonArray.getJsonNumber(0).longValueExact()"); long value = array.getJsonNumber(0).longValueExact(); pass = false; LOGGER.warning("Failed to throw ArithmeticException"); } catch (ArithmeticException e) { LOGGER.info("Got expected ArithmeticException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test for ArithmeticException try { LOGGER.info( "Trip ArithmeticException calling add(12345.12345) and attempting to extract as an exact biginteger value"); JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); LOGGER.info("Call JsonArray.getJsonNumber(0).bigIntegerValueExact()"); BigInteger value = array.getJsonNumber(0).bigIntegerValueExact(); pass = false; LOGGER.warning("Failed to throw ArithmeticException"); } catch (ArithmeticException e) { LOGGER.info("Got expected ArithmeticException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Tests for UnsupportedOperationException using Collection methods to // modify JsonArray List // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.add(E) trying to modify JsonArray list which should be immutable"); testArray.add(JsonValue.FALSE); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.add(int,E) trying to modify JsonArray list which should be immutable"); testArray.add(0, JsonValue.FALSE); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.addAll(C) trying to modify JsonArray list which should be immutable"); testArray.addAll(testArray); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.addAll(int, C) trying to modify JsonArray list which should be immutable"); testArray.addAll(0, testArray); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.clear() trying to modify JsonArray list which should be immutable"); testArray.clear(); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.remove(int) trying to modify JsonArray list which should be immutable"); testArray.remove(0); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonArray.removeAll(C) trying to modify JsonArray list which should be immutable"); testArray.removeAll(testArray); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException trying to modify JsonArray list which should be immutable"); testArray.remove(JsonValue.TRUE); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonArrayExceptionTests Failed"); } /* * @testName: jsonArrayNullValueExceptionTests * * @assertion_ids: JSONP:JAVADOC:555; JSONP:JAVADOC:556; JSONP:JAVADOC:557; * JSONP:JAVADOC:558; JSONP:JAVADOC:559; JSONP:JAVADOC:560; * * @test_Strategy: Test JSON NPE exception conditions when attempting to add a * specified value that is null. */ @Test public void jsonArrayNullValueExceptionTests() { boolean pass = true; JsonArrayBuilder jab = Json.createArrayBuilder(); // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(JsonValue) when JsonValue is null."); jab.add((JsonValue) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(BigInteger) when BigInteger is null."); jab.add((BigInteger) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(JsonArrayBuilder) when JsonArrayBuilder is null."); jab.add((JsonArrayBuilder) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(JsonObjectBuilder) when JsonObjectBuilder is null."); jab.add((JsonObjectBuilder) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(BigDecimal) when BigDecimal is null."); jab.add((BigDecimal) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(String) when String is null."); jab.add((String) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonArrayNullValueExceptionTests Failed"); } /* * @testName: jsonCreateArrayBuilder11Test * * @assertion_ids: JSONP:JAVADOC:572; JSONP:JAVADOC:573; JSONP:JAVADOC:651; * JSONP:JAVADOC:652; * * @test_Strategy: Tests JsonArrayBuilder API factory methods added in JSON-P * 1.1. */ @Test public void jsonCreateArrayBuilder11Test() { ArrayBuilders createTest = new ArrayBuilders(); final TestResult result = createTest.test(); result.eval(); } /* * @testName: jsonArrayBuilder11AddTest * * @assertion_ids: JSONP:JAVADOC:589; JSONP:JAVADOC:590; JSONP:JAVADOC:591; * JSONP:JAVADOC:592; JSONP:JAVADOC:593; JSONP:JAVADOC:594; JSONP:JAVADOC:595; * JSONP:JAVADOC:596; JSONP:JAVADOC:597; JSONP:JAVADOC:598; JSONP:JAVADOC:599; * JSONP:JAVADOC:600; JSONP:JAVADOC:601; * * @test_Strategy: Tests JsonArrayBuilder API add() methods added in JSON-P * 1.1. */ @Test public void jsonArrayBuilder11AddTest() { ArrayBuildAdd addTest = new ArrayBuildAdd(); final TestResult result = addTest.test(); result.eval(); } /* * @testName: jsonArrayBuilder11SetTest * * @assertion_ids: JSONP:JAVADOC:603; JSONP:JAVADOC:604; JSONP:JAVADOC:605; * JSONP:JAVADOC:606; JSONP:JAVADOC:607; JSONP:JAVADOC:608; JSONP:JAVADOC:609; * JSONP:JAVADOC:610; JSONP:JAVADOC:611; JSONP:JAVADOC:612; JSONP:JAVADOC:613; * * @test_Strategy: Tests JsonArrayBuilder API set() methods added in JSON-P * 1.1. */ @Test public void jsonArrayBuilder11SetTest() { ArrayBuildSet setTest = new ArrayBuildSet(); final TestResult result = setTest.test(); result.eval(); } /* * @testName: jsonArrayBuilder11RemoveTest * * @assertion_ids: JSONP:JAVADOC:602; * * @test_Strategy: Tests JsonArrayBuilder API remove() methods added in JSON-P * 1.1. */ @Test public void jsonArrayBuilder11RemoveTest() { ArrayBuildRemove removeTest = new ArrayBuildRemove(); final TestResult result = removeTest.test(); result.eval(); } } jsonbuilderfactorytests/000077500000000000000000000000001451447132700332465ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/apiBuilderFactory.java000066400000000000000000000240421451447132700370310ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonbuilderfactorytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonbuilderfactorytests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for * {@link JsonBuilderFactory}. */ public class BuilderFactory { private static final Logger LOGGER = Logger.getLogger(BuilderFactory.class.getName()); /** * {@link JsonBuilderFactory} API methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonBuilderFactory API methods added in JSON-P 1.1."); LOGGER.info("JsonBuilderFactory API methods added in JSON-P 1.1."); testCreateArrayBuilderString(result); testCreateArrayBuilderInt(result); testCreateArrayBuilderBool(result); testCreateArrayBuilderObject(result); testCreateArrayBuilderNull(result); testCreateObjectBuilderString(result); testCreateObjectBuilderInt(result); testCreateObjectBuilderBool(result); testCreateObjectBuilderObject(result); testCreateObjectBuilderNull(result); return result; } /** * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on * {@code String} value. * * @param result * Test suite result. */ private void testCreateArrayBuilderString(final TestResult result) { LOGGER.info(" - createArrayBuilder(JsonArray) for String"); final JsonArray in = SimpleValues.createStringArray2(); final JsonArray check = SimpleValues.createStringArray2(); verifyCreateArrayBuilder(result, check, in); } /** * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on * {@code int} value. * * @param result * Test suite result. */ private void testCreateArrayBuilderInt(final TestResult result) { LOGGER.info(" - createArrayBuilder(JsonArray) for int"); final JsonArray in = SimpleValues.createIntArray2(); final JsonArray check = SimpleValues.createIntArray2(); verifyCreateArrayBuilder(result, check, in); } /** * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on * {@code boolean} value. * * @param result * Test suite result. */ private void testCreateArrayBuilderBool(final TestResult result) { LOGGER.info(" - createArrayBuilder(JsonArray) for boolean"); final JsonArray in = SimpleValues.createBoolArray2(); final JsonArray check = SimpleValues.createBoolArray2(); verifyCreateArrayBuilder(result, check, in); } /** * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on * {@code JsonObject} value. * * @param result * Test suite result. */ private void testCreateArrayBuilderObject(final TestResult result) { LOGGER.info(" - createArrayBuilder(JsonArray) for JsonObject"); final JsonArray in = SimpleValues.createObjectArray2(); final JsonArray check = SimpleValues.createObjectArray2(); verifyCreateArrayBuilder(result, check, in); } /** * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on * {@code null} value. Method shall throw NullPointerException. * * @param result * Test suite result. */ private void testCreateArrayBuilderNull(final TestResult result) { LOGGER.info(" - createArrayBuilder(JsonArray) for null"); final JsonArray in = null; final JsonBuilderFactory factory = Json.createBuilderFactory(null); try { factory.createArrayBuilder(in); result.fail("createArrayBuilder(JsonArray)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info( " - Expected exception for null argument: " + e.getMessage()); } catch (Throwable t) { result.fail("createObjectBuilder(JsonObject)", "Calling method with with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on * {@code String} value. * * @param result * Test suite result. */ private void testCreateObjectBuilderString(final TestResult result) { LOGGER.info(" - createObjectBuilder(JsonObject) for String"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectStr(); verifyCreateObjectBuilder(result, check, in); } /** * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on * {@code int} value. * * @param result * Test suite result. */ private void testCreateObjectBuilderInt(final TestResult result) { LOGGER.info(" - createObjectBuilder(JsonObject) for int"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectInt(); verifyCreateObjectBuilder(result, check, in); } /** * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on * {@code boolean} value. * * @param result * Test suite result. */ private void testCreateObjectBuilderBool(final TestResult result) { LOGGER.info(" - createObjectBuilder(JsonObject) for boolean"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectBool(); verifyCreateObjectBuilder(result, check, in); } /** * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on * {@code JsonObject} value. * * @param result * Test suite result. */ private void testCreateObjectBuilderObject(final TestResult result) { LOGGER.info(" - createObjectBuilder(JsonObject) for JsonObject"); final JsonObject in = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createSimpleObjectObject(); verifyCreateObjectBuilder(result, check, in); } /** * Test helper: Verify {@code JsonArrayBuilder createArrayBuilder(JsonArray)} * method on provided array. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param in * JSON array to pass to the method. */ private void verifyCreateArrayBuilder(final TestResult result, final JsonArray check, final JsonArray in) { final JsonBuilderFactory factory = Json.createBuilderFactory(null); final JsonArrayBuilder builder = factory.createArrayBuilder(in); final JsonArray out = builder.build(); if (operationFailed(check, out)) { result.fail("createArrayBuilder(JsonArray)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test helper: Verify * {@code JsonObjectBuilder createObjectBuilder(JsonObjecty)} method on * provided object. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param in * JSON object to pass to the method. */ private void verifyCreateObjectBuilder(final TestResult result, final JsonObject check, final JsonObject in) { LOGGER.info(" - IN: " + JsonAssert.valueToString(in)); final JsonBuilderFactory factory = Json.createBuilderFactory(null); final JsonObjectBuilder builder = factory.createObjectBuilder(in); final JsonObject out = builder.build(); if (operationFailed(check, out)) { result.fail("createObjectBuilder(JsonObject)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on * {@code null} value. Method shall throw NullPointerException. * * @param result * Test suite result. */ private void testCreateObjectBuilderNull(final TestResult result) { LOGGER.info(" - createObjectBuilder(JsonObject) for null"); final JsonObject in = null; final JsonBuilderFactory factory = Json.createBuilderFactory(null); try { factory.createObjectBuilder(in); result.fail("createObjectBuilder(JsonObject)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info( " - Expected exception for null argument: " + e.getMessage()); } catch (Throwable t) { result.fail("createObjectBuilder(JsonObject)", "Calling method with with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } ClientTests.java000066400000000000000000000127401451447132700363560ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonbuilderfactorytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonbuilderfactorytests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Util; import java.util.Map; import java.util.logging.Logger; import jakarta.json.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonBuilderFactoryTest1 * * @assertion_ids: JSONP:JAVADOC:445; JSONP:JAVADOC:453; JSONP:JAVADOC:454; * JSONP:JAVADOC:455; * * @test_Strategy: Tests the JsonBuilderFactory API. * * JsonBuilderFactory builderFactory = Json.createBuilderFactory(Map); JsonArray array = builderFactory.createArrayBuilder() JsonObject * object = builderFactory.createObjectBuilder() */ @Test public void jsonBuilderFactoryTest1() { boolean pass = true; try { LOGGER.info("Create JsonBuilderFactory with Map with EMPTY config"); JsonBuilderFactory builderFactory = Json .createBuilderFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = builderFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("---------------------------------------------------"); LOGGER.info("TEST CASE [JsonBuilderFactory.createArrayBuilder()]"); LOGGER.info("---------------------------------------------------"); LOGGER.info("Create JsonArrayBuilder using JsonBuilderFactory"); JsonArray expJsonArray = JSONP_Util.createJsonArrayFromString("[0,2]"); JsonArray actJsonArray = builderFactory.createArrayBuilder().add(0).add(2) .build(); if (!JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray)) pass = false; LOGGER.info("----------------------------------------------------"); LOGGER.info("TEST CASE [JsonBuilderFactory.createObjectBuilder()]"); LOGGER.info("----------------------------------------------------"); LOGGER.info("Create JsonObjectBuilder using JsonBuilderFactory"); JsonObject expJsonObject = JSONP_Util .createJsonObjectFromString("{\"foo\":\"bar\"}"); JsonObject actJsonObject = builderFactory.createObjectBuilder() .add("foo", "bar").build(); if (!JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject)) pass = false; } catch (Exception e) { fail("jsonBuilderFactoryTest1 Failed: ", e); } assertTrue(pass, "jsonBuilderFactoryTest1 Failed"); } /* * @testName: jsonBuilderFactoryTest2 * * @assertion_ids: JSONP:JAVADOC:445; JSONP:JAVADOC:455; * * @test_Strategy: Tests the JsonBuilderFactory API. * * JsonBuilderFactory builderFactory = Json.createBuilderFactory(Map); Map config = JsonBuilderFactory.getConfigInUse(); * * Test for the following 3 scenarios: 1) no supported provider property * (empty config) 2) non supported provider property */ @Test public void jsonBuilderFactoryTest2() { boolean pass = true; JsonBuilderFactory builderFactory; Map config; try { LOGGER.info("----------------------------------------------"); LOGGER.info("Test scenario1: no supported provider property"); LOGGER.info("----------------------------------------------"); LOGGER.info("Create JsonBuilderFactory with Map with EMPTY config"); builderFactory = Json.createBuilderFactory(JSONP_Util.getEmptyConfig()); config = builderFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-----------------------------------------------"); LOGGER.info("Test scenario2: non supported provider property"); LOGGER.info("-----------------------------------------------"); LOGGER.info("Create JsonBuilderFactory with Map with FOO config"); builderFactory = Json.createBuilderFactory(JSONP_Util.getFooConfig()); config = builderFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; } catch (Exception e) { fail("jsonBuilderFactoryTest2 Failed: ", e); } assertTrue(pass, "jsonBuilderFactoryTest2 Failed"); } /* * @testName: jsonBuilderFactory11Test * * @assertion_ids: JSONP:JAVADOC:614; JSONP:JAVADOC:615; * * @test_Strategy: Tests JsonBuilderFactory API methods added in JSON-P 1.1. */ @Test public void jsonBuilderFactory11Test() { BuilderFactory factoryTest = new BuilderFactory(); final TestResult result = factoryTest.test(); result.eval(); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsoncoding/000077500000000000000000000000001451447132700304675ustar00rootroot00000000000000ClientTests.java000066400000000000000000000042551451447132700335220ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsoncoding/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsoncoding; import jakarta.json.Json; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.*; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonEncodeTest * * @assertion_ids: JSONP:JAVADOC:681; JSONP:JAVADOC:682; * * @test_Strategy: Encode and decode Json Pointer as defined by RFC 6901 */ @Test public void jsonEncodeTest() { String DECODED = "/a/~b/c"; String ENCODED = "~1a~1~0b~1c"; StringBuilder error = new StringBuilder(); LOGGER.info("----------------------------------------------"); LOGGER.info("Test encode " + DECODED); LOGGER.info("----------------------------------------------"); String encoded = Json.encodePointer(DECODED); if (!ENCODED.equals(encoded)) error.append("The pointer ").append(DECODED) .append(" has been encoded as ").append(encoded).append('\n'); LOGGER.info("----------------------------------------------"); LOGGER.info("Test decode " + ENCODED); String decoded = Json.decodePointer(ENCODED); if (!DECODED.equals(decoded)) error.append("The pointer ").append(ENCODED) .append(" has been decoded as ").append(decoded).append('\n'); assertEquals(0, error.length(), error.toString()); LOGGER.info("----------------------------------------------"); } } jsongeneratorfactorytests/000077500000000000000000000000001451447132700336065ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/apiClientTests.java000066400000000000000000000305511451447132700367160ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsongeneratorfactorytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsongeneratorfactorytests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import jakarta.json.stream.*; import java.io.*; import java.util.Map; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonGeneratorFactoryTest1 * * @assertion_ids: JSONP:JAVADOC:162; JSONP:JAVADOC:416; JSONP:JAVADOC:427; * * @test_Strategy: Tests the JsonGeneratorFactory API. * * JsonGeneratorFactory generatorFactory = * Json.createGeneratorFactory(Map); JsonGenerator generator1 = * generatorFactory.createGenerator(Writer) JsonGenerator generator2 = * generatorFactory.createGenerator(Writer) */ @Test public void jsonGeneratorFactoryTest1() { boolean pass = true; JsonGenerator generator1 = null; JsonGenerator generator2 = null; String expString; String actString; try { LOGGER.info( "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); JsonGeneratorFactory generatorFactory = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); LOGGER.info("Checking factory configuration properties"); Map config = generatorFactory.getConfigInUse(); String[] props = { JsonGenerator.PRETTY_PRINTING, }; if (!JSONP_Util.doConfigCheck(config, 1, props)) pass = false; LOGGER.info("--------------------------------------------------------"); LOGGER.info("TEST CASE [JsonGeneratorFactory.createGenerator(Writer)]"); LOGGER.info("--------------------------------------------------------"); LOGGER.info("Create 1st JsonGenerator using JsonGeneratorFactory"); StringWriter sWriter1 = new StringWriter(); generator1 = generatorFactory.createGenerator(sWriter1); if (generator1 == null) { LOGGER.warning("GeneratorFactory failed to create generator1"); pass = false; } else { generator1.writeStartObject().writeEnd(); generator1.close(); } LOGGER.info("sWriter1=" + sWriter1.toString()); expString = "{}"; actString = JSONP_Util.removeWhitespace(sWriter1.toString()); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; LOGGER.info("Create 2nd JsonGenerator using JsonGeneratorFactory"); StringWriter sWriter2 = new StringWriter(); generator2 = generatorFactory.createGenerator(sWriter2); if (generator2 == null) { LOGGER.warning("GeneratorFactory failed to create generator2"); pass = false; } else { generator2.writeStartArray().writeEnd(); generator2.close(); } LOGGER.info("sWriter2=" + sWriter2.toString()); expString = "[]"; actString = JSONP_Util.removeWhitespace(sWriter2.toString()); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; } catch (Exception e) { fail("jsonGeneratorFactoryTest1 Failed: ", e); } assertTrue(pass, "jsonGeneratorFactoryTest1 Failed"); } /* * @testName: jsonGeneratorFactoryTest2 * * @assertion_ids: JSONP:JAVADOC:163; JSONP:JAVADOC:416; JSONP:JAVADOC:427; * * @test_Strategy: Tests the JsonGeneratorFactory API. * * JsonGeneratorFactory generatorFactory = * Json.createGeneratorFactory(Map); JsonGenerator generator1 = * generatorFactory.createGenerator(OutputStream, Charset) JsonGenerator * generator2 = generatorFactory.createGenerator(OutputStream, Charset) * * Create generator with both UTF-8 and UTF-16BE. */ @Test public void jsonGeneratorFactoryTest2() { boolean pass = true; JsonGenerator generator1 = null; JsonGenerator generator2 = null; String expString, actString; try { LOGGER.info( "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); JsonGeneratorFactory generatorFactory = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); LOGGER.info("Checking factory configuration properties"); Map config = generatorFactory.getConfigInUse(); String[] props = { JsonGenerator.PRETTY_PRINTING, }; if (!JSONP_Util.doConfigCheck(config, 1, props)) pass = false; LOGGER.info( "-----------------------------------------------------------------------"); LOGGER.info( "TEST CASE [JsonGeneratorFactory.createGenerator(OutputStream, Charset)]"); LOGGER.info( "-----------------------------------------------------------------------"); LOGGER.info( "Create 1st JsonGenerator using JsonGeneratorFactory with UTF-8 encoding"); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); generator1 = generatorFactory.createGenerator(baos1, JSONP_Util.UTF_8); if (generator1 == null) { LOGGER.warning("GeneratorFactory failed to create generator1"); pass = false; } else { generator1.writeStartObject().writeEnd(); generator1.close(); } LOGGER.info("baos1=" + baos1.toString("UTF-8")); expString = "{}"; actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; LOGGER.info( "Create 2nd JsonGenerator using JsonGeneratorFactory with UTF-16BE encoding"); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); generator2 = generatorFactory.createGenerator(baos2, JSONP_Util.UTF_16BE); if (generator2 == null) { LOGGER.warning("GeneratorFactory failed to create generator2"); pass = false; } else { generator2.writeStartArray().writeEnd(); generator2.close(); } LOGGER.info("baos2=" + baos2.toString("UTF-16BE")); expString = "[]"; actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-16BE")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; } catch (Exception e) { fail("jsonGeneratorFactoryTest2 Failed: ", e); } assertTrue(pass, "jsonGeneratorFactoryTest2 Failed"); } /* * @testName: jsonGeneratorFactoryTest3 * * @assertion_ids: JSONP:JAVADOC:200; JSONP:JAVADOC:416; JSONP:JAVADOC:427; * * @test_Strategy: Tests the JsonGeneratorFactory API. * * JsonGeneratorFactory generatorFactory = * Json.createGeneratorFactory(Map); JsonGenerator generator1 = * generatorFactory.createGenerator(OutputStream) JsonGenerator generator2 = * generatorFactory.createGenerator(OutputStream) */ @Test public void jsonGeneratorFactoryTest3() { boolean pass = true; JsonGenerator generator1 = null; JsonGenerator generator2 = null; String expString; String actString; try { LOGGER.info( "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); JsonGeneratorFactory generatorFactory = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); LOGGER.info("Checking factory configuration properties"); Map config = generatorFactory.getConfigInUse(); String[] props = { JsonGenerator.PRETTY_PRINTING, }; if (!JSONP_Util.doConfigCheck(config, 1, props)) pass = false; LOGGER.info( "-----------------------------------------------------------------"); LOGGER.info( "TEST CASE [JsonGeneratorFactory.createGenerator(OutputStream os)]"); LOGGER.info( "-----------------------------------------------------------------"); LOGGER.info("Create 1st JsonGenerator using JsonGeneratorFactory"); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); generator1 = generatorFactory.createGenerator(baos1); if (generator1 == null) { LOGGER.warning("GeneratorFactory failed to create generator1"); pass = false; } else { generator1.writeStartObject().writeEnd(); generator1.close(); } LOGGER.info("baos1=" + baos1.toString("UTF-8")); expString = "{}"; actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; LOGGER.info("Create 2nd JsonGenerator using JsonGeneratorFactory"); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); generator2 = generatorFactory.createGenerator(baos2); if (generator2 == null) { LOGGER.warning("GeneratorFactory failed to create generator2"); pass = false; } else { generator2.writeStartArray().writeEnd(); generator2.close(); } LOGGER.info("baos2=" + baos2.toString("UTF-8")); expString = "[]"; actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; } catch (Exception e) { fail("jsonGeneratorFactoryTest3 Failed: ", e); } assertTrue(pass, "jsonGeneratorFactoryTest3 Failed"); } /* * @testName: jsonGeneratorFactoryTest4 * * @assertion_ids: JSONP:JAVADOC:416; JSONP:JAVADOC:427; * * @test_Strategy: Tests the JsonGeneratorFactory API. * * JsonGeneratorFactory generatorFactory = * Json.createGeneratorFactory(Map); Map config = * JsonGeneratorFactory.getConfigInUse(); * * Test for the following 3 scenarios: 1) no supported provider property * (empty config) 2) supported provider property 3) supported and non * supported provider property */ @Test public void jsonGeneratorFactoryTest4() { boolean pass = true; JsonGeneratorFactory generatorFactory; Map config; try { LOGGER.info("----------------------------------------------"); LOGGER.info("Test scenario1: no supported provider property"); LOGGER.info("----------------------------------------------"); LOGGER.info( "Create JsonGeneratorFactory with Map with EMPTY config"); generatorFactory = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()); config = generatorFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-------------------------------------------"); LOGGER.info("Test scenario2: supported provider property"); LOGGER.info("-------------------------------------------"); LOGGER.info( "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); generatorFactory = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); config = generatorFactory.getConfigInUse(); String[] props = { JsonGenerator.PRETTY_PRINTING, }; if (!JSONP_Util.doConfigCheck(config, 1, props)) pass = false; LOGGER.info("-------------------------------------------------------------"); LOGGER.info("Test scenario3: supported and non supported provider property"); LOGGER.info("-------------------------------------------------------------"); LOGGER.info("Create JsonGeneratorFactory with Map with all config"); generatorFactory = Json.createGeneratorFactory(JSONP_Util.getAllConfig()); config = generatorFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 1, props)) pass = false; } catch (Exception e) { fail("jsonGeneratorFactoryTest4 Failed: ", e); } assertTrue(pass, "jsonGeneratorFactoryTest4 Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsongeneratortests/000077500000000000000000000000001451447132700322755ustar00rootroot00000000000000ClientTests.java000066400000000000000000002710341451447132700353310ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsongeneratortests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsongeneratortests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Util; import ee.jakarta.tck.jsonp.common.MyBufferedWriter; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.logging.Logger; import jakarta.json.*; import jakarta.json.stream.*; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* private Utility methods */ /********************************************************************************* * generateSimpleJsonObject *********************************************************************************/ private void generateSimpleJsonObject(JsonGenerator generator) { try { generator.writeStartObject().writeStartObject("object") .write("string", "string").write("number", 1) .write("true", JsonValue.TRUE).write("false", JsonValue.FALSE) .write("null", JsonValue.NULL).writeEnd().writeStartArray("array") .write("string").write(1).write(JsonValue.TRUE).write(JsonValue.FALSE) .write(JsonValue.NULL).writeEnd().writeEnd(); generator.close(); } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); } } /********************************************************************************* * generateSimpleJsonArray *********************************************************************************/ private void generateSimpleJsonArray(JsonGenerator generator) { try { generator.writeStartArray().writeStartObject().write("string", "string") .write("number", 1).write("true", JsonValue.TRUE) .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) .writeEnd().writeStartArray().write("string").write(1) .write(JsonValue.TRUE).write(JsonValue.FALSE).write(JsonValue.NULL) .writeEnd().writeEnd(); generator.close(); } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); } } /********************************************************************************* * generateJsonObject *********************************************************************************/ private String generateJsonObject() { try { LOGGER.info("Generate a JsonObject"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("emptyString", "") .writeStartArray("emptyArray").writeEnd() .writeStartObject("emptyObject").writeEnd().write("string", "string") .write("intMin", Integer.MIN_VALUE).write("intMax", Integer.MAX_VALUE) .write("longMin", Long.MIN_VALUE).write("longMax", Long.MAX_VALUE) .write("doubleMin", Double.MIN_VALUE) .write("doubleMax", Double.MAX_VALUE) .write("bigInteger", new BigInteger(Integer.toString(Integer.MAX_VALUE))) .write("bigDecimal", BigDecimal.valueOf(Integer.MIN_VALUE)) .write("true", JsonValue.TRUE).write("false", JsonValue.FALSE) .write("null", JsonValue.NULL).writeStartObject("object") .write("emptyString", "").writeStartArray("emptyArray").writeEnd() .writeStartObject("emptyObject").writeEnd().write("string", "string") .write("number", 100).write("true", true).write("false", false) .writeNull("null").writeStartObject("object").write("name", "value") .write("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) .write("arrayFooBar", JSONP_Util.buildJsonArrayFooBar()).writeEnd() .writeStartArray("array").write("one").write("two") .write(JSONP_Util.buildJsonObjectFooBar()) .write(JSONP_Util.buildJsonArrayFooBar()).writeEnd().writeEnd() .writeStartArray("array").write("string").write(Integer.MAX_VALUE) .write(Long.MAX_VALUE).write(Double.MAX_VALUE) .write(new BigInteger(Integer.toString(Integer.MAX_VALUE))) .write(JsonValue.TRUE).write(JsonValue.FALSE).write(JsonValue.NULL) .writeStartObject().write("name", "value").writeEnd() .writeStartArray().write("one").write("two").writeEnd().writeEnd() .write("asciiChars", "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") .writeEnd(); generator.close(); return sWriter.toString(); } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); return null; } } /********************************************************************************* * buildJsonObject *********************************************************************************/ private JsonObject buildJsonObject() { try { LOGGER.info("Build a JsonObject"); JsonObject jsonObject = Json.createObjectBuilder().add("emptyString", "") .add("emptyArray", Json.createArrayBuilder()) .add("emptyObject", Json.createObjectBuilder()) .add("string", "string").add("intMin", Integer.MIN_VALUE) .add("intMax", Integer.MAX_VALUE).add("longMin", Long.MIN_VALUE) .add("longMax", Long.MAX_VALUE).add("doubleMin", Double.MIN_VALUE) .add("doubleMax", Double.MAX_VALUE) .add("bigInteger", new BigInteger(Integer.toString(Integer.MAX_VALUE))) .add("bigDecimal", BigDecimal.valueOf(Integer.MIN_VALUE)) .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) .add("null", JsonValue.NULL) .add("object", Json.createObjectBuilder().add("emptyString", "") .add("emptyArray", Json.createArrayBuilder()) .add("emptyObject", Json.createObjectBuilder()) .add("string", "string").add("number", 100) .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) .add("null", JsonValue.NULL) .add("object", Json.createObjectBuilder().add("name", "value") .add("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) .add("arrayFooBar", JSONP_Util.buildJsonArrayFooBar())) .add("array", Json.createArrayBuilder().add("one").add("two") .add(JSONP_Util.buildJsonObjectFooBar()) .add(JSONP_Util.buildJsonArrayFooBar()))) .add("array", Json.createArrayBuilder().add("string").add(Integer.MAX_VALUE) .add(Long.MAX_VALUE).add(Double.MAX_VALUE) .add(new BigInteger(Integer.toString(Integer.MAX_VALUE))) .add(JsonValue.TRUE).add(JsonValue.FALSE).add(JsonValue.NULL) .add(Json.createObjectBuilder().add("name", "value")) .add(Json.createArrayBuilder().add("one").add("two"))) .add("asciiChars", "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") .build(); return jsonObject; } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); return null; } } /********************************************************************************* * generateJsonArray *********************************************************************************/ private String generateJsonArray() { try { LOGGER.info("Generate a JsonArray"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("").writeStartArray().writeEnd() .writeStartObject().writeEnd().write("string") .write(Integer.MIN_VALUE).write(Integer.MAX_VALUE) .write(Long.MIN_VALUE).write(Long.MAX_VALUE).write(Double.MIN_VALUE) .write(Double.MAX_VALUE) .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) .write(BigDecimal.valueOf(Integer.MIN_VALUE)).write(JsonValue.TRUE) .write(JsonValue.FALSE).write(JsonValue.NULL).writeStartObject() .write("emptyString", "").writeStartArray("emptyArray").writeEnd() .writeStartObject("emptyObject").writeEnd().write("string", "string") .write("number", 100).write("true", JsonValue.TRUE) .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) .writeStartObject("object").write("name", "value") .write("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) .write("arrayFooBar", JSONP_Util.buildJsonArrayFooBar()).writeEnd() .writeStartArray("array").write("one").write("two") .write(JSONP_Util.buildJsonObjectFooBar()) .write(JSONP_Util.buildJsonArrayFooBar()).writeEnd().writeEnd() .writeStartArray().write("string").write(Integer.MAX_VALUE) .write(Long.MAX_VALUE).write(Double.MAX_VALUE) .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) .write(true).write(false).writeNull().writeStartObject() .write("name", "value").writeEnd().writeStartArray().write("one") .write("two").writeEnd().writeEnd() .write( "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") .writeEnd(); generator.close(); return sWriter.toString(); } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); return null; } } /********************************************************************************* * buildJsonArray *********************************************************************************/ private JsonArray buildJsonArray() { try { LOGGER.info("Build a JsonArray"); JsonArray jsonArray = Json.createArrayBuilder().add("") .add(Json.createArrayBuilder()).add(Json.createObjectBuilder()) .add("string").add(Integer.MIN_VALUE).add(Integer.MAX_VALUE) .add(Long.MIN_VALUE).add(Long.MAX_VALUE).add(Double.MIN_VALUE) .add(Double.MAX_VALUE) .add(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) .add(BigDecimal.valueOf(Integer.MIN_VALUE)).add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL) .add(Json.createObjectBuilder().add("emptyString", "") .add("emptyArray", Json.createArrayBuilder()) .add("emptyObject", Json.createObjectBuilder()) .add("string", "string").add("number", 100) .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) .add("null", JsonValue.NULL) .add("object", Json.createObjectBuilder().add("name", "value") .add("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) .add("arrayFooBar", JSONP_Util.buildJsonArrayFooBar())) .add("array", Json.createArrayBuilder().add("one").add("two") .add(JSONP_Util.buildJsonObjectFooBar()) .add(JSONP_Util.buildJsonArrayFooBar()))) .add(Json.createArrayBuilder().add("string").add(Integer.MAX_VALUE) .add(Long.MAX_VALUE).add(Double.MAX_VALUE) .add(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) .add(JsonValue.TRUE).add(JsonValue.FALSE).add(JsonValue.NULL) .add(Json.createObjectBuilder().add("name", "value")) .add(Json.createArrayBuilder().add("one").add("two"))) .add( "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") .build(); return jsonArray; } catch (Exception e) { LOGGER.warning("Exception occurred: " + e); return null; } } /* Tests */ /* * @testName: jsonGeneratorObjectTest1 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; * JSONP:JAVADOC:289; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * The output is written to a writer, read back as a string and filtered to * remove whitespace and is compared against an expected string. * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } */ @Test public void jsonGeneratorObjectTest1() { try { StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generateSimpleJsonObject(generator); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectTest1 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectTest1 Failed: ", e); } } /* * @testName: jsonGeneratorObjectTest2 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:168; * JSONP:JAVADOC:289; JSONP:JAVADOC:307; JSONP:JAVADOC:327; JSONP:JAVADOC:339; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * The output is written to a writer, read back as a string and filtered to * remove whitespace and is compared against an expected string. * * { "emptyString":"", "emptyArray":[], "emptyObject":{}, "string":"string","+ * "intMin":Integer.MIN_VALUE, "intMax":Integer.MAX_VALUE, * "longMin":Long.MIN_VALUE, "longMax":Long.MAX_VALUE, "true":true, * "false":false, "null":null, "object": { "emptyString":"", "emptyArray":[], * "emptyObject":{}, "string":"string", "number":100, "true":true, * "false":false, "null":null, "object":{"name":"value"} "array":["one","two"] * }, "array": [ "string", Integer.MAX_VALUE, Long.MAX_VALUE, true, false, * null, {"name":"value"}, ["one","two"] ], * "asciiChars":"\"\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" * } */ @Test public void jsonGeneratorObjectTest2() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json.createGenerator(baos); generator.writeStartObject().write("emptyString", "") .writeStartArray("emptyArray").writeEnd() .writeStartObject("emptyObject").writeEnd().write("string", "string") .write("intMin", Integer.MIN_VALUE).write("intMax", Integer.MAX_VALUE) .write("longMin", Long.MIN_VALUE).write("longMax", Long.MAX_VALUE) .write("true", JsonValue.TRUE).write("false", JsonValue.FALSE) .write("null", JsonValue.NULL).writeStartObject("object") .write("emptyString", "").writeStartArray("emptyArray").writeEnd() .writeStartObject("emptyObject").writeEnd().write("string", "string") .write("number", 100).write("true", JsonValue.TRUE) .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) .writeStartObject("object").write("name", "value").writeEnd() .writeStartArray("array").write("one").write("two").writeEnd() .writeEnd().writeStartArray("array").write("string") .write(Integer.MAX_VALUE).write(Long.MAX_VALUE).write(JsonValue.TRUE) .write(JsonValue.FALSE).write(JsonValue.NULL).writeStartObject() .write("name", "value").writeEnd().writeStartArray().write("one") .write("two").writeEnd().writeEnd() .write("asciiChars", "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") .writeEnd(); generator.close(); LOGGER.info("Dump of string: " + baos.toString("UTF-8")); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"emptyString\":\"\",\"emptyArray\":[],\"emptyObject\":{},\"string\":\"string\"," + "\"intMin\":" + Integer.MIN_VALUE + "," + "\"intMax\":" + Integer.MAX_VALUE + "," + "\"longMin\":" + Long.MIN_VALUE + "," + "\"longMax\":" + Long.MAX_VALUE + "," + "\"true\":true,\"false\":false,\"null\":null,\"object\":{\"emptyString\":\"\",\"emptyArray\":[]," + "\"emptyObject\":{},\"string\":\"string\",\"number\":100,\"true\":true,\"false\":false," + "\"null\":null,\"object\":{\"name\":\"value\"}," + "\"array\":[\"one\",\"two\"]},\"array\":[\"string\"," + Integer.MAX_VALUE + "," + Long.MAX_VALUE + ",true,false,null," + "{\"name\":\"value\"},[\"one\",\"two\"]],\"asciiChars\":" + "\"\\\\\\\"\\\\\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\"" + "}"; LOGGER.info("Read the JSON text back from OutputStream removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectTest2 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectTest2 Failed: ", e); } } /* * @testName: jsonGeneratorObjectTest3 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; * JSONP:JAVADOC:289; JSONP:JAVADOC:307; JSONP:JAVADOC:327; JSONP:JAVADOC:339; * JSONP:JAVADOC:301; JSONP:JAVADOC:310; JSONP:JAVADOC:329; JSONP:JAVADOC:323; * JSONP:JAVADOC:298; JSONP:JAVADOC:314; JSONP:JAVADOC:334; * * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * The output is written to a writer, read back as a JsonObject and compared * against an expected JsonObject. * * { "emptyString":"", "emptyArray":[], "emptyObject":{}, "string":"string","+ * "intMin":Integer.MIN_VALUE, "intMax":Integer.MAX_VALUE, * "longMin":Long.MIN_VALUE, "longMax":Long.MAX_VALUE, * "doubleMin":Double.MIN_VALUE, "doubleMax":Double.MAX_VALUE, * "bigInteger":Integer.MAX_VALUE, "bigDecimal":Integer.MIN_VALUE, * "true":true, "false":false, "null":null, "object": { "emptyString":"", * "emptyArray":[], "emptyObject":{}, "string":"string", "number":100, * "true":true, "false":false, "null":null, * "object":{"name":"value",{"foo":"bar"}}, * "array":["one","two",["foo","bar"]] }, "array": [ "string", * Integer.MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE, Integer.MAX_VALUE * true, false, null, {"name":"value"}, ["one","two"] ], * "asciiChars":"\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" * } */ @Test public void jsonGeneratorObjectTest3() { try { JsonObject expJsonObject = buildJsonObject(); String jsonText = generateJsonObject(); JsonReader reader = Json.createReader(new StringReader(jsonText)); JsonObject actJsonObject = (JsonObject) reader.read(); // Do comparison LOGGER.info("Compare expJsonObject and actJsonObject for equality"); assertTrue( JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject), "jsonGeneratorObjectTest3 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectTest3 Failed: ", e); } } /* * @testName: jsonGeneratorObjectTest4 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:416; * JSONP:JAVADOC:289; JSONP:JAVADOC:163; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * Encoding is done in UTF-16BE. The output is written to an OutputStream as * UTF-16BE encoding, read back as a string using UTF-16BE encoding and * filtered to remove whitespace and is compared against an expected string. * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } Tests the following API * call: * * JsonGenerator generator = * Json.createGeneratorFactory(Map).createGenerator(OutputStream, * Charset); */ @Test public void jsonGeneratorObjectTest4() { try { LOGGER.info("Create generator output in UTF-16BE encoding."); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_16BE); generateSimpleJsonObject(generator); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; LOGGER.info( "Read the JSON text back encoding from OutputStream using UTF-16BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectTest4 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectTest4 Failed: ", e); } } /* * @testName: jsonGeneratorObjectTest5 * * @assertion_ids: JSONP:JAVADOC:131; JSONP:JAVADOC:341; JSONP:JAVADOC:295; * JSONP:JAVADOC:289; * * @test_Strategy: Test generation of object data with multiple unicode chars * in data. The output is written to a writer, read back using a reader as a * JsonObject and extracts the JsonString value out and compares it against * the expected JsonString value. * * Generate the following object of unicode char(s): * * {"unicodechars":"\u0000\u000f\u001f\u00ff\uff00\uffff"} */ @Test public void jsonGeneratorObjectTest5() { JsonReader reader = null; String expUnicodeChars = "\u0000\u000f\u001f\u00ff\uff00\uffff"; try { StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject() .write("unicodechars", "\u0000\u000f\u001f\u00ff\uff00\uffff") .writeEnd(); generator.close(); sWriter.close(); LOGGER.info("Testing read of " + sWriter.toString()); reader = Json.createReader(new StringReader(sWriter.toString())); JsonObject jsonObject = reader.readObject(); String actUnicodeChars = jsonObject.getJsonString("unicodechars") .getString(); reader.close(); LOGGER.info("actUnicodeChars=" + actUnicodeChars); assertTrue(JSONP_Util.assertEquals(expUnicodeChars, actUnicodeChars), "jsonGeneratorObjectTest5 Failed"); } catch (Exception e) { fail("Exception occurred: ", e); } } /* * @testName: jsonGeneratorArrayTest1 * * @assertion_ids: JSONP:JAVADOC:339; JSONP:JAVADOC:341; JSONP:JAVADOC:295; * JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; JSONP:JAVADOC:325; * JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; JSONP:JAVADOC:289; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. * The output is written to a writer, read back as a string and filtered to * remove whitespace and is compared against an expected string. * * [ {"string":"string","number":1,"true":true,"false":false,"null":null}, * ["string", 1, true, false, null] ] * */ @Test public void jsonGeneratorArrayTest1() { try { StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generateSimpleJsonArray(generator); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "[{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},[\"string\",1,true,false,null]]"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorArrayTest1 Failed"); } catch (Exception e) { fail("jsonGeneratorArrayTest1 Failed: ", e); } } /* * @testName: jsonGeneratorArrayTest2 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:168; * JSONP:JAVADOC:289; JSONP:JAVADOC:327; JSONP:JAVADOC:339; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. * The output is written to a writer, read back as a string and filtered to * remove whitespace and is compared against an expected string. * * [ "", [], {}, "string", Integer.MIN_VALUE, Integer.MAX_VALUE, * Long.MIN_VALUE, Long.MAX_VALUE, true, false, null, { "emptyString":"", * "emptyArray":[], "emptyObject":{}, "string":"string", "number":100, * "true":true, "false":false, "null":null, "object":{"name":"value"}, * "array":["one","two"] }, [ "string", Integer.MAX_VALUE, Long.MAX_VALUE, * true, false, null, {"name":"value"}, ["one","two"] ], * "\"\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" * ] */ @Test public void jsonGeneratorArrayTest2() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json.createGenerator(baos); generator.writeStartArray().write("").writeStartArray().writeEnd() .writeStartObject().writeEnd().write("string") .write(Integer.MIN_VALUE).write(Integer.MAX_VALUE) .write(Long.MIN_VALUE).write(Long.MAX_VALUE).write(JsonValue.TRUE) .write(JsonValue.FALSE).write(JsonValue.NULL).writeStartObject() .write("emptyString", "").writeStartArray("emptyArray").writeEnd() .writeStartObject("emptyObject").writeEnd().write("string", "string") .write("number", 100).write("true", JsonValue.TRUE) .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) .writeStartObject("object").write("name", "value").writeEnd() .writeStartArray("array").write("one").write("two").writeEnd() .writeEnd().writeStartArray().write("string").write(Integer.MAX_VALUE) .write(Long.MAX_VALUE).write(JsonValue.TRUE).write(JsonValue.FALSE) .write(JsonValue.NULL).writeStartObject().write("name", "value") .writeEnd().writeStartArray().write("one").write("two").writeEnd() .writeEnd() .write( "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") .writeEnd(); generator.close(); LOGGER.info("Dump of string: " + baos.toString("UTF-8")); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "[\"\",[],{},\"string\"," + Integer.MIN_VALUE + "," + Integer.MAX_VALUE + "," + Long.MIN_VALUE + "," + Long.MAX_VALUE + "," + "true,false,null,{\"emptyString\":\"\",\"emptyArray\":[]," + "\"emptyObject\":{},\"string\":\"string\",\"number\":100,\"true\":true,\"false\":false," + "\"null\":null,\"object\":{\"name\":\"value\"}," + "\"array\":[\"one\",\"two\"]},[\"string\"," + Integer.MAX_VALUE + "," + Long.MAX_VALUE + ",true,false,null," + "{\"name\":\"value\"},[\"one\",\"two\"]]," + "\"\\\\\\\"\\\\\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\"" + "]"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorArrayTest2 Failed"); } catch (Exception e) { fail("jsonGeneratorArrayTest2 Failed: ", e); } } /* * @testName: jsonGeneratorArrayTest3 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; * JSONP:JAVADOC:289; JSONP:JAVADOC:327; JSONP:JAVADOC:339; JSONP:JAVADOC:329; * JSONP:JAVADOC:321; JSONP:JAVADOC:323; JSONP:JAVADOC:332; JSONP:JAVADOC:337; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. * The output is written to a writer, read back as a JsonArray and compared * against an expected JsonArray. * * [ "", [], {}, "string", Integer.MIN_VALUE, Integer.MAX_VALUE, * Long.MIN_VALUE, Long.MAX_VALUE, Double.MIN_VALUE, Double.MAX_VALUE, * Integer.MAX_VALUE, Integer.MIN_VALUE, true, false, null, { * "emptyString":"", "emptyArray":[], "emptyObject":{}, "string":"string", * "number":100, "true":true, "false":false, "null":null, * "object":{"name":"value",{"foo":"bar"}}, * "array":["one","two",["foo","bar"]] }, [ "string", Integer.MAX_VALUE, * Long.MAX_VALUE, Double.MAX_VALUE, Integer.MAX_VALUE true, false, null, * {"name":"value"}, ["one","two"] ], * "\"\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" * ] */ @Test public void jsonGeneratorArrayTest3() { try { JsonArray expJsonArray = buildJsonArray(); String jsonText = generateJsonArray(); LOGGER.info("generator json text: " + jsonText); JsonReader reader = Json.createReader(new StringReader(jsonText)); JsonArray actJsonArray = (JsonArray) reader.read(); // Do comparison LOGGER.info("Compare expJsonArray and actJsonArray for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray), "jsonGeneratorArrayTest3 Failed"); } catch (Exception e) { fail("jsonGeneratorArrayTest3 Failed: ", e); } } /* * @testName: jsonGeneratorArrayTest4 * * @assertion_ids: JSONP:JAVADOC:339; JSONP:JAVADOC:341; JSONP:JAVADOC:115; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:163; JSONP:JAVADOC:289; * JSONP:JAVADOC:416; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. * Encoding is done in UTF-16BE. The output is written to an OutputStream as * UTF-16BE encoding, read back as a string using UTF-16BE encoding and * filtered to remove whitespace and is compared against an expected string. * * [ {"string":"string","number":1,"true":true,"false":false,"null":null}, * ["string", 1, true, false, null] ] * */ @Test public void jsonGeneratorArrayTest4() { try { LOGGER.info("Create generator output in UTF-16BE encoding."); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_16BE); generateSimpleJsonArray(generator); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "[{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},[\"string\",1,true,false,null]]"; LOGGER.info( "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorArrayTest4 Failed"); } catch (Exception e) { fail("jsonGeneratorArrayTest4 Failed: ", e); } } /* * @testName: jsonGeneratorArrayTest5 * * @assertion_ids: JSONP:JAVADOC:131; JSONP:JAVADOC:339; JSONP:JAVADOC:319; * JSONP:JAVADOC:289; * * @test_Strategy: Test generation of array data with multiple unicode chars * in data. The output is written to a writer, read back using a reader as a * JsonArray and extracts the JsonString value out and compares it against the * expected JsonString value. * * Generate the following array of unicode char(s): * * ["\u0000\u000f\u001f\u00ff\uff00\uffff"] */ @Test public void jsonGeneratorArrayTest5() { JsonReader reader = null; String expUnicodeChars = "\u0000\u000f\u001f\u00ff\uff00\uffff"; try { StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("\u0000\u000f\u001f\u00ff\uff00\uffff") .writeEnd(); generator.close(); sWriter.close(); LOGGER.info("Testing read of " + sWriter.toString()); reader = Json.createReader(new StringReader(sWriter.toString())); JsonArray jsonArray = reader.readArray(); String actUnicodeChars = jsonArray.getJsonString(0).getString(); reader.close(); LOGGER.info("actUnicodeChars=" + actUnicodeChars); assertTrue(JSONP_Util.assertEquals(expUnicodeChars, actUnicodeChars), "jsonGeneratorArrayTest5 Failed"); } catch (Exception e) { fail("JsonGeneratorArrayTest5 Failed. Exception occurred:", e); } } /* * @testName: jsonGeneratorObjectConfigTest1 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:289; * JSONP:JAVADOC:162; JSONP:JAVADOC:416; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * This test uses the configuration feature to PRETTY PRINT. The output is * written to a Writer, read back as a string and filtered to remove * whitespace and is compared against an expected string. * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } Tests following API call: * * JsonGenerator generator = Json.createGeneratorFactory(Map).createGenerator(Writer) */ @Test public void jsonGeneratorObjectConfigTest1() { try { LOGGER.info("Create JsonGenerator using configuration with PRETTY_PRINTING"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()) .createGenerator(sWriter); generateSimpleJsonObject(generator); // Dump JsonText output with PRETTY_PRINTING feature LOGGER.info("PRETTY_PRINTING feature\n" + sWriter.toString()); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectConfigTest1 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectConfigTest1 Failed: ", e); } } /* * @testName: jsonGeneratorObjectConfigTest2 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:289; * JSONP:JAVADOC:200; JSONP:JAVADOC:416; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * This test uses the configuration feature to PRETTY PRINT. The output is * written to a OutputStream, read back as a string and filtered to remove * whitespace and is compared against an expected string. * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } Tests following API call: * * JsonGenerator generator = Json.createGeneratorFactory(Map).createGenerator(OutputStream) */ @Test public void jsonGeneratorObjectConfigTest2() { try { LOGGER.info("Create JsonGenerator using configuration with PRETTY_PRINTING"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()) .createGenerator(baos); generateSimpleJsonObject(generator); // Dump JsonText output with PRETTY_PRINTING feature LOGGER.info("PRETTY_PRINTING feature\n" + baos.toString("UTF-8")); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectConfigTest2 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectConfigTest2 Failed: ", e); } } /* * @testName: jsonGeneratorObjectEncodingTest1 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:163; * JSONP:JAVADOC:289; JSONP:JAVADOC:416; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * The output is written to an OutputStream using UTF-8 encoding, read back as * a string and filtered to remove whitespace and is compared against an * expected string. * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } */ @Test public void jsonGeneratorObjectEncodingTest1() { try { LOGGER.info("Create JsonGenerator using UTF-8 encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_8); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generator Output=" + baos.toString("UTF-8")); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; LOGGER.info( "Read the JSON text back from OutputStream using UTF-8 encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectEncodingTest1 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectEncodingTest1 Failed: ", e); } } /* * @testName: jsonGeneratorObjectEncodingTest2 * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:289; * JSONP:JAVADOC:163; JSONP:JAVADOC:416; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * This test uses the configuration feature to PRETTY PRINT. The output is * written to an OutputStream using UTF-16BE encoding, read back as a string * and filtered to remove whitespace and is compared against an expected * string. * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } Tests the following API * call: * * JsonGenerator generator = Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset); */ @Test public void jsonGeneratorObjectEncodingTest2() { try { LOGGER.info( "Create JsonGenerator using configuration with PRETTY_PRINTING using UTF-16BE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()) .createGenerator(baos, JSONP_Util.UTF_16BE); generateSimpleJsonObject(generator); // Dump JsonText output with PRETTY_PRINTING feature LOGGER.info("PRETTY_PRINTING feature\n" + baos.toString("UTF-16BE")); // Do comparison LOGGER.info("Create expected JSON text with no whitespace"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; LOGGER.info( "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); assertTrue(JSONP_Util.assertEqualsJsonText(expJson, actJson), "jsonGeneratorObjectEncodingTest2 Failed"); } catch (Exception e) { fail("jsonGeneratorObjectEncodingTest2 Failed: ", e); } } /* * @testName: jsonGeneratorUTFEncodedTests * * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:163; * JSONP:JAVADOC:289; JSONP:JAVADOC:416; * * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. * * The output is written to an OutputStream using all supported UTF encodings * and read back as a string and filtered to remove whitespace and is compared * against an expected string. The following UTF encodings are tested: * * UTF8 UTF16 UTF16LE UTF16BE UTF32LE UTF32BE * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } */ @Test public void jsonGeneratorUTFEncodedTests() { boolean pass = true; LOGGER.info( "Create expected JSON text with no whitespace for use with comparison"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; try { LOGGER.info( "-----------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-8]"); LOGGER.info( "-----------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonGenerator using UTF-8 encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_8); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-8")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-8 encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing generation to UTF-8 encoding: " + e); } try { LOGGER.info( "------------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-16]"); LOGGER.info( "------------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonGenerator using UTF-16 encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_16); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-16")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-16 encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing generation to UTF-16 encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-16LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonGenerator using UTF-16LE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_16LE); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-16LE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-16LE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16LE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-16LE encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-16BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonGenerator using UTF-16BE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_16BE); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-16BE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-16BE encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-32LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonGenerator using UTF-32LE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_32LE); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-32LE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-32LE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32LE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-32LE encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-32BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonGenerator using UTF-32BE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json .createGeneratorFactory(JSONP_Util.getEmptyConfig()) .createGenerator(baos, JSONP_Util.UTF_32BE); generateSimpleJsonObject(generator); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-32BE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-32BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32BE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-32BE encoding: " + e); } assertTrue(pass, "jsonGeneratorUTFEncodedTests Failed"); } /* * @testName: jsonGeneratorExceptionTests * * @assertion_ids: JSONP:JAVADOC:339; JSONP:JAVADOC:341; JSONP:JAVADOC:115; * JSONP:JAVADOC:293; JSONP:JAVADOC:296; JSONP:JAVADOC:299; JSONP:JAVADOC:302; * JSONP:JAVADOC:305; JSONP:JAVADOC:308; JSONP:JAVADOC:311; JSONP:JAVADOC:315; * JSONP:JAVADOC:297; JSONP:JAVADOC:303; JSONP:JAVADOC:306; JSONP:JAVADOC:309; * JSONP:JAVADOC:312; JSONP:JAVADOC:316; JSONP:JAVADOC:336; JSONP:JAVADOC:335; * JSONP:JAVADOC:290; JSONP:JAVADOC:331; JSONP:JAVADOC:381; JSONP:JAVADOC:382; * JSONP:JAVADOC:350; JSONP:JAVADOC:352; JSONP:JAVADOC:354; JSONP:JAVADOC:356; * JSONP:JAVADOC:358; JSONP:JAVADOC:360; JSONP:JAVADOC:362; JSONP:JAVADOC:364; * JSONP:JAVADOC:366; JSONP:JAVADOC:347; JSONP:JAVADOC:348; JSONP:JAVADOC:368; * JSONP:JAVADOC:370; JSONP:JAVADOC:372; JSONP:JAVADOC:374; * * @test_Strategy: Tests various exception test cases. * * NumberFormatException JsonGenerationException * */ @Test public void jsonGeneratorExceptionTests() { boolean pass = true; // Test NumberFormatException for write(double) if value is // Not-a-Number(NaN) or infinity try { LOGGER.info( "Trip NumberFormatException for write(double) if value is Not-a-Number(NaN) or infinity"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write(Double.NaN); LOGGER.warning("Did not get expected NumberFormatException"); pass = false; } catch (NumberFormatException e) { LOGGER.info("Caught expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test NumberFormatException for write(double) if value is // Not-a-Number(NaN) or infinity try { LOGGER.info( "Trip NumberFormatException for write(double) if value is Not-a-Number(NaN) or infinity"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write(Double.NEGATIVE_INFINITY); LOGGER.warning("Did not get expected NumberFormatException"); pass = false; } catch (NumberFormatException e) { LOGGER.info("Caught expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test NumberFormatException for write(double) if value is // Not-a-Number(NaN) or infinity try { LOGGER.info( "Trip NumberFormatException for write(double) if value is Not-a-Number(NaN) or infinity"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write(Double.POSITIVE_INFINITY); LOGGER.warning("Did not get expected NumberFormatException"); pass = false; } catch (NumberFormatException e) { LOGGER.info("Caught expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test NumberFormatException for write(String,double) if value is // Not-a-Number(NaN) or infinity try { LOGGER.info( "Trip NumberFormatException for write(String,double) if value is Not-a-Number(NaN) or infinity"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("badnumber", Double.NaN); LOGGER.warning("Did not get expected NumberFormatException"); pass = false; } catch (NumberFormatException e) { LOGGER.info("Caught expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test NumberFormatException for write(String,double) if value is // Not-a-Number(NaN) or infinity try { LOGGER.info( "Trip NumberFormatException for write(String,double) if value is Not-a-Number(NaN) or infinity"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("badnumber", Double.NEGATIVE_INFINITY); LOGGER.warning("Did not get expected NumberFormatException"); pass = false; } catch (NumberFormatException e) { LOGGER.info("Caught expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test NumberFormatException for write(String,double) if value is // Not-a-Number(NaN) or infinity try { LOGGER.info( "Trip NumberFormatException for write(String,double) if value is Not-a-Number(NaN) or infinity"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("badnumber", Double.POSITIVE_INFINITY); LOGGER.warning("Did not get expected NumberFormatException"); pass = false; } catch (NumberFormatException e) { LOGGER.info("Caught expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonGenerationExceptipn if an incomplete JSON is generated. try { LOGGER.info( "Trip JsonGenerationExceptipn if an incomplete JSON is generated."); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("name", "value"); generator.close(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonGenerationExceptipn if an incomplete JSON is generated. try { LOGGER.info( "Trip JsonGenerationExceptipn if an incomplete JSON is generated."); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string"); generator.close(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(JsonValue) if not called within // array context try { LOGGER.info( "Trip JsonGenerationException for write(JsonValue) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write(JsonValue.TRUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String) if not called within array // context try { LOGGER.info( "Trip JsonGenerationException for write(String) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("name"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(BigInteger) if not called within // array context try { LOGGER.info( "Trip JsonGenerationException for write(BigInteger) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject() .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(BigDecimal) if not called within // array context try { LOGGER.info( "Trip JsonGenerationException for write(BigDecimal) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write(BigDecimal.valueOf(Integer.MIN_VALUE)); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(int) if not called within array // context try { LOGGER.info( "Trip JsonGenerationException for write(int) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write(Integer.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(long) if not called within array // context try { LOGGER.info( "Trip JsonGenerationException for write(long) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write(Long.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(double) if not called within array // context try { LOGGER.info( "Trip JsonGenerationException for write(double) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write(Double.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(boolean) if not called within // array context try { LOGGER.info( "Trip JsonGenerationException for write(boolean) if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write(true); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeNull() if not called within array // context try { LOGGER.info( "Trip JsonGenerationException for writeNull() if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeNull(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeStartArray() if not called within // array context try { LOGGER.info( "Trip JsonGenerationException for writeStartArray() if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeStartArray(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeStartObject() if not called within // array context try { LOGGER.info( "Trip JsonGenerationException for writeStartObject() if not called within array context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeStartObject(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,JsonValue) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for write(String,JsonValue) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", JsonValue.TRUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,String) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for write(String,String) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", "name"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,BigInteger) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for write(String,BigInteger) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", new BigInteger(new Integer(Integer.MAX_VALUE).toString())); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,BigDecimal) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for write(String,BigDecimal) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", BigDecimal.valueOf(Integer.MIN_VALUE)); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,int) if not called within // object context try { LOGGER.info( "Trip JsonGenerationException for write(String,int) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", Integer.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,long) if not called within // object context try { LOGGER.info( "Trip JsonGenerationException for write(String,long) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", Long.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,double) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for write(String,double) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", Double.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,boolean) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for write(String,boolean) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write("string", true); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeNull(String) if not called within // object context try { LOGGER.info( "Trip JsonGenerationException for writeNull(String) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeNull("string"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeStartArray(String) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for writeStartArray(String) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeStartArray("string"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeStartObject(String) if not called // within object context try { LOGGER.info( "Trip JsonGenerationException for writeStartObject(String) if not called within object context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeStartObject("string"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,JsonValue) when invoked // after the writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,JsonValue) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", "value"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeEnd() when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for writeEnd() when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().writeEnd(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,BigInteger) when invoked // after the writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,BigInteger) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", new BigInteger(new Integer(Integer.MAX_VALUE).toString())); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,BigDecimal) when invoked // after the writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,BigDecimal) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", BigDecimal.valueOf(Integer.MIN_VALUE)); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,int) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,int) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", Integer.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,long) when invoked after // the writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,long) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", Long.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,double) when invoked after // the writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,double) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", Double.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String,boolean) when invoked after // the writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String,boolean) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().write("name", false); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for writeNull(String) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for writeNull(String) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeEnd().writeNull("name"); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(JsonValue) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(JsonValue) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().write(JsonValue.TRUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(String) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(String) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().write(JsonValue.TRUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(BigDecimal) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(BigDecimal) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd() .write(BigDecimal.valueOf(Integer.MIN_VALUE)); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(BigInteger) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(BigInteger) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd() .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(int) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(int) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().write(Integer.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(long) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(long) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().write(Long.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(double) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(double) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().write(Double.MAX_VALUE); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for write(boolean) when invoked after the // writeEnd method is called try { LOGGER.info( "Trip JsonGenerationException for write(boolean) when invoked after the writeEnd method is called"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().write(true); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test JsonGenerationException for for writeNull() when invoked with no // context try { LOGGER.info( "Trip JsonGenerationException for for writeNull() when invoked with no context"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().writeEnd().writeNull(); LOGGER.warning("Did not get expected JsonGenerationException"); pass = false; } catch (JsonGenerationException e) { LOGGER.info("Caught expected JsonGenerationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonGeneratorExceptionTests Failed"); } /* * @testName: flushTest * * @assertion_ids: JSONP:JAVADOC:131; JSONP:JAVADOC:289; JSONP:JAVADOC:291; * JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; * * @test_Strategy: Generate some partial Json, flush output and compare * output. Generate additional Json to complete, flush output again and * compare. Test passes if comparisons are correct. * * {"object":{},"array":[]} */ @Test public void flushTest() { boolean pass = true; try { LOGGER.info("Generate some partial Json and flush output."); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().writeStartObject("object").writeEnd() .flush(); // Do comparison 1 LOGGER.info("Create expected partial JSON text with no whitespace"); String expJson = "{\"object\":{}"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; LOGGER.info("Generate additional Json to complete and flush output."); generator.writeStartArray("array").writeEnd().writeEnd().flush(); // Do comparison 2 expJson = "{\"object\":{},\"array\":[]}"; LOGGER.info("Read the JSON text back from Writer removing whitespace"); actJson = JSONP_Util.removeWhitespace(sWriter.toString()); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; generator.close(); } catch (Exception e) { fail("flushTest Failed: ", e); } assertTrue(pass, "flushTest Failed"); } /* * @testName: jsonGeneratorIOErrorTests * * @assertion_ids: JSONP:JAVADOC:346; JSONP:JAVADOC:551; * * @test_Strategy: Tests for JsonException for testable i/o errors. * */ @Test public void jsonGeneratorIOErrorTests() { boolean pass = true; // Trip JsonException if there is an i/o error on JsonGenerator.close() try { LOGGER.info( "Trip JsonException if there is an i/o error on JsonGenerator.close()."); MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); JsonGenerator generator = Json.createGenerator(mbw); generator.writeStartObject().writeEnd(); mbw.setThrowIOException(true); LOGGER.info("Calling JsonGenerator.close()"); generator.close(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException if there is an i/o error on JsonGenerator.flush() try { LOGGER.info( "Trip JsonException if there is an i/o error on JsonGenerator.flush()."); MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); JsonGenerator generator = Json.createGenerator(mbw); generator.writeStartObject().writeEnd(); mbw.setThrowIOException(true); LOGGER.info("Calling JsonGenerator.flush()"); generator.flush(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonGeneratorIOErrorTests Failed"); } /* * @testName: jsonGeneratorDocumentRootTest * * @assertion_ids: JSONP:JAVADOC:317; JSONP:JAVADOC:319; JSONP:JAVADOC:321; * JSONP:JAVADOC:323; JSONP:JAVADOC:325; JSONP:JAVADOC:327; JSONP:JAVADOC:329; * JSONP:JAVADOC:332; JSONP:JAVADOC:583; JSONP:JAVADOC:584; JSONP:JAVADOC:585; * JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; JSONP:JAVADOC:662; * JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; JSONP:JAVADOC:666; * JSONP:JAVADOC:667; JSONP:JAVADOC:289; JSONP:JAVADOC:341; JSONP:JAVADOC:672; * * @test_Strategy: Tests RFC 7159 grammar changes:
{@code * "JSON-text = ws value ws"}
{@code * "value = false / null / true / object / array / number / string"} */ @Test public void jsonGeneratorDocumentRootTest() { Generator genTest = new Generator(); final TestResult result = genTest.test(); result.eval(); } /* * @testName: jsonGeneratorStreamNotClosedTest */ @Test public void jsonGeneratorStreamNotClosedTest() { ByteArrayOutputStreamCloseChecker stream = new ByteArrayOutputStreamCloseChecker(); JsonGenerator gen = Json.createGenerator(stream); try { gen.writeStartObject(); gen.write("foo", "bar"); // no end object gen.close(); throw new AssertionFailedError("It is expected a JsonGenerationException"); } catch (JsonGenerationException e) { if (stream.closed) { // Stream should not be closed throw new AssertionFailedError("The underlying stream is closed but it shouldn't because JSON object was not completed"); } } } /* * @testName: jsonGeneratorStreamClosedTest */ @Test public void jsonGeneratorStreamClosedTest() { ByteArrayOutputStreamCloseChecker stream = new ByteArrayOutputStreamCloseChecker(); JsonGenerator gen = Json.createGenerator(stream); gen.writeStartObject(); gen.write("foo", "bar"); gen.writeEnd(); gen.close(); if (!stream.closed) { // Stream should be closed throw new AssertionFailedError("The underlying stream has to be closed because JSON object was completed"); } } private static class ByteArrayOutputStreamCloseChecker extends ByteArrayOutputStream { private boolean closed = false; @Override public void close() throws IOException { closed = true; } } } Generator.java000066400000000000000000000173271451447132700350210ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsongeneratortests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsongeneratortests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.io.StringReader; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.logging.Logger; import jakarta.json.Json; import jakarta.json.JsonReader; import jakarta.json.JsonValue; import jakarta.json.stream.JsonGenerator; import jakarta.json.JsonObject; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: {@link JsonGenerator} * API methods. */ public class Generator { private static final Logger LOGGER = Logger.getLogger(Generator.class.getName()); /** Tests input data. */ private static final Object[] VALUES = new Object[] { SimpleValues.OBJ_VALUE, // write(JsonValue) // for // JsonObject SimpleValues.createEmptyArrayWithStr(), // write(JsonValue) for simple JsonArray SimpleValues.STR_VALUE, // write(JsonValue) for String SimpleValues.INT_VALUE, // write(JsonValue) for int SimpleValues.LNG_VALUE, // write(JsonValue) for long SimpleValues.DBL_VALUE, // write(JsonValue) for double SimpleValues.BIN_VALUE, // write(JsonValue) for BigInteger SimpleValues.BDC_VALUE, // write(JsonValue) for BigDecimal SimpleValues.BOOL_VALUE, // write(JsonValue) for boolean null // write(JsonValue) for null }; /** * Test {@link JsonGenerator} API methods. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonGenerator API methods for RFC 7159 grammar changes."); LOGGER.info("JsonGenerator API methods for RFC 7159 grammar changes."); testPrimitiveTypesInRoot(result); testWrittingObjectByParts(result); return result; } /** * Test primitive types as JSON value stored in JSON document root. RFC 7159 * grammar changes now allows such a values to be stored in JSON document * root. */ private void testPrimitiveTypesInRoot(final TestResult result) { for (Object value : VALUES) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - write(JsonValue) for " + typeName + " as an argument"); verifyJsonGeneratorForJsonValue(result, value); verifyJsonGeneratorForSimpleType(result, value); } } /** * Verify JSON object generation using low level methods * {@code writeStartObject()}, {@code writeEnd()}, {@code writeKey(String)} * and {@code write(String)}. */ private void testWrittingObjectByParts(final TestResult result) { LOGGER.info(" - generate JSON object"); final StringWriter strWriter = new StringWriter(); try (JsonGenerator generator = Json.createGenerator(strWriter)) { generator.writeStartObject(); generator.writeKey(SimpleValues.STR_NAME); generator.write(SimpleValues.STR_VALUE); generator.writeEnd(); } final String out = strWriter.toString(); final JsonObject check = SimpleValues.createSimpleObjectStr(); if (operationFailed(check, out)) { final String checkStr = check.toString(); LOGGER.info( " Generated JSON object " + out + " shall be " + checkStr); result.fail("generate JSON object", "Generated value " + out + " shall be " + checkStr); } else { LOGGER.info(" Output: " + out); } } /** * Verify JSON document root generation for provided JSON value. */ private void verifyJsonGeneratorForJsonValue(final TestResult result, final Object value) { final StringWriter strWriter = new StringWriter(); final JsonValue jsonValue = SimpleValues.toJsonValue(value); try (JsonGenerator generator = Json.createGenerator(strWriter)) { generator.write(jsonValue); } final String out = strWriter.toString(); if (operationFailed(jsonValue, out)) { final String check = jsonValue.toString(); LOGGER.info(" Generated JSON value " + out + " shall be " + check); result.fail("write(JsonValue)", "Generated value " + out + " shall be " + check); } else { LOGGER.info(" Output (JsonValue): " + out); } } /** * Verify JSON document root generation for provided JSON value. */ @SuppressWarnings("UnnecessaryUnboxing") private void verifyJsonGeneratorForSimpleType(final TestResult result, final Object value) { final StringWriter strWriter = new StringWriter(); try (JsonGenerator generator = Json.createGenerator(strWriter)) { switch (JsonValueType.getType(value)) { case String: generator.write((String) value); break; case Integer: generator.write(((Integer) value).intValue()); break; case Long: generator.write(((Long) value).longValue()); break; case BigInteger: generator.write((BigInteger) value); break; case Double: generator.write(((Double) value).doubleValue()); break; case BigDecimal: generator.write((BigDecimal) value); break; case Boolean: generator.write(((Boolean) value).booleanValue() ? JsonValue.TRUE : JsonValue.FALSE); break; case JsonValue: generator.write((JsonValue) value); break; case Null: generator.write(JsonValue.NULL); break; default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } final String out = strWriter.toString(); if (operationFailed(value, out)) { final String check = SimpleValues.toJsonValue(value).toString(); LOGGER.info(" Generated simple value " + out + " shall be " + check); result.fail("write(JsonValue)", "Generated value " + out + " shall be " + check); } else { LOGGER.info(" Output (simple): " + out); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final Object check, final String out) { return out == null || !JsonAssert.assertEquals(check, out); } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final String out) { if (out == null) { return true; } try (final JsonReader reader = Json.createReader(new StringReader(out))) { final JsonValue actVal = reader.readValue(); return !JsonAssert.assertEquals((JsonValue) check, actVal); } } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonnumbertests/000077500000000000000000000000001451447132700315775ustar00rootroot00000000000000ClientTests.java000066400000000000000000000144651451447132700346360ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonnumbertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonnumbertests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonNumberEqualsTest * * @assertion_ids: JSONP:JAVADOC:250; * * @test_Strategy: Tests JsonNumber equals method. Create 2 equal JsonNumbers * and compare them for equality and expect true. Create 2 non-equal * JsonNumbers and compare them for equality and expect false. */ @Test public void jsonNumberEqualsTest() { boolean pass = true; try { LOGGER.info("Create sample JsonNumber 1 for testing"); JsonNumber number1 = JSONP_Util.createJsonNumber(10); LOGGER.info("number1=" + JSONP_Util.toStringJsonNumber(number1)); LOGGER.info("Create sample JsonNumber 2 for testing"); JsonNumber number2 = JSONP_Util.createJsonNumber(10); LOGGER.info("number2=" + JSONP_Util.toStringJsonNumber(number2)); LOGGER.info( "Call JsonNumber.equals() to compare 2 equal JsonNumbers and expect true"); if (number1.equals(number2)) { LOGGER.info("JsonNumbers are equal - expected."); } else { pass = false; LOGGER.warning("JsonNumbers are not equal - unexpected."); } LOGGER.info("Create sample JsonNumber 1 for testing"); number1 = JSONP_Util.createJsonNumber(10); LOGGER.info("number1=" + JSONP_Util.toStringJsonNumber(number1)); LOGGER.info("Create sample JsonNumber 2 for testing"); number2 = JSONP_Util.createJsonNumber((double) 10.25); LOGGER.info("number2=" + JSONP_Util.toStringJsonNumber(number2)); LOGGER.info( "Call JsonNumber.equals() to compare 2 equal JsonNumbers and expect false"); if (!number1.equals(number2)) { LOGGER.info("JsonNumbers are not equal - expected."); } else { pass = false; LOGGER.warning("JsonNumbers are equal - unexpected."); } } catch (Exception e) { fail("jsonNumberEqualsTest Failed: ", e); } assertTrue(pass, "jsonNumberEqualsTest Failed"); } /* * @testName: jsonNumberHashCodeTest * * @assertion_ids: JSONP:JAVADOC:251; * * @test_Strategy: Tests JsonNumber equals method. Create 2 equal JsonNumbers * and compare them for hashcode and expect true. Create 2 non-equal * JsonNumbers and compare them for hashcode and expect false. */ @Test public void jsonNumberHashCodeTest() { boolean pass = true; try { LOGGER.info("Create sample JsonNumber 1 for testing"); JsonNumber number1 = JSONP_Util.createJsonNumber(10); LOGGER.info("number1=" + JSONP_Util.toStringJsonNumber(number1)); LOGGER.info("number1.hashCode()=" + number1.hashCode()); LOGGER.info("Create sample JsonNumber 2 for testing"); JsonNumber number2 = JSONP_Util.createJsonNumber(10); LOGGER.info("number2=" + JSONP_Util.toStringJsonNumber(number2)); LOGGER.info("number2.hashCode()=" + number2.hashCode()); LOGGER.info( "Call JsonNumber.hashCode() to compare 2 equal JsonNumbers and expect true"); if (number1.hashCode() == number2.hashCode()) { LOGGER.info("JsonNumbers hashCode are equal - expected."); } else { pass = false; LOGGER.warning("JsonNumbers hashCode are not equal - unexpected."); } LOGGER.info("Create sample JsonNumber 1 for testing"); number1 = JSONP_Util.createJsonNumber(10); LOGGER.info("number1=" + JSONP_Util.toStringJsonNumber(number1)); LOGGER.info("number1.hashCode()=" + number1.hashCode()); LOGGER.info("Create sample JsonNumber 2 for testing"); number2 = JSONP_Util.createJsonNumber((double) 10.25); LOGGER.info("number2=" + JSONP_Util.toStringJsonNumber(number2)); LOGGER.info("number2.hashCode()=" + number2.hashCode()); LOGGER.info( "Call JsonNumber.hashCode() to compare 2 equal JsonNumbers and expect false"); if (number1.hashCode() != number2.hashCode()) { LOGGER.info("JsonNumbers hashCode are not equal - expected."); } else { pass = false; LOGGER.warning("JsonNumbers hashCode are equal - unexpected."); } } catch (Exception e) { fail("jsonNumberHashCodeTest Failed: ", e); } assertTrue(pass, "jsonNumberHashCodeTest Failed"); } /* * @testName: jsonNumberIsIntegralTest * * @assertion_ids: JSONP:JAVADOC:51; * * @test_Strategy: Test JsonNumber.isIntegral() method. */ @Test public void jsonNumberIsIntegralTest() { boolean pass = true; JsonNumber jsonNumber = null; try { // INTEGRAL NUMBER TEST JsonNumber number1 = JSONP_Util.createJsonNumber(123); if (!JSONP_Util.assertEqualsJsonNumberType(number1.isIntegral(), JSONP_Util.INTEGRAL)) pass = false; else { if (!JSONP_Util.assertEquals(123, number1.intValue())) pass = false; } // NON_INTEGRAL NUMBER TEST JsonNumber number2 = JSONP_Util.createJsonNumber(12345.45); if (!JSONP_Util.assertEqualsJsonNumberType(number2.isIntegral(), JSONP_Util.NON_INTEGRAL)) pass = false; else { if (!JSONP_Util.assertEquals(12345.45, number2.doubleValue())) pass = false; } } catch (Exception e) { fail("jsonNumberIsIntegralTest Failed: ", e); } assertTrue(pass, "jsonNumberIsIntegralTest Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonobjecttests/000077500000000000000000000000001451447132700315555ustar00rootroot00000000000000ClientTests.java000066400000000000000000001524541451447132700346150ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonobjecttests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonobjecttests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Data; import ee.jakarta.tck.jsonp.common.JSONP_Util; import java.io.StringReader; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonNumber; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonReader; import jakarta.json.JsonString; import jakarta.json.JsonValue; import jakarta.json.JsonWriter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonObjectTest1 * * @assertion_ids: JSONP:JAVADOC:58; JSONP:JAVADOC:61; JSONP:JAVADOC:64; * JSONP:JAVADOC:67; JSONP:JAVADOC:70; JSONP:JAVADOC:73; JSONP:JAVADOC:76; * JSONP:JAVADOC:80; JSONP:JAVADOC:86; JSONP:JAVADOC:400; JSONP:JAVADOC:401; * JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; JSONP:JAVADOC:406; * JSONP:JAVADOC:408; JSONP:JAVADOC:409; * * @test_Strategy: Tests JsonObject/JsonObjectBuilder API's. Build a * JsonObject using the JsonObjectBuilder API's then verify that the Map of * JsonObject values matches the expected Map of JsonObject values. */ @Test public void jsonObjectTest1() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject object = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); JsonArray array = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create the expected map of JsonObject values"); Map expMap = new HashMap<>(); expMap.put("false", JsonValue.FALSE); expMap.put("true", JsonValue.TRUE); expMap.put("null", JsonValue.NULL); expMap.put("doublemin", JSONP_Util.createJsonNumber(Double.MIN_VALUE)); expMap.put("doublemax", JSONP_Util.createJsonNumber(Double.MAX_VALUE)); expMap.put("intmin", JSONP_Util.createJsonNumber(Integer.MIN_VALUE)); expMap.put("intmax", JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); expMap.put("longmin", JSONP_Util.createJsonNumber(Long.MIN_VALUE)); expMap.put("longmax", JSONP_Util.createJsonNumber(Long.MAX_VALUE)); expMap.put("bigdecimal", JSONP_Util.createJsonNumber(BigDecimal.valueOf(123456789.123456789))); expMap.put("biginteger", JSONP_Util.createJsonNumber(new BigInteger("123456789"))); expMap.put("string", JSONP_Util.createJsonString("string1")); expMap.put("false2", JsonValue.FALSE); expMap.put("true2", JsonValue.TRUE); expMap.put("null2", JsonValue.NULL); expMap.put("object", object); expMap.put("array", array); JSONP_Util.dumpMap(expMap, "Expected Map"); LOGGER.info("Create JsonObject using all JsonObjectBuilder API's"); JsonObject myJsonObject = Json.createObjectBuilder() .add("false", JsonValue.FALSE).add("true", JsonValue.TRUE) .add("null", JsonValue.NULL).add("doublemin", Double.MIN_VALUE) .add("doublemax", Double.MAX_VALUE).add("intmin", Integer.MIN_VALUE) .add("intmax", Integer.MAX_VALUE).add("longmin", Long.MIN_VALUE) .add("longmax", Long.MAX_VALUE) .add("bigdecimal", BigDecimal.valueOf(123456789.123456789)) .add("biginteger", new BigInteger("123456789")) .add("string", "string1").add("false2", false).add("true2", true) .addNull("null2").add("object", object).add("array", array).build(); Map actMap = myJsonObject; JSONP_Util.dumpMap(actMap, "Actual Map"); LOGGER.info( "Compare actual Map of JsonObject values with expected Map of JsonObject values"); assertTrue(JSONP_Util.assertEqualsMap(expMap, actMap), "jsonObjectTest1 Failed"); } catch (Exception e) { fail("jsonObjectTest1 Failed: ", e); } } /* * @testName: jsonObjectTest2 * * @assertion_ids: JSONP:JAVADOC:86; JSONP:JAVADOC:58; JSONP:JAVADOC:61; * JSONP:JAVADOC:64; JSONP:JAVADOC:67; JSONP:JAVADOC:70; JSONP:JAVADOC:73; * JSONP:JAVADOC:76; JSONP:JAVADOC:80; JSONP:JAVADOC:185; JSONP:JAVADOC:400; * JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; * * @test_Strategy: Tests JsonObject/JsonObjectBuilder API's. Build a * JsonObject using the JsonObjectBuilder API's. Write the JsonObject to a * JsonWriter and read it back using a JsonReader. Verify that JsonObject * written to the JsonWriter and then read back using the JsonReader are * equal. */ @Test public void jsonObjectTest2() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject object = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); JsonArray array = JSONP_Util.createSampleJsonArray(); LOGGER.info( "Create JsonObject 'myJsonObject1' using all JsonObjectBuilder API's"); JsonObject myJsonObject1 = Json.createObjectBuilder() .add("false", JsonValue.FALSE).add("true", JsonValue.TRUE) .add("null", JsonValue.NULL).add("doublemin", Double.MIN_VALUE) .add("doublemax", Double.MAX_VALUE).add("intmin", Integer.MIN_VALUE) .add("intmax", Integer.MAX_VALUE).add("longmin", Long.MIN_VALUE) .add("longmax", Long.MAX_VALUE) .add("bigdecimal", BigDecimal.valueOf(123456789.123456789)) .add("biginteger", new BigInteger("123456789")) .add("string", "string1").add("false2", false).add("true2", true) .addNull("null2").add("object", object).add("array", array).build(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); StringWriter sw = new StringWriter(); try (JsonWriter writer = Json.createWriter(sw)) { writer.writeObject(myJsonObject1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sw.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info( "Read the JsonObject back into 'myJsonObject2' using a JsonReader"); JsonObject myJsonObject2; try (JsonReader reader = Json.createReader(new StringReader(contents))) { myJsonObject2 = reader.readObject(); LOGGER.info("Save contents of the JsonReader as a String"); contents = reader.toString(); } LOGGER.info("Dump contents of JsonReader as a String"); LOGGER.info("JsonReaderContents=" + contents); LOGGER.info("Compare myJsonObject1 and myJsonObject2 for equality"); assertTrue(JSONP_Util.assertEqualsJsonObjects(myJsonObject1, myJsonObject2), "jsonObjectTest2 Failed"); } catch (Exception e) { fail("jsonObjectTest2 Failed: ", e); } } /* * @testName: jsonObjectTest3 * * @assertion_ids: JSONP:JAVADOC:58; JSONP:JAVADOC:61; JSONP:JAVADOC:64; * JSONP:JAVADOC:67; JSONP:JAVADOC:70; JSONP:JAVADOC:73; JSONP:JAVADOC:76; * JSONP:JAVADOC:80; JSONP:JAVADOC:86; JSONP:JAVADOC:215; JSONP:JAVADOC:101; * JSONP:JAVADOC:403; JSONP:JAVADOC:264; JSONP:JAVADOC:265; JSONP:JAVADOC:436; * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:404; * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; JSONP:JAVADOC:439; * JSONP:JAVADOC:441; JSONP:JAVADOC:443; JSONP:JAVADOC:527; JSONP:JAVADOC:529; * JSONP:JAVADOC:531; JSONP:JAVADOC:533; JSONP:JAVADOC:539; * * @test_Strategy: Tests JsonObject/JsonObjectBuilder API's. Build a * JsonObject using the JsonObjectBuilder API's. Verify contents of JsonObject * using JsonObject().getJsonArray(String), * JsonObject().getJsonNumber(String), JsonObject().getJsonObject(String), * JsonObject().getJsonString(String), JsonObject.getInt(String) and * JsonObject.getString(String), JsonObject.getBoolean(String), * JsonObject.getBoolean(String, boolean), JsonObject.getInt(String, int), * JsonObject.getString(String, String) */ @Test public void jsonObjectTest3() { boolean pass = true; try { LOGGER.info("Create sample JsonObject for testing"); JsonObject object = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); JsonArray array = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create myObject JsonObject with 22 name/value pairs"); JsonObject myObject = Json.createObjectBuilder().add("key0", -1) .add("key1", +1).add("key2", 1).add("key3", -1e3).add("key4", +1e3) .add("key5", 1e3).add("key6", -2E3).add("key7", +2E3).add("key8", 2E3) .add("key9", Long.MAX_VALUE).add("key10", Long.MIN_VALUE) .add("key11", Integer.MAX_VALUE).add("key12", Integer.MIN_VALUE) .add("key13", Double.MAX_VALUE).add("key14", Double.MIN_VALUE) .add("key15", BigDecimal.valueOf(123456789.123456789)) .add("key16", new BigInteger("123456789")) .add("key17", JsonValue.TRUE).add("key18", JsonValue.FALSE) .add("key19", JsonValue.NULL).add("key20", JSONP_Data.asciiCharacters) .add("key21", false).add("key22", true).addNull("key23") .add("key24", object).add("key25", array).build(); LOGGER.info("Checking intValue of key0 for correctness"); if (!JSONP_Util.assertEquals(-1, myObject.getJsonNumber("key0").intValue())) pass = false; LOGGER.info("key0 via JsonNumber.toString()=" + myObject.getJsonNumber("key0").toString()); LOGGER.info("Checking intValue of key1 for correctness"); if (!JSONP_Util.assertEquals(1, myObject.getInt("key1"))) pass = false; LOGGER.info("key1 via JsonNumber.toString()=" + myObject.getInt("key1")); LOGGER.info("Checking intValue of key2 for correctness"); if (!JSONP_Util.assertEquals(1, myObject.getJsonNumber("key2").intValue())) pass = false; LOGGER.info("key2 via JsonNumber.toString()=" + myObject.getJsonNumber("key2").toString()); LOGGER.info("Checking intValue of key3 for correctness"); if (!JSONP_Util.assertEquals(-1000, myObject.getInt("key3"))) pass = false; LOGGER.info("key3 via JsonNumber.toString()=" + myObject.getJsonNumber("key3").toString()); LOGGER.info("Checking intValue of key4 for correctness"); if (!JSONP_Util.assertEquals(1000, myObject.getJsonNumber("key4").intValue())) pass = false; LOGGER.info("key4 via JsonNumber.toString()=" + myObject.getJsonNumber("key4").toString()); LOGGER.info("Checking intValue of key5 for correctness"); if (!JSONP_Util.assertEquals(1000, myObject.getJsonNumber("key5").intValue())) pass = false; LOGGER.info("key5 via JsonNumber.toString()=" + myObject.getJsonNumber("key5").toString()); LOGGER.info("Checking intValue of key6 for correctness"); if (!JSONP_Util.assertEquals(-2000, myObject.getJsonNumber("key6").intValue())) pass = false; LOGGER.info("key6 via JsonNumber.toString()=" + myObject.getJsonNumber("key6").toString()); LOGGER.info("Checking intValue of key7 for correctness"); if (!JSONP_Util.assertEquals(2000, myObject.getJsonNumber("key7").intValue())) pass = false; LOGGER.info("key7 via JsonNumber.toString()=" + myObject.getJsonNumber("key7").toString()); LOGGER.info("Checking intValue of key8 for correctness"); if (!JSONP_Util.assertEquals(2000, myObject.getJsonNumber("key8").intValue())) pass = false; LOGGER.info("key8 via JsonNumber.toString()=" + myObject.getJsonNumber("key8").toString()); LOGGER.info("Checking longValue of key9 for correctness"); if (!JSONP_Util.assertEquals(Long.MAX_VALUE, myObject.getJsonNumber("key9").longValue())) pass = false; LOGGER.info("LongMax via JsonNumber.toString()=" + myObject.getJsonNumber("key9").toString()); if (!JSONP_Util.assertEquals("" + Long.MAX_VALUE, myObject.getJsonNumber("key9").toString())) pass = false; LOGGER.info("Checking longValue of key10 for correctness"); if (!JSONP_Util.assertEquals(Long.MIN_VALUE, myObject.getJsonNumber("key10").longValue())) pass = false; LOGGER.info("LongMin via JsonNumber.toString()=" + myObject.getJsonNumber("key10").toString()); if (!JSONP_Util.assertEquals("" + Long.MIN_VALUE, myObject.getJsonNumber("key10").toString())) pass = false; LOGGER.info("Checking intValue of key11 for correctness"); if (!JSONP_Util.assertEquals(Integer.MAX_VALUE, myObject.getJsonNumber("key11").intValue())) pass = false; LOGGER.info("IntMax via JsonNumber.toString()=" + myObject.getJsonNumber("key11").toString()); if (!JSONP_Util.assertEquals("" + Integer.MAX_VALUE, myObject.getJsonNumber("key11").toString())) pass = false; LOGGER.info("Checking intValue of key12 for correctness"); if (!JSONP_Util.assertEquals(Integer.MIN_VALUE, myObject.getJsonNumber("key12").intValue())) pass = false; LOGGER.info("IntMin via JsonNumber.toString()=" + myObject.getJsonNumber("key12").toString()); if (!JSONP_Util.assertEquals("" + Integer.MIN_VALUE, myObject.getJsonNumber("key12").toString())) pass = false; LOGGER.info("Checking doubleValue of key13 for correctness"); if (!JSONP_Util.assertEquals(Double.MAX_VALUE, myObject.getJsonNumber("key13").doubleValue())) pass = false; LOGGER.info("Checking doubleValue of key14 for correctness"); if (!JSONP_Util.assertEquals(Double.MIN_VALUE, myObject.getJsonNumber("key14").doubleValue())) pass = false; LOGGER.info("Checking bigDecimalValue of key15 for correctness"); if (!JSONP_Util.assertEquals(BigDecimal.valueOf(123456789.123456789), myObject.getJsonNumber("key15").bigDecimalValue())) pass = false; LOGGER.info("Checking bigIntegerValue of key16 for correctness"); if (!JSONP_Util.assertEquals(new BigInteger("123456789"), myObject.getJsonNumber("key16").bigIntegerValue())) pass = false; LOGGER.info("Checking getBoolean of key17 for correctness"); if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key17"))) pass = false; LOGGER.info("Checking getBoolean of key18 for correctness"); if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key18"))) pass = false; LOGGER.info("Checking isNull of key19 for correctness"); if (!JSONP_Util.assertEquals(true, myObject.isNull("key19"))) pass = false; LOGGER.info("Checking getJsonString of key20 for correctness"); if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, myObject.getJsonString("key20").getString())) pass = false; LOGGER.info("Checking getString of key20 for correctness"); if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, myObject.getString("key20"))) pass = false; LOGGER.info("Checking getBoolean of key21 for correctness"); if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key21"))) pass = false; LOGGER.info("Checking getBoolean of key22 for correctness"); if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key22"))) pass = false; LOGGER.info("Checking isNull of key23 for correctness"); if (!JSONP_Util.assertEquals(true, myObject.isNull("key23"))) pass = false; LOGGER.info("Checking getJsonObject of key24 for correctness"); if (!JSONP_Util.assertEqualsJsonObjects(object, myObject.getJsonObject("key24"))) pass = false; LOGGER.info("Checking getJsonArray of key25 for correctness"); if (!JSONP_Util.assertEqualsJsonArrays(array, myObject.getJsonArray("key25"))) pass = false; // Verify calls to JsonObject.getBoolean(int) if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key17"))) pass = false; if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key18"))) pass = false; // Verify calls to JsonObject.getBoolean(String, boolean) LOGGER.info( "Testing JsonObject.getBoolean(String, boolean) with/without default value setting."); if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key17", false))) pass = false; if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key18", true))) pass = false; if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key0", true))) pass = false; if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key19", true))) pass = false; if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key20", true))) pass = false; if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key24", true))) pass = false; if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key25", true))) pass = false; // Verify calls to JsonObject.getInt(String, int) LOGGER.info( "Testing JsonObject.getInt(String, int) with/without default value setting."); if (!JSONP_Util.assertEquals(-1, myObject.getInt("key0", 10))) pass = false; if (!JSONP_Util.assertEquals(10, myObject.getInt("key18", 10))) pass = false; if (!JSONP_Util.assertEquals(10, myObject.getInt("key19", 10))) pass = false; if (!JSONP_Util.assertEquals(10, myObject.getInt("key20", 10))) pass = false; if (!JSONP_Util.assertEquals(10, myObject.getInt("key24", 10))) pass = false; if (!JSONP_Util.assertEquals(10, myObject.getInt("key25", 10))) pass = false; // Verify calls to JsonObject.getString(String, String) LOGGER.info( "Testing JsonObject.getString(String, String) with/without default value setting."); if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, myObject.getString("key20", "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myObject.getString("key0", "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myObject.getString("key18", "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myObject.getString("key19", "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myObject.getString("key24", "foo"))) pass = false; if (!JSONP_Util.assertEquals("foo", myObject.getString("key25", "foo"))) pass = false; } catch (Exception e) { fail("jsonObjectTest3 Failed: ", e); } assertTrue(pass, "jsonObjectTest3 Failed"); } /* * @testName: jsonObjectTest4 * * @assertion_ids: JSONP:JAVADOC:61; JSONP:JAVADOC:70; JSONP:JAVADOC:58; * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:403; JSONP:JAVADOC:404; * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; JSONP:JAVADOC:438; * * @test_Strategy: Build a JsonObject and than write the JsonObject. Compare * the Json text from the writer contents with the expected Json text output * expected based on the JsonObject. */ @Test public void jsonObjectTest4() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); StringWriter sw = new StringWriter(); try (JsonWriter writer = Json.createWriter(sw)) { writer.writeObject(myJsonObject1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sw.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info("Remove whitespace from contents."); String actJsonText = JSONP_Util.removeWhitespace(contents); LOGGER.info( "Compare expected JsonObject text with actual JsonObject text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonText), "jsonObjectTest4 Failed"); } catch (Exception e) { fail("jsonObjectTest4 Failed: ", e); } } /* * @testName: jsonObjectExceptionTests * * @assertion_ids: JSONP:JAVADOC:43; JSONP:JAVADOC:47; JSONP:JAVADOC:50; * JSONP:JAVADOC:344; JSONP:JAVADOC:345; JSONP:JAVADOC:79; JSONP:JAVADOC:437; * JSONP:JAVADOC:440; JSONP:JAVADOC:442; JSONP:JAVADOC:528; JSONP:JAVADOC:530; * JSONP:JAVADOC:532; JSONP:JAVADOC:534; JSONP:JAVADOC:540; * * @test_Strategy: Test JSON exception conditions. Trips the exceptions: * java.lang.ArithmeticException java.lang.ClassCastException * java.lang.NumberFormatException java.lang.UnsupportedOperationException * java.lang.NullPointerException */ @Test public void jsonObjectExceptionTests() { boolean pass = true; JsonObject testObject = null; JsonArray testArray = null; try { LOGGER.info("Create sample JsonObject for testing"); testObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create sample JsonArray for testing"); testArray = JSONP_Util.createSampleJsonArray(); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonNumber via getJsonNumber(String)"); JsonNumber value = testObject.getJsonNumber("address"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonString via getJsonString(String)"); JsonString value = testObject.getJsonString("address"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to JsonArray via getJsonArray(String)"); JsonArray value = testObject.getJsonArray("address"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to JsonNumber via getNumber(String)"); JsonNumber value = testObject.getJsonNumber("phoneNumber"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to JsonString via getJsonString(String)"); JsonString value = testObject.getJsonString("phoneNumber"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to String via getString(String)"); String value = testObject.getString("address"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to String via getString(String)"); String value = testObject.getString("phoneNumber"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonObject to int via getInt(String)"); int value = testObject.getInt("address"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to int via getInt(String)"); int value = testObject.getInt("phoneNumber"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonArray to JsonObject via getJsonObject(String)"); JsonObject value = testObject.getJsonObject("phoneNumber"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonNumber to JsonString via getJsonString(String)"); JsonString value = testObject.getJsonString("age"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonNumber to JsonObject via getJsonNumber(String)"); JsonObject value = testObject.getJsonObject("age"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonNumber to JsonArray via getJsonArray(String)"); JsonArray value = testObject.getJsonArray("age"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonString to JsonNumber via getJsonNumber(String)"); JsonNumber value = testObject.getJsonNumber("firstName"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonString to int via getInt(String)"); int value = testObject.getInt("firstName"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonString to JsonObject via getJsonString(String)"); JsonObject value = testObject.getJsonObject("firstName"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonString to JsonArray via getJsonArray(String)"); JsonArray value = testObject.getJsonArray("firstName"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonNumber via getJsonNumber(String)"); JsonNumber value = testObject.getJsonNumber("elderly"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonString via getJsonString(String)"); JsonString value = testObject.getJsonString("elderly"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonObject via getJsonObject(String)"); JsonObject value = testObject.getJsonObject("elderly"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonArray via getJsonArray(String)"); JsonArray value = testObject.getJsonArray("elderly"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); boolean value = testObject.getBoolean("firstName"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); boolean value = testObject.getBoolean("age"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); boolean value = testObject.getBoolean("objectOfFooBar"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip ClassCastException try { LOGGER.info( "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); boolean value = testObject.getBoolean("arrayOfFooBar"); pass = false; LOGGER.warning("Failed to throw ClassCastException"); } catch (ClassCastException e) { LOGGER.info("Got expected ClassCastException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Testing NumberFormatException calling add(String, Double.NaN) try { LOGGER.info("Trip NumberFormatException calling add(String, Double.NaN)"); JsonObject object = Json.createObjectBuilder().add("double", Double.NaN) .build(); pass = false; LOGGER.warning("Failed to throw NumberFormatException"); } catch (NumberFormatException e) { LOGGER.info("Got expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Testing NumberFormatException calling add(String, // Double.NEGATIVE_INFINITY) try { LOGGER.info( "Trip NumberFormatException calling add(String, Double.NEGATIVE_INFINITY)"); JsonObject object = Json.createObjectBuilder() .add("double", Double.NEGATIVE_INFINITY).build(); pass = false; LOGGER.warning("Failed to throw NumberFormatException"); } catch (NumberFormatException e) { LOGGER.info("Got expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Testing NumberFormatException calling add(String, // Double.POSITIVE_INFINITY) try { LOGGER.info( "Trip NumberFormatException calling add(String, Double.POSITIVE_INFINITY)"); JsonObject object = Json.createObjectBuilder() .add("double", Double.POSITIVE_INFINITY).build(); pass = false; LOGGER.warning("Failed to throw NumberFormatException"); } catch (NumberFormatException e) { LOGGER.info("Got expected NumberFormatException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test for ArithmeticException try { LOGGER.info( "Trip ArithmeticException calling add(\"number\", 12345.12345) and attempting to extract as an exact integer value"); JsonObject object = Json.createObjectBuilder().add("number", 12345.12345) .build(); LOGGER.info("Call JsonObject.getJsonNumber(\"number\").intValueExact()"); int value = object.getJsonNumber("number").intValueExact(); pass = false; LOGGER.warning("Failed to throw ArithmeticException"); } catch (ArithmeticException e) { LOGGER.info("Got expected ArithmeticException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test for ArithmeticException try { LOGGER.info( "Trip ArithmeticException calling add(\"number\", 12345.12345) and attempting to extract as an exact long value"); JsonObject object = Json.createObjectBuilder().add("number", 12345.12345) .build(); LOGGER.info("Call JsonObject.getJsonNumber(\"number\").longValueExact()"); long value = object.getJsonNumber("number").longValueExact(); pass = false; LOGGER.warning("Failed to throw ArithmeticException"); } catch (ArithmeticException e) { LOGGER.info("Got expected ArithmeticException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Test for ArithmeticException try { LOGGER.info( "Trip ArithmeticException calling add(\"number\", 12345.12345) and attempting to extract as an exact biginteger value"); JsonObject object = Json.createObjectBuilder().add("number", 12345.12345) .build(); LOGGER.info( "Call JsonObject.getJsonNumber(\"number\").bigIntegerValueExact()"); BigInteger value = object.getJsonNumber("number").bigIntegerValueExact(); pass = false; LOGGER.warning("Failed to throw ArithmeticException"); } catch (ArithmeticException e) { LOGGER.info("Got expected ArithmeticException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Tests for UnsupportedOperationException using Collection methods to // modify JsonObject Map // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonObject.put(K,V) trying to modify JsonObject map which should be immutable"); testObject.put("foo", JsonValue.FALSE); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonObject.putAll(Map) trying to modify JsonObject map which should be immutable"); testObject.putAll(testObject); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonObject.clear() trying to modify JsonObject map which should be immutable"); testObject.clear(); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip UnsupportedOperationException try { LOGGER.info( "Trip UnsupportedOperationException JsonObject.remove(K) trying to modify JsonObject map which should be immutable"); testObject.remove("firstName"); pass = false; LOGGER.warning("Failed to throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { LOGGER.info("Got expected UnsupportedOperationException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObject.getBoolean(String) when no mapping exists for name."); boolean value = testObject.getBoolean("foo"); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObject.getInt(String) when no mapping exists for name."); int value = testObject.getInt("foo"); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObject.getString(String) when no mapping exists for name."); String value = testObject.getString("foo"); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObject.isNull(String) when no mapping exists for name."); boolean value = testObject.isNull("foo"); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonObjectExceptionTests Failed"); } /* * @testName: jsonObjectNullNameValueExceptionTests * * @assertion_ids: JSONP:JAVADOC:561; JSONP:JAVADOC:562; JSONP:JAVADOC:563; * JSONP:JAVADOC:564; JSONP:JAVADOC:565; JSONP:JAVADOC:566; JSONP:JAVADOC:567; * JSONP:JAVADOC:568; JSONP:JAVADOC:569; JSONP:JAVADOC:570; JSONP:JAVADOC:571; * * @test_Strategy: Test JSON NPE exception conditions when attempting to add a * specified name or value that is null. */ @Test public void jsonObjectNullNameValueExceptionTests() { boolean pass = true; JsonObjectBuilder job = Json.createObjectBuilder(); // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, JsonValue) when name is null."); job.add(null, JsonValue.TRUE); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, JsonValue) when value is null."); job.add("name", (JsonValue) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, String) when name is null."); job.add(null, "value"); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, String) when value is null."); job.add("name", (String) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, BigInteger) when name is null."); job.add(null, new BigInteger("123456789")); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, BigInteger) when value is null."); job.add("name", (BigInteger) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, BigDecimal) when name is null."); job.add(null, new BigDecimal("123456789")); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, BigDecimal) when value is null."); job.add("name", (BigDecimal) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, int) when name is null."); job.add(null, 123456789); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, long) when name is null."); job.add(null, 123456789L); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, double) when name is null."); job.add(null, 123456.789); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObject.add(String, boolean) when name is null."); job.add(null, true); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObject.addNull(String) when name is null."); job.addNull(null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, JsonObjectBuilder) when name is null."); job.add(null, Json.createObjectBuilder()); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonObjectBuilder.add(String, JsonObjectBuilder) when value is null."); job.add("name", (JsonObjectBuilder) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(String, JsonArrayBuilder) when name is null."); job.add(null, Json.createArrayBuilder()); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NullPointerException try { LOGGER.info( "Trip NullPointerException for JsonArrayBuilder.add(String, JsonArrayBuilder) when value is null."); job.add("name", (JsonArrayBuilder) null); pass = false; LOGGER.warning("Failed to throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonObjectNullNameValueExceptionTests Failed"); } /* * @testName: jsonCreateObjectBuilder11Test * * @assertion_ids: JSONP:JAVADOC:577; JSONP:JAVADOC:578; JSONP:JAVADOC:656; * JSONP:JAVADOC:657; * * @test_Strategy: Tests JsonObjectBuilder API factory methods added in JSON-P * 1.1. */ @Test public void jsonCreateObjectBuilder11Test() { CreateObjectBuilder createTest = new CreateObjectBuilder(); final TestResult result = createTest.test(); result.eval(); } /* * @testName: jsonObjectBuilder11Test * * @assertion_ids: JSONP:JAVADOC:618; JSONP:JAVADOC:619; * * @test_Strategy: Tests JsonObjectBuilder API methods added in JSON-P 1.1. */ @Test public void jsonObjectBuilder11Test() { ObjectBuild buildTest = new ObjectBuild(); final TestResult result = buildTest.test(); result.eval(); } /* * @testName: jsonObjectBuilderBuildTest * * @test_Strategy: Tests JsonObjectBuilder#build clears the builder. */ @Test public void jsonObjectBuilderBuildTest() { JsonObjectBuilder builder = Json.createObjectBuilder().add("test", "value"); JsonObject jsonObj = builder.build(); assertEquals("\"value\"", jsonObj.get("test").toString()); jsonObj = builder.build(); assertNull(jsonObj.get("test")); } } CreateObjectBuilder.java000066400000000000000000000073171451447132700362120ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonobjecttests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonobjecttests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: * {@link JsonObjectBuilder} API factory methods added in JSON-P 1.1.
*/ public class CreateObjectBuilder { private static final Logger LOGGER = Logger.getLogger(CreateObjectBuilder.class.getName()); /** * Test {@link JsonObjectBuilder} factory method added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonObjectBuilder API factory methods added in JSON-P 1.1."); LOGGER.info("JsonObjectBuilder API factory methods added in JSON-P 1.1."); testCreateFromMap(result); testCreateFromJsonObject(result); return result; } /** * Test {@link Json#createObjectBuilder(Map)} method. * * @param result * Test suite result. */ private void testCreateFromMap(final TestResult result) { LOGGER.info(" - Json#createObjectBuilder(Map)"); final JsonObject check = SimpleValues.createSimpleObjectWithStr(); Map values = new HashMap<>(2); values.put(SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE); values.put(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); final JsonObjectBuilder builder = Json.createObjectBuilder(values); final JsonObject out = builder.build(); if (operationFailed(check, out)) { result.fail("createObjectBuilder(Map)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test {@link Json#createObjectBuilder(JsonObject)} method. * * @param result * Test suite result. */ private void testCreateFromJsonObject(final TestResult result) { LOGGER.info(" - Json#createObjectBuilder(JsonObject)"); final JsonObject check = SimpleValues.createSimpleObjectWithStr(); final JsonObjectBuilder builder = Json.createObjectBuilder(check); final JsonObject out = builder.build(); if (operationFailed(check, out)) { result.fail("reateObjectBuilder(JsonObject)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } ObjectBuild.java000066400000000000000000000257511451447132700345410ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonobjecttests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonobjecttests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.ObjectBuilder; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for {@link JsonObject} * and {@link JsonObjectBuilder}. */ public class ObjectBuild { private static final Logger LOGGER = Logger.getLogger(ObjectBuild.class.getName()); /** * {@link JsonArrayBuilder} API remove() methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonObjectBuilder API methods added in JSON-P 1.1."); LOGGER.info("JsonObjectBuilder API methods added in JSON-P 1.1."); testAddString(result); testAddInt(result); testAddBool(result); testAddObject(result); testAddAllNull(result); testRemoveString(result); testRemoveInt(result); testRemoveBool(result); testRemoveObject(result); testRemoveNull(result); return result; } /** * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on * {@code String} value. * * @param result * Test suite result. */ private void testAddString(final TestResult result) { LOGGER.info(" - addAll(JsonObjectBuilder) for String"); final JsonObjectBuilder target = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE); final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), SimpleValues.STR_NAME, SimpleValues.STR_VALUE); final JsonObject check = SimpleValues.createSimpleObjectWithStr(); verifyAddAll(result, check, target, arg); } /** * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on * {@code int} value. * * @param result * Test suite result. */ private void testAddInt(final TestResult result) { LOGGER.info(" - addAll(JsonObjectBuilder) for int"); final JsonObjectBuilder target = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE); final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), SimpleValues.INT_NAME, SimpleValues.INT_VALUE); final JsonObject check = SimpleValues.createSimpleObjectWithInt(); verifyAddAll(result, check, target, arg); } /** * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on * {@code boolean} value. * * @param result * Test suite result. */ private void testAddBool(final TestResult result) { LOGGER.info(" - addAll(JsonObjectBuilder) for boolean"); final JsonObjectBuilder target = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE); final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), SimpleValues.BOOL_NAME, SimpleValues.BOOL_VALUE); final JsonObject check = SimpleValues.createSimpleObjectWithBool(); verifyAddAll(result, check, target, arg); } /** * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on * {@code JsonObject} value. * * @param result * Test suite result. */ private void testAddObject(final TestResult result) { LOGGER.info(" - addAll(JsonObjectBuilder) for JsonObject"); final JsonObjectBuilder target = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE) .add(SimpleValues.DEF_OBJ_NAME, SimpleValues.DEF_OBJ_VALUE); final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), SimpleValues.OBJ_NAME, SimpleValues.OBJ_VALUE); final JsonObject check = SimpleValues.createCompoundObjectWithObject(); verifyAddAll(result, check, target, arg); } /** * Test {@code JsonObjectBuilder addAll(JsonObjectBuilder)} method with * {@code null} builder argument. * * @param result * Test suite result. */ private void testAddAllNull(final TestResult result) { LOGGER.info(" - addAll(JsonObjectBuilder) for null builder argument"); JsonObjectBuilder builder = Json.createObjectBuilder(); try { builder.addAll((JsonObjectBuilder) null); result.fail("addAll(null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("addAll(null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test {@code JsonObjectBuilder remove(String)} method on {@code String} * value. * * @param result * Test suite result. */ private void testRemoveString(final TestResult result) { LOGGER.info(" - remove(String) for String"); final JsonObjectBuilder in = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE) .add(SimpleValues.STR_NAME, SimpleValues.STR_VALUE); final JsonObjectBuilder builder = in.remove(SimpleValues.STR_NAME); final JsonObject check = SimpleValues.createSimpleObject(); verifyRemovel(result, check, builder); } /** * Test {@code JsonObjectBuilder remove(String)} method on {@code int} value. * * @param result * Test suite result. */ private void testRemoveInt(final TestResult result) { LOGGER.info(" - remove(String) for int"); final JsonObjectBuilder in = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE) .add(SimpleValues.INT_NAME, SimpleValues.INT_VALUE); final JsonObjectBuilder builder = in.remove(SimpleValues.INT_NAME); final JsonObject check = SimpleValues.createSimpleObject(); verifyRemovel(result, check, builder); } /** * Test {@code JsonObjectBuilder remove(String)} method on {@code boolean} * value. * * @param result * Test suite result. */ private void testRemoveBool(final TestResult result) { LOGGER.info(" - remove(String) for boolean"); final JsonObjectBuilder in = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE) .add(SimpleValues.BOOL_NAME, SimpleValues.BOOL_VALUE); final JsonObjectBuilder builder = in.remove(SimpleValues.BOOL_NAME); final JsonObject check = SimpleValues.createSimpleObject(); verifyRemovel(result, check, builder); } /** * Test {@code JsonObjectBuilder remove(String)} method on {@code JsonObject} * value. * * @param result * Test suite result. */ private void testRemoveObject(final TestResult result) { LOGGER.info(" - remove(String) for JsonObject"); final JsonObjectBuilder in = ObjectBuilder .add(Json.createObjectBuilder(), SimpleValues.DEF_NAME, SimpleValues.DEF_VALUE) .add(SimpleValues.DEF_OBJ_NAME, SimpleValues.DEF_OBJ_VALUE).add(SimpleValues.OBJ_NAME, SimpleValues.OBJ_VALUE); final JsonObjectBuilder builder = in.remove(SimpleValues.OBJ_NAME); final JsonObject check = SimpleValues.createCompoundObject(); verifyRemovel(result, check, builder); } /** * Test {@code JsonObjectBuilder remove(String)} method with {@code null} * name. * * @param result * Test suite result. */ private void testRemoveNull(final TestResult result) { LOGGER.info(" - remove(String) for null name argument"); JsonObjectBuilder builder = Json.createObjectBuilder(); try { builder.remove((String) null); result.fail("remove(null)", "Calling method with null argument shall throw NullPointerException"); } catch (NullPointerException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("remove(null)", "Calling method with null argument shall throw NullPointerException, not " + t.getClass().getSimpleName()); } } /** * Test helper: Verify {@code JsonObjectBuilder addAll(JsonObjectBuilder)} * method on provided builders. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param target * Builder instance used to call {@code addAll(JsonObjectBuilder)} * method. * @param arg * Builder instance passed as an argument. */ private void verifyAddAll(final TestResult result, final JsonObject check, JsonObjectBuilder target, final JsonObjectBuilder arg) { target.addAll(arg); final JsonObject out = target.build(); if (operationFailed(check, out)) { result.fail("addAll(JsonObjectBuilder)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Test helper: Verify {@code JsonObjectBuilder remove(String)} method on * provided builder. * * @param result * Test suite result. * @param check * Expected value (used for operation check). * @param builder * Builder instance after {@code JsonObjectBuilder remove(String)} * method was called. * @param arg * Builder instance passed as an argument. */ private void verifyRemovel(final TestResult result, final JsonObject check, JsonObjectBuilder builder) { final JsonObject out = builder.build(); if (operationFailed(check, out)) { result.fail("remove(String)", "Output builder " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(check)); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparsereventtests/000077500000000000000000000000001451447132700326455ustar00rootroot00000000000000ClientTests.java000066400000000000000000000072751451447132700357050ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparsereventtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonparsereventtests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.stream.*; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonValueOfTest * * @assertion_ids: JSONP:JAVADOC:128; * * @test_Strategy: Test JsonParser.Event.valueOf() API method call with all * JsonParser.Event types. * */ @Test public void jsonValueOfTest() { boolean pass = true; String eventTypeStrings[] = { "END_ARRAY", "END_OBJECT", "KEY_NAME", "START_ARRAY", "START_OBJECT", "VALUE_FALSE", "VALUE_NULL", "VALUE_NUMBER", "VALUE_STRING", "VALUE_TRUE" }; for (String eventTypeString : eventTypeStrings) { JsonParser.Event eventType; try { LOGGER.info( "Testing enum value for string constant name " + eventTypeString); eventType = JsonParser.Event.valueOf(eventTypeString); LOGGER.info("Got enum type " + eventType + " for enum string constant named " + eventTypeString); } catch (Exception e) { LOGGER.warning("Caught unexpected exception: " + e); pass = false; } } LOGGER.info("Testing negative test case for NullPointerException"); try { JsonParser.Event.valueOf(null); LOGGER.warning("did not get expected NullPointerException"); pass = false; } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { LOGGER.warning("Got unexpected exception " + e); pass = false; } LOGGER.info("Testing negative test case for IllegalArgumentException"); try { JsonParser.Event.valueOf("INVALID"); LOGGER.warning("did not get expected IllegalArgumentException"); pass = false; } catch (IllegalArgumentException e) { LOGGER.info("Got expected IllegalArgumentException"); } catch (Exception e) { LOGGER.warning("Got unexpected exception " + e); pass = false; } assertTrue(pass, "jsonValueOfTest Failed"); } /* * @testName: jsonValuesTest * * @assertion_ids: JSONP:JAVADOC:129; * * @test_Strategy: Test JsonParser.Event.values() API method call and verify * enums returned. * */ @Test public void jsonValuesTest() { LOGGER.info( "Testing API method JsonParser.Event.values() to return array of enums."); JsonParser.Event[] values = JsonParser.Event.values(); for (JsonParser.Event eventType : values) { String eventString = JSONP_Util.getEventTypeString(eventType); if (eventString == null) { fail("jsonValuesTest Failed. Got no value for enum " + eventType); } else LOGGER.info("Got " + eventString + " for enum " + eventType); } } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparserfactorytests/000077500000000000000000000000001451447132700331735ustar00rootroot00000000000000ClientTests.java000066400000000000000000000527621451447132700362340ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparserfactorytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id: Client.java 66863 2012-07-23 11:26:40Z adf $ */ package ee.jakarta.tck.jsonp.api.jsonparserfactorytests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import ee.jakarta.tck.jsonp.common.MyBufferedInputStream; import jakarta.json.*; import jakarta.json.stream.*; import java.io.*; import java.util.Map; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonParserFactoryTest1 * * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:164; * * @test_Strategy: Tests the JsonParserFactory API. * * JsonParserFactory parserFactory = Json.createParserFactory(Map); * JsonParser parser1 = parserFactory.createParser(Reader) JsonParser parser2 * = parserFactory.createParser(Reader) */ @Test public void jsonParserFactoryTest1() { boolean pass = true; JsonParser parser1 = null; JsonParser parser2 = null; JsonParser.Event event = null; try { LOGGER.info("Create JsonParserFactory with a configuration"); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("--------------------------------------------------"); LOGGER.info("TEST CASE [JsonParserFactory.createParser(Reader)]"); LOGGER.info("--------------------------------------------------"); String jsonObjectString = "{\"foo\":\"bar\"}"; LOGGER.info("Create 1st JsonParser from the Reader using JsonParserFactory"); parser1 = parserFactory.createParser(new StringReader(jsonObjectString)); if (parser1 == null) { LOGGER.warning("ParserFactory failed to create parser1 from Reader"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } LOGGER.info("Create 2nd JsonParser from the Reader using JsonParserFactory"); parser2 = parserFactory.createParser(new StringReader(jsonObjectString)); if (parser2 == null) { LOGGER.warning("ParserFactory failed to create parser2 from Reader"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } } catch (Exception e) { fail("jsonParserFactoryTest1 Failed: ", e); } finally { try { parser1.close(); parser2.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserFactoryTest1 Failed"); } /* * @testName: jsonParserFactoryTest2 * * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:166; * * @test_Strategy: Tests the JsonParserFactory API. * * JsonParserFactory parserFactory = Json.createParserFactory(Map); * JsonParser parser1 = parserFactory.createParser(JsonObject) JsonParser * parser2 = parserFactory.createParser(JsonObject) */ @Test public void jsonParserFactoryTest2() { boolean pass = true; JsonParser parser1 = null; JsonParser parser2 = null; JsonParser.Event event = null; try { LOGGER.info("Create JsonParserFactory with a configuration"); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("------------------------------------------------------"); LOGGER.info("TEST CASE [JsonParserFactory.createParser(JsonObject)]"); LOGGER.info("------------------------------------------------------"); String jsonObjectString = "{\"foo\":\"bar\"}"; JsonObject jsonObj = JSONP_Util .createJsonObjectFromString(jsonObjectString); LOGGER.info( "Create 1st JsonParser from the JsonObject using JsonParserFactory"); parser1 = parserFactory.createParser(jsonObj); if (parser1 == null) { LOGGER.warning("ParserFactory failed to create parser1 from JsonObject"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } LOGGER.info( "Create 2nd JsonParser from the JsonObject using JsonParserFactory"); parser2 = parserFactory.createParser(jsonObj); if (parser2 == null) { LOGGER.warning("ParserFactory failed to create parser2 from JsonObject"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } } catch (Exception e) { fail("jsonParserFactoryTest2 Failed: ", e); } finally { try { parser1.close(); parser2.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserFactoryTest2 Failed"); } /* * @testName: jsonParserFactoryTest3 * * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:167; * * @test_Strategy: Tests the JsonParserFactory API. * * JsonParserFactory parserFactory = Json.createParserFactory(Map); * JsonParser parser1 = parserFactory.createParser(JsonArray) JsonParser * parser2 = parserFactory.createParser(JsonArray) */ @Test public void jsonParserFactoryTest3() { boolean pass = true; JsonParser parser1 = null; JsonParser parser2 = null; JsonParser.Event event = null; try { LOGGER.info("Create JsonParserFactory with a configuration"); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-----------------------------------------------------"); LOGGER.info("TEST CASE [JsonParserFactory.createParser(JsonArray)]"); LOGGER.info("-----------------------------------------------------"); String jsonArrayString = "[\"foo\",\"bar\"]"; JsonArray jsonArr = JSONP_Util.createJsonArrayFromString(jsonArrayString); LOGGER.info( "Create 1st JsonParser from the JsonArray using JsonParserFactory"); parser1 = parserFactory.createParser(jsonArr); if (parser1 == null) { LOGGER.warning("ParserFactory failed to create parser1 from JsonArray"); pass = false; } else { LOGGER.info("Parsing " + jsonArrayString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser1, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser1, "foo"); JSONP_Util.testStringValue(parser1, "bar"); JSONP_Util.testEventType(parser1, JsonParser.Event.END_ARRAY); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } LOGGER.info( "Create 2nd JsonParser from the JsonArray using JsonParserFactory"); parser2 = parserFactory.createParser(jsonArr); if (parser2 == null) { LOGGER.warning("ParserFactory failed to create parser2 from JsonArray"); pass = false; } else { LOGGER.info("Parsing " + jsonArrayString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser2, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser2, "foo"); JSONP_Util.testStringValue(parser2, "bar"); JSONP_Util.testEventType(parser2, JsonParser.Event.END_ARRAY); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } } catch (Exception e) { fail("jsonParserFactoryTest3 Failed: ", e); } finally { try { parser1.close(); parser2.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserFactoryTest3 Failed"); } /* * @testName: jsonParserFactoryTest4 * * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:165; * * @test_Strategy: Tests the JsonParserFactory API. * * JsonParserFactory parserFactory = Json.createParserFactory(Map); * JsonParser parser1 = parserFactory.createParser(InputStream) JsonParser * parser2 = parserFactory.createParser(InputStream) */ @Test public void jsonParserFactoryTest4() { boolean pass = true; JsonParser parser1 = null; JsonParser parser2 = null; JsonParser.Event event = null; try { LOGGER.info("Create JsonParserFactory with a configuration"); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-------------------------------------------------------"); LOGGER.info("TEST CASE [JsonParserFactory.createParser(InputStream)]"); LOGGER.info("-------------------------------------------------------"); String jsonObjectString = "{\"foo\":\"bar\"}"; LOGGER.info( "Create 1st JsonParser from the InputStream using JsonParserFactory"); parser1 = parserFactory.createParser(new ByteArrayInputStream( jsonObjectString.getBytes(JSONP_Util.UTF_8))); if (parser1 == null) { LOGGER.warning("ParserFactory failed to create parser1 from InputStream"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } LOGGER.info( "Create 2nd JsonParser from the InputStream using JsonParserFactory"); parser2 = parserFactory.createParser(new ByteArrayInputStream( jsonObjectString.getBytes(JSONP_Util.UTF_8))); if (parser2 == null) { LOGGER.warning("ParserFactory failed to create parser2 from InputStream"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } } catch (Exception e) { fail("jsonParserFactoryTest4 Failed: ", e); } finally { try { parser1.close(); parser2.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserFactoryTest4 Failed"); } /* * @testName: jsonParserFactoryTest5 * * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:201; * * @test_Strategy: Tests the JsonParserFactory API. * * JsonParserFactory parserFactory = Json.createParserFactory(Map); * JsonParser parser1 = parserFactory.createParser(InputStream, Charset) * JsonParser parser2 = parserFactory.createParser(InputStream, Charset) */ @Test public void jsonParserFactoryTest5() { boolean pass = true; JsonParser parser1 = null; JsonParser parser2 = null; JsonParser.Event event = null; try { LOGGER.info("Create JsonParserFactory with a configuration"); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info( "----------------------------------------------------------------"); LOGGER.info( "TEST CASE [JsonParserFactory.createParser(InputStream, Charset)]"); LOGGER.info( "----------------------------------------------------------------"); String jsonObjectString = "{\"foo\":\"bar\"}"; LOGGER.info( "Create 1st JsonParser from the InputStream using JsonParserFactory"); parser1 = parserFactory.createParser( new ByteArrayInputStream(jsonObjectString.getBytes(JSONP_Util.UTF_8)), JSONP_Util.UTF_8); if (parser1 == null) { LOGGER.warning("ParserFactory failed to create parser1 from InputStream"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } LOGGER.info( "Create 2nd JsonParser from the InputStream using JsonParserFactory"); parser2 = parserFactory.createParser( new ByteArrayInputStream(jsonObjectString.getBytes(JSONP_Util.UTF_8)), JSONP_Util.UTF_8); if (parser2 == null) { LOGGER.warning("ParserFactory failed to create parser2 from InputStream"); pass = false; } else { LOGGER.info("Parsing " + jsonObjectString); LOGGER.info("Verify that JSON Parser Events/Data matches"); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } } catch (Exception e) { fail("jsonParserFactoryTest5 Failed: ", e); } finally { try { parser1.close(); parser2.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserFactoryTest5 Failed"); } /* * @testName: jsonParserFactoryTest6 * * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:164; JSONP:JAVADOC:428; * * @test_Strategy: Tests the JsonParserFactory API. * * JsonParserFactory parserFactory = Json.createParserFactory(Map); * Map config = JsonParserFactory.getConfigInUse(); * * Test for the following 2 scenarios: 1) no supported provider property * (empty config) 2) non supported provider property */ @Test public void jsonParserFactoryTest6() { boolean pass = true; JsonParserFactory parserFactory; Map config; try { LOGGER.info("----------------------------------------------"); LOGGER.info("Test scenario1: no supported provider property"); LOGGER.info("----------------------------------------------"); LOGGER.info("Create JsonParserFactory with Map with EMPTY config"); parserFactory = Json.createParserFactory(JSONP_Util.getEmptyConfig()); config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-----------------------------------------------"); LOGGER.info("Test scenario2: non supported provider property"); LOGGER.info("-----------------------------------------------"); LOGGER.info("Create JsonParserFactory with Map with FOO config"); parserFactory = Json.createParserFactory(JSONP_Util.getFooConfig()); config = parserFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; } catch (Exception e) { fail("jsonParserFactoryTest6 Failed: ", e); } assertTrue(pass, "jsonParserFactoryTest6 Failed"); } /* * @testName: jsonParserFactoryExceptionTest * * @assertion_ids: JSONP:JAVADOC:225; * * @test_Strategy: Test JsonParserFactory exception conditions. Trip the * following exception due to unknown encoding or i/o error: * * jakarta.json.JsonException */ @Test public void jsonParserFactoryExceptionTest() { boolean pass = true; // Tests JsonParserFactory.createParser(InputStream) for JsonException if // i/o error try { LOGGER.info( "Tests JsonParserFactory.createParser(InputStream) for JsonException if i/o error."); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); MyBufferedInputStream mbi = new MyBufferedInputStream( JSONP_Util.getInputStreamFromString("{}"), true); JsonParser parser = parserFactory.createParser(mbi); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Tests JsonParserFactory.createParser(InputStream) for JsonException if // unknown encoding try { LOGGER.info( "Tests JsonParserFactory.createParser(InputStream) for JsonException if unknown encoding."); JsonParserFactory parserFactory = Json .createParserFactory(JSONP_Util.getEmptyConfig()); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectUnknownEncoding.json"); JsonParser parser = parserFactory.createParser(is); LOGGER.info("parser=" + parser); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonParserFactoryExceptionTest Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparsertests/000077500000000000000000000000001451447132700316035ustar00rootroot00000000000000ClientTests.java000066400000000000000000002227701451447132700346420ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparsertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonparsertests; import java.io.InputStream; import java.io.StringReader; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.logging.Logger; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Data; import ee.jakarta.tck.jsonp.common.JSONP_Util; import ee.jakarta.tck.jsonp.common.MyBufferedInputStream; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParser.Event; import jakarta.json.stream.JsonParsingException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* * Utitity method to parse various JsonObjectUTF encoded files */ private boolean parseAndVerify_JsonObjectUTF(JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "stringName", "stringValue"); JSONP_Util.testKeyStartObjectValue(parser, "objectName"); JSONP_Util.testKeyStringValue(parser, "foo", "bar"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStartArrayValue(parser, "arrayName"); JSONP_Util.testIntegerValue(parser, 1); JSONP_Util.testIntegerValue(parser, 2); JSONP_Util.testIntegerValue(parser, 3); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* * Utitity method to parse JsonObjectWithAllTypesOfData */ private boolean parseAndVerify_JsonObjectWithAllTypesOfData(JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "emptyString", ""); JSONP_Util.testKeyStartArrayValue(parser, "emptyArray"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testKeyStartObjectValue(parser, "emptyObject"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStringValue(parser, "string", "string"); JSONP_Util.testKeyIntegerValue(parser, "number", 100); JSONP_Util.testKeyTrueValue(parser, "true"); JSONP_Util.testKeyFalseValue(parser, "false"); JSONP_Util.testKeyNullValue(parser, "null"); JSONP_Util.testKeyStartObjectValue(parser, "object"); JSONP_Util.testKeyStringValue(parser, "emptyString", ""); JSONP_Util.testKeyStartArrayValue(parser, "emptyArray"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testKeyStartObjectValue(parser, "emptyObject"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStringValue(parser, "string", "string"); JSONP_Util.testKeyIntegerValue(parser, "number", 100); JSONP_Util.testKeyTrueValue(parser, "true"); JSONP_Util.testKeyFalseValue(parser, "false"); JSONP_Util.testKeyNullValue(parser, "null"); JSONP_Util.testKeyStartObjectValue(parser, "object"); JSONP_Util.testKeyStringValue(parser, "name", "value"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStartArrayValue(parser, "array"); JSONP_Util.testStringValue(parser, "one"); JSONP_Util.testStringValue(parser, "two"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStartArrayValue(parser, "array"); JSONP_Util.testStringValue(parser, "string"); JSONP_Util.testIntegerValue(parser, 100); JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "name", "value"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "one"); JSONP_Util.testStringValue(parser, "two"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testKeyIntegerValue(parser, "intPositive", 100); JSONP_Util.testKeyIntegerValue(parser, "intNegative", -100); JSONP_Util.testKeyLongValue(parser, "longMax", 9223372036854775807L); JSONP_Util.testKeyLongValue(parser, "longMin", -9223372036854775808L); JSONP_Util.testKeyDoubleValue(parser, "fracPositive", (double) 0.5); JSONP_Util.testKeyDoubleValue(parser, "fracNegative", (double) -0.5); JSONP_Util.testKeyDoubleValue(parser, "expPositive1", (double) 7e3); JSONP_Util.testKeyDoubleValue(parser, "expPositive2", (double) 7e+3); JSONP_Util.testKeyDoubleValue(parser, "expPositive3", (double) 9E3); JSONP_Util.testKeyDoubleValue(parser, "expPositive4", (double) 9E+3); JSONP_Util.testKeyDoubleValue(parser, "expNegative1", (double) 7e-3); JSONP_Util.testKeyDoubleValue(parser, "expNegative2", (double) 7E-3); JSONP_Util.testKeyStringValue(parser, "asciiChars", JSONP_Data.asciiCharacters); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* * Utitity method to parse JsonObjectWithLotsOfNestedObjectsData */ private boolean parseAndVerify_JsonObjectWithLotsOfNestedObjectsData( JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); for (int i = 1; i < 31; i++) { JSONP_Util.testKeyStartObjectValue(parser, "nested" + i); JSONP_Util.testKeyStringValue(parser, "name" + i, "value" + i); } for (int i = 1; i < 31; i++) { JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); } JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* * Utitity method to parse JsonArrayWithLotsOfNestedObjectsData */ private boolean parseAndVerify_JsonArrayWithLotsOfNestedObjectsData( JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "name1", "value1"); for (int i = 2; i < 31; i++) { JSONP_Util.testKeyStartObjectValue(parser, "nested" + i); JSONP_Util.testKeyStringValue(parser, "name" + i, "value" + i); } for (int i = 2; i < 31; i++) { JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); } JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* * Utitity method to parse JsonArrayWithLotsOfNestedArraysData */ private boolean parseAndVerify_JsonArrayWithLotsOfNestedArraysData( JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "name1"); JSONP_Util.testStringValue(parser, "value1"); for (int i = 2; i < 31; i++) { JSONP_Util.testStringValue(parser, "nested" + i); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "name" + i); JSONP_Util.testStringValue(parser, "value" + i); } for (int i = 2; i < 31; i++) { JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); } JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* * Utitity method to parse JsonArrayWithMultipleArraysData */ private boolean parseAndVerify_JsonArrayWithMultipleArraysData( JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "string"); JSONP_Util.testIntegerValue(parser, 100); JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "object", "object"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "one"); JSONP_Util.testStringValue(parser, "two"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testIntegerValue(parser, 100); JSONP_Util.testDoubleValue(parser, (double) 7e7); JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "object2", "object2"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* * Utitity method to parse JsonArrayWithAllTypesOfData */ private boolean parseAndVerify_JsonArrayWithAllTypesOfData(JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, ""); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testStringValue(parser, "string"); JSONP_Util.testIntegerValue(parser, 100); JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "emptyString", ""); JSONP_Util.testKeyStartArrayValue(parser, "emptyArray"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testKeyStartObjectValue(parser, "emptyObject"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStringValue(parser, "string", "string"); JSONP_Util.testKeyIntegerValue(parser, "number", 100); JSONP_Util.testKeyTrueValue(parser, "true"); JSONP_Util.testKeyFalseValue(parser, "false"); JSONP_Util.testKeyNullValue(parser, "null"); JSONP_Util.testKeyStartObjectValue(parser, "object"); JSONP_Util.testKeyStringValue(parser, "name", "value"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testKeyStartArrayValue(parser, "array"); JSONP_Util.testStringValue(parser, "one"); JSONP_Util.testStringValue(parser, "two"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "string"); JSONP_Util.testIntegerValue(parser, 100); JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStringValue(parser, "name", "value"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); JSONP_Util.testStringValue(parser, "one"); JSONP_Util.testStringValue(parser, "two"); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.testIntegerValue(parser, 100); JSONP_Util.testIntegerValue(parser, -100); JSONP_Util.testLongValue(parser, 9223372036854775807L); JSONP_Util.testLongValue(parser, -9223372036854775808L); JSONP_Util.testDoubleValue(parser, (double) 0.5); JSONP_Util.testDoubleValue(parser, (double) -0.5); JSONP_Util.testDoubleValue(parser, (double) 7e3); JSONP_Util.testDoubleValue(parser, (double) 7e+3); JSONP_Util.testDoubleValue(parser, (double) 9E3); JSONP_Util.testDoubleValue(parser, (double) 9E+3); JSONP_Util.testDoubleValue(parser, (double) 7e-3); JSONP_Util.testDoubleValue(parser, (double) 7E-3); JSONP_Util.testStringValue(parser, JSONP_Data.asciiCharacters); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } private boolean parseAndVerify_JsonHelloWorld(JsonParser parser) throws Exception { boolean pass = true; try { JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyStartObjectValue(parser, "greetingObj"); JSONP_Util.dumpLocation(parser); JSONP_Util.testKeyStringValue(parser, "hello", "world"); JSONP_Util.dumpLocation(parser); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.dumpLocation(parser); JSONP_Util.testKeyStartArrayValue(parser, "greetingArr"); JSONP_Util.dumpLocation(parser); JSONP_Util.testStringValue(parser, "hello"); JSONP_Util.dumpLocation(parser); JSONP_Util.testStringValue(parser, "world"); JSONP_Util.dumpLocation(parser); JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); JSONP_Util.dumpLocation(parser); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); JSONP_Util.dumpLocation(parser); int parseErrs = JSONP_Util.getParseErrs(); if (parseErrs != 0) { LOGGER.warning("There were " + parseErrs + " parser errors that occurred."); pass = false; } } catch (Exception e) { throw e; } return pass; } /* Tests */ /* * @testName: jsonParserTest1 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:133; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in "JSONP_Data.jsonObjectWithAllTypesOfData". Creates * the JsonParser via the API: * * JsonParser parser = Json.createParser(Reader) */ @Test public void jsonParserTest1() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info("-------------------------------------"); LOGGER.info("TEST CASE [Json.createParser(Reader)]"); LOGGER.info("-------------------------------------"); LOGGER.info("Create Reader from (JSONP_Data.jsonObjectWithAllTypesOfData)"); StringReader reader = new StringReader( JSONP_Data.jsonObjectWithAllTypesOfData); LOGGER.info("Create JsonParser from the Reader"); parser = Json.createParser(reader); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithAllTypesOfData)"); assertTrue(parseAndVerify_JsonObjectWithAllTypesOfData(parser), "jsonParserTest1 Failed"); } catch (Exception e) { fail("jsonParserTest1 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest2 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:417; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:166; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in "JSONP_Data.jsonObjectWithAllTypesOfData". Creates * the JsonParser via the API: * * JsonParser parser = * Json.createParserFactory(Map).createParser(JsonObject) */ @Test public void jsonParserTest2() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "----------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(JsonObject)]"); LOGGER.info( "----------------------------------------------------------------------------"); LOGGER.info( "Create JsonObject from (JSONP_Data.jsonObjectWithAllTypesOfData)"); JsonObject jsonObj = JSONP_Util .createJsonObjectFromString(JSONP_Data.jsonObjectWithAllTypesOfData); JSONP_Util.dumpJsonObject(jsonObj); LOGGER.info("Create JsonParser from the JsonObject"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(jsonObj); LOGGER.info("parser=" + parser); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithAllTypesOfData)"); assertTrue(parseAndVerify_JsonObjectWithAllTypesOfData(parser), "jsonParserTest2 Failed"); } catch (Exception e) { fail("jsonParserTest2 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest3 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:133; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in "JSONP_Data.jsonObjectWithLotsOfNestedObjectsData". * Creates the JsonParser via the API: * * JsonParser parser = Json.createParser(Reader) */ @Test public void jsonParserTest3() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info("-------------------------------------------"); LOGGER.info("TEST CASE [Json.createParser(Reader) again]"); LOGGER.info("-------------------------------------------"); LOGGER.info( "Create Reader from (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); StringReader reader = new StringReader( JSONP_Data.jsonObjectWithLotsOfNestedObjectsData); LOGGER.info("Create JsonParser from the Reader"); parser = Json.createParser(reader); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); assertTrue(parseAndVerify_JsonObjectWithLotsOfNestedObjectsData(parser), "jsonParserTest3 Failed"); } catch (Exception e) { fail("jsonParserTest3 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest4 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:166; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in "JSONP_Data.jsonObjectithLotsOfNestedObjectsData". * Creates the JsonParser via the API: * * JsonParser parser = * Json.createParserFactory(Map).createParser(JsonObject) */ @Test public void jsonParserTest4() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "-----------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(JsonObject object) again]"); LOGGER.info( "-----------------------------------------------------------------------------------------"); LOGGER.info( "Create JsonObject from (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); JsonObject jsonObj = JSONP_Util.createJsonObjectFromString( JSONP_Data.jsonObjectWithLotsOfNestedObjectsData); JSONP_Util.dumpJsonObject(jsonObj); LOGGER.info("Create JsonParser from the JsonObject"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(jsonObj); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); assertTrue(parseAndVerify_JsonObjectWithLotsOfNestedObjectsData(parser), "jsonParserTest4 Failed"); } catch (Exception e) { fail("jsonParserTest4 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest5 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:417; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:167; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonArray defined in "JSONP_Data.jsonArrayWithMultipleArraysData". Creates * the JsonParser via the API: * * JsonParser parser = * Json.createParserFactory(Map).createParser(JsonArray) */ @Test public void jsonParserTest5() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "---------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(JsonArray)]"); LOGGER.info( "---------------------------------------------------------------------------"); LOGGER.info( "Create JsonArray from (JSONP_Data.jsonArrayWithMultipleArraysData)"); JsonArray jsonArr = JSONP_Util.createJsonArrayFromString( JSONP_Data.jsonArrayWithMultipleArraysData); JSONP_Util.dumpJsonArray(jsonArr); LOGGER.info("Create JsonParser from the JsonArray"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(jsonArr); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonArrayWithMultipleArraysData)"); assertTrue(parseAndVerify_JsonArrayWithMultipleArraysData(parser), "jsonParserTest5 Failed"); } catch (Exception e) { fail("jsonParserTest5 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest6 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:172; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonArray defined in resource file "jsonArrayWithAllTypesOfData.json". * * Creates the JsonParser via the API: * * JsonParser parser = Json.createParser(InputStream) */ @Test public void jsonParserTest6() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info("------------------------------------------"); LOGGER.info("TEST CASE [Json.createParser(InputStream)]"); LOGGER.info("------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonArrayWithAllTypesOfData.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonArrayWithAllTypesOfData.json"); LOGGER.info("Create JsonParser from the InputStream"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonArrayWithAllTypesOfData.json)"); assertTrue(parseAndVerify_JsonArrayWithAllTypesOfData(parser), "jsonParserTest6 Failed"); } catch (Exception e) { fail("jsonParserTest6 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest7 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:417; JSONP:JAVADOC:164; JSONP:JAVADOC:235; JSONP:JAVADOC:237; * JSONP:JAVADOC:239; JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser with a configuration. Verifies * PARSING of the JsonObject defined in * "JSONP_Data.jsonObjectWithAllTypesOfData". Creates the JsonParser via the * following API * * JsonParser parser = Json.createParserFactory(Map).createParser(Reader) */ @Test public void jsonParserTest7() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "-------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(Reader)]"); LOGGER.info( "-------------------------------------------------------------------------"); LOGGER.info("Create a Reader from (JSONP_Data.jsonObjectWithAllTypesOfData)"); StringReader reader = new StringReader( JSONP_Data.jsonObjectWithAllTypesOfData); LOGGER.info("Create JsonParser using Reader and a configuration"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(reader); LOGGER.info("Call JsonParser.toString() to print the JsonObject"); parser.toString(); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithAllTypesOfData)"); assertTrue(parseAndVerify_JsonObjectWithAllTypesOfData(parser), "jsonParserTest7 Failed"); } catch (Exception e) { fail("jsonParserTest7 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest8 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; * JSONP:JAVADOC:167; JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser with a configuration. Verifies * PARSING of the JsonArray defined in * "JSONP_Data.jsonArrayWithLotsOfNestedObjectsData". Creates the JsonParser * via the following API * * JsonParser parser = Json.createParserFactory(Map).createParser(JsonArray) */ @Test public void jsonParserTest8() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "----------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(JsonArray)]"); LOGGER.info( "----------------------------------------------------------------------------"); LOGGER.info( "Create a JsonArray from (JSONP_Data.jsonArrayWithLotsOfNestedObjectsData)"); JsonArray jsonArr = JSONP_Util.createJsonArrayFromString( JSONP_Data.jsonArrayWithLotsOfNestedObjectsData); JSONP_Util.dumpJsonArray(jsonArr); LOGGER.info("Create JsonParser using JsonArray and a configuration"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(jsonArr); LOGGER.info("Call JsonParser.toString() to print the JsonObject"); parser.toString(); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonArrayWithLotsOfNestedObjectsData)"); assertTrue(parseAndVerify_JsonArrayWithLotsOfNestedObjectsData(parser), "jsonParserTest8 Failed"); } catch (Exception e) { fail("jsonParserTest8 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest9 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:417; JSONP:JAVADOC:167; JSONP:JAVADOC:235; JSONP:JAVADOC:237; * JSONP:JAVADOC:239; JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser with an empty configuration. * Verifies PARSING of the JsonArray defined in * "JSONP_Data.jsonArrayWithMultipleArraysData". Creates the JsonParser via * the following API * * JsonParser parser = Json.createParserFactory(Map).createParser(JsonArray) */ @Test public void jsonParserTest9() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "----------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(JsonArray)]"); LOGGER.info( "----------------------------------------------------------------------------"); LOGGER.info( "Create JsonArray from (JSONP_Data.jsonArrayWithMultipleArraysData)"); JsonArray jsonArr = JSONP_Util.createJsonArrayFromString( JSONP_Data.jsonArrayWithMultipleArraysData); JSONP_Util.dumpJsonArray(jsonArr); LOGGER.info("Create JsonParser using JsonArray and a configuration"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(jsonArr); LOGGER.info("Call JsonParser.toString() to print the JsonArray"); parser.toString(); LOGGER.info( "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonArrayWithMultipleArraysData)"); assertTrue(parseAndVerify_JsonArrayWithMultipleArraysData(parser), "jsonParserTest9 Failed"); } catch (Exception e) { fail("jsonParserTest9 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest10 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; * JSONP:JAVADOC:165; JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in resource file * "jsonObjectWithLotsOfNestedObjectsData.json". Creates the JsonParser via * the following API * * JsonParser parser = Json.createParserFactory(Map).createParser(InputStream) */ @Test public void jsonParserTest10() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream)]"); LOGGER.info( "------------------------------------------------------------------------------"); LOGGER.info("Create JsonParser using InputStream and a configuration"); InputStream istream = JSONP_Util.getInputStreamFromResource( "jsonObjectWithLotsOfNestedObjectsData.json"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream); LOGGER.info("Call JsonParser.toString() to print the JsonObject"); parser.toString(); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectWithLotsOfNestedObjectsData.json)"); assertTrue(parseAndVerify_JsonObjectWithLotsOfNestedObjectsData(parser), "jsonParserTest10 Failed"); } catch (Exception e) { fail("jsonParserTest10 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest11 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; JSONP:JAVADOC:375; * JSONP:JAVADOC:376; JSONP:JAVADOC:417; JSONP:JAVADOC:201; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonArray defined in resource file * "jsonArrayWithAllTypesOfDataUTF16BE.json". Use UTF-16BE encoding. * * Creates the JsonParser via the API: * * JsonParser parser = * Json.createParserFactory(Map).createParser(InputStream, Charset) */ @Test public void jsonParserTest11() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "--------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset)]"); LOGGER.info( "--------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonArrayWithAllTypesOfDataUTF16BE.json)"); InputStream istream = JSONP_Util.getInputStreamFromResource( "jsonArrayWithAllTypesOfDataUTF16BE.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-16BE"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_16BE); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonArrayWithAllTypesOfDataUTF16BE.json)"); assertTrue(parseAndVerify_JsonArrayWithAllTypesOfData(parser), "jsonParserTest11 Failed"); } catch (Exception e) { fail("jsonParserTest11 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest12 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:201; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonArray defined in resource file * "jsonArrayWithLotsOfNestedArraysData.json". Use UTF-8 encoding. * * Creates the JsonParser via the API: * * JsonParser parser = Json.createParserFactory(Map).createParser(InputStream, Charset) */ @Test public void jsonParserTest12() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "---------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset)]"); LOGGER.info( "---------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonArrayWithLotsOfNestedArraysData.json)"); InputStream istream = JSONP_Util.getInputStreamFromResource( "jsonArrayWithLotsOfNestedArraysData.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-8 and a configuration"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_8); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonArrayWithLotsOfNestedArraysData.json)"); assertTrue(parseAndVerify_JsonArrayWithLotsOfNestedArraysData(parser), "jsonParserTest12 Failed"); } catch (Exception e) { fail("jsonParserTest12 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest13 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:201; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in UTF-16LE encoding resource file * "jsonObjectWithAllTypesOfDataUTF16LE.json". * * Creates the JsonParser via the API: * * JsonParser parser = Json.createParserFactory(Map).createParser(InputStream, Charset) */ @Test public void jsonParserTest13() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "---------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset)]"); LOGGER.info( "---------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectWithAllTypesOfDataUTF16LE.json)"); InputStream istream = JSONP_Util.getInputStreamFromResource( "jsonObjectWithAllTypesOfDataUTF16LE.json"); LOGGER.info("Create JsonParser from the InputStream using UTF-16LE encoding"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_16LE); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectWithAllTypesOfDataUTF16LE.json)"); assertTrue(parseAndVerify_JsonObjectWithAllTypesOfData(parser), "jsonParserTest13 Failed"); } catch (Exception e) { fail("jsonParserTest13 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: jsonParserTest14 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:172; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:477; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in resource file "jsonHelloWorld.json.json". * * Creates the JsonParser via the API: * * JsonParser parser = Json.createParser(InputStream) */ @Test public void jsonParserTest14() { JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info("------------------------------------------"); LOGGER.info("TEST CASE [Json.createParser(InputStream)]"); LOGGER.info("------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonHelloWorld.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonHelloWorld.json"); LOGGER.info("Create JsonParser from the InputStream"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonHelloWorld.json)"); assertTrue(parseAndVerify_JsonHelloWorld(parser), "jsonParserTest14 Failed"); } catch (Exception e) { fail("jsonParserTest14 Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } } /* * @testName: parseUTFEncodedTests * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:201; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in resource files: * * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16.json * jsonObjectEncodingUTF16LE.json jsonObjectEncodingUTF16BE.json * jsonObjectEncodingUTF32LE.json jsonObjectEncodingUTF32BE.json * * Creates the JsonParser via the API: * * JsonParser parser = * Json.createParserFactory(Map).createParser(InputStream, Charset) * * For each supported encoding supported by JSON RFC parse the JsonObject and * verify we get the expected results. The Charset encoding is passed in as an * argument for each encoding type tested. */ @Test public void parseUTFEncodedTests() { boolean pass = true; JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "-----------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-8]"); LOGGER.info( "-----------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-8"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_8); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF8.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-8 encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-16]"); LOGGER.info( "------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-16"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_16); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-16 encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-16LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-16LE"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_16LE); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16LE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-16LE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-16BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-16BE"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_16BE); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16BE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-16BE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-32LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-32LE"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_32LE); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32LE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-32LE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "-------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-32BE]"); LOGGER.info( "-------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); LOGGER.info( "Create JsonParser from the InputStream with character encoding UTF-32BE"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(istream, JSONP_Util.UTF_32BE); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32BE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-32BE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } assertTrue(pass, "parseUTFEncodedTests Failed"); } /* * @testName: parseUTFEncodedTests2 * * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; * JSONP:JAVADOC:172; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; * JSONP:JAVADOC:375; JSONP:JAVADOC:376; * * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the * JsonObject defined in resource files and auto-detecting the encoding: * * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16LE.json * jsonObjectEncodingUTF16BE.json jsonObjectEncodingUTF32LE.json * jsonObjectEncodingUTF32BE.json * * Creates the JsonParser via the API: * * JsonParser parser = Json.createParser(InputStream) * * For each supported encoding supported by JSON RFC the above should * auto-detect the encoding and verify we get the expected results. */ @Test public void parseUTFEncodedTests2() { boolean pass = true; JsonParser parser = null; JsonParser.Event event = null; try { LOGGER.info( "-------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-8]"); LOGGER.info( "-------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); LOGGER.info( "Create JsonParser from the InputStream and auto-detect character encoding UTF-8"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF8.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-8 encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-16LE]"); LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); LOGGER.info( "Create JsonParser from the InputStream and auto-detect character encoding UTF-16LE"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16LE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-16LE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-16BE]"); LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); LOGGER.info( "Create JsonParser from the InputStream and auto-detect character encoding UTF-16BE"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16BE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-16BE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-32LE]"); LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); LOGGER.info( "Create JsonParser from the InputStream and auto-detect character encoding UTF-32LE"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32LE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-32LE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } try { LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-32BE]"); LOGGER.info( "----------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); InputStream istream = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); LOGGER.info( "Create JsonParser from the InputStream and auto-detect character encoding UTF-32BE"); parser = Json.createParser(istream); LOGGER.info( "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32BE.json)"); if (!parseAndVerify_JsonObjectUTF(parser)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing parsing of UTF-32BE encoding: " + e); } finally { try { parser.close(); } catch (Exception e) { } } assertTrue(pass, "parseUTFEncodedTests2 Failed"); } /* * @testName: jsonParserIsIntegralNumberTest * * @assertion_ids: JSONP:JAVADOC:120; JSONP:JAVADOC:133; JSONP:JAVADOC:375; * JSONP:JAVADOC:376; * * @test_Strategy: Test JsonParser.isIntegralNumber() method. */ @Test public void jsonParserIsIntegralNumberTest() { boolean pass = true; JsonParser parser = null; String jsonTestString = "[123, 12345.45]"; try { LOGGER.info("Create JsonParser"); parser = Json.createParser(new StringReader(jsonTestString)); // INTEGRAL NUMBER TEST JsonParser.Event event = JSONP_Util.getNextSpecificParserEvent(parser, JsonParser.Event.VALUE_NUMBER); // e=JsonParser.Event.VALUE_NUMBER JSONP_Util.dumpEventType(event); if (!JSONP_Util.assertEqualsJsonNumberType(parser.isIntegralNumber(), JSONP_Util.INTEGRAL)) pass = false; else { if (!JSONP_Util.assertEquals(123, parser.getInt())) pass = false; } // NON_INTEGRAL NUMBER TEST event = JSONP_Util.getNextSpecificParserEvent(parser, JsonParser.Event.VALUE_NUMBER); // e=JsonParser.Event.VALUE_NUMBER JSONP_Util.dumpEventType(event); if (!JSONP_Util.assertEqualsJsonNumberType(parser.isIntegralNumber(), JSONP_Util.NON_INTEGRAL)) pass = false; else { if (!JSONP_Util.assertEquals(12345.45, parser.getBigDecimal().doubleValue())) pass = false; } } catch (Exception e) { fail("jsonParserIsIntegralNumberTest Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserIsIntegralNumberTest Failed"); } private boolean tripIllegalStateException(JsonParser parser, JsonParser.Event event) { boolean pass = true; // Check in case event is null if (event == null) { LOGGER.warning("event is null - unexpected."); return false; } LOGGER.info("Event=" + JSONP_Util.getEventTypeString(event)); LOGGER.info("Testing call to JsonParser.getString()"); if (event != JsonParser.Event.VALUE_STRING && event != JsonParser.Event.VALUE_NUMBER && event != JsonParser.Event.KEY_NAME) { try { LOGGER.info("Trip IllegalStateException by calling JsonParser.getString()"); String string = parser.getString(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } } else { LOGGER.info("No testing for IllegalStateException for this scenario."); } LOGGER.info("Testing call to JsonParser.isIntegralNumber()"); if (event != JsonParser.Event.VALUE_NUMBER) { try { LOGGER.info( "Trip IllegalStateException by calling JsonParser.isIntegralNumber()"); boolean numberType = parser.isIntegralNumber(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } } else { LOGGER.info("No testing for IllegalStateException for this scenario."); } LOGGER.info("Testing call to JsonParser.getBigDecimal()"); if (event != JsonParser.Event.VALUE_NUMBER) { try { LOGGER.info( "Trip IllegalStateException by calling JsonParser.getBigDecimal()"); BigDecimal number = parser.getBigDecimal(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } } else { LOGGER.info("No testing for IllegalStateException for this scenario."); } LOGGER.info("Testing call to JsonParser.getInt()"); if (event != JsonParser.Event.VALUE_NUMBER) { try { LOGGER.info("Trip IllegalStateException by calling JsonParser.getInt()"); int number = parser.getInt(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } } else { LOGGER.info("No testing for IllegalStateException for this scenario."); } LOGGER.info("Testing call to JsonParser.getLong()"); if (event != JsonParser.Event.VALUE_NUMBER) { try { LOGGER.info("Trip IllegalStateException by calling JsonParser.getLong()"); long number = parser.getLong(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } } else { LOGGER.info("No testing for IllegalStateException for this scenario."); } return pass; } /* * @testName: jsonParserIllegalExceptionTests * * @assertion_ids: JSONP:JAVADOC:121; JSONP:JAVADOC:123; JSONP:JAVADOC:236; * JSONP:JAVADOC:238; JSONP:JAVADOC:240; * * @test_Strategy: Test JsonParser exception conditions. Trip the following * exceptions: * * java.lang.IllegalStateException */ @Test public void jsonParserIllegalExceptionTests() { boolean pass = true; JsonParser parser = null; String jsonTestString = "[\"string\",100,false,null,true,{\"foo\":\"bar\"}]"; try { LOGGER.info("Create JsonParser"); parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) .createParser(new StringReader(jsonTestString)); JsonParser.Event event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.START_ARRAY */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_STRING */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_NUMBER */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_FALSE */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_NULL */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_TRUE */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.START_OBJECT */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.KEY_NAME */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_STRING */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.END_OBJECT */ if (!tripIllegalStateException(parser, event)) pass = false; event = JSONP_Util .getNextParserEvent(parser); /* e=JsonParser.Event.END_ARRAY */ if (!tripIllegalStateException(parser, event)) pass = false; } catch (Exception e) { fail("jsonParserIllegalExceptionTests Failed: ", e); } finally { try { parser.close(); } catch (Exception e) { } } assertTrue(pass, "jsonParserIllegalExceptionTests Failed"); } /* * @testName: jsonParserIOErrorTests * * @assertion_ids: JSONP:JAVADOC:207; JSONP:JAVADOC:389; JSONP:JAVADOC:415; * * @test_Strategy: Tests for JsonException for testable i/o errors. * */ @SuppressWarnings("ConvertToTryWithResources") @Test public void jsonParserIOErrorTests() { boolean pass = true; String jsonText = "{\"name1\":\"value1\",\"name2\":\"value2\"}"; // Trip JsonException if there is an i/o error on // Json.createParser(InputStream) try { LOGGER.info( "Trip JsonException if there is an i/o error on Json.createParser(InputStream)."); LOGGER.info("Parsing " + jsonText); InputStream is = JSONP_Util.getInputStreamFromString(jsonText); MyBufferedInputStream mbi = new MyBufferedInputStream(is, true); LOGGER.info("Calling Json.createParser(InputStream)"); JsonParser parser = Json.createParser(mbi); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException if there is an i/o error on JsonParser.next() try { LOGGER.info( "Trip JsonException if there is an i/o error on JsonParser.next()."); LOGGER.info("Parsing " + jsonText); InputStream is = JSONP_Util.getInputStreamFromString(jsonText); MyBufferedInputStream mbi = new MyBufferedInputStream(is, true); JsonParser parser = Json.createParser(mbi); LOGGER.info("Calling JsonParser.next()"); parser.next(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException if there is an i/o error on JsonParser.close() try { LOGGER.info( "Trip JsonException if there is an i/o error on JsonParser.close()."); LOGGER.info("Parsing " + jsonText); InputStream is = JSONP_Util.getInputStreamFromString(jsonText); MyBufferedInputStream mbi = new MyBufferedInputStream(is); JsonParser parser = Json.createParser(mbi); mbi.setThrowIOException(true); LOGGER.info("Calling JsonParser.close()"); parser.close(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonParserIOErrorTests Failed"); } /* * @testName: jsonParserExceptionTests * * @assertion_ids: JSONP:JAVADOC:390; JSONP:JAVADOC:391; * * @test_Strategy: Tests for the following exception test cases: * * JsonParsingException - if incorrect JSON is encountered while advancing * parser to next state NoSuchElementException - if there are no more parsing * states * */ @Test public void jsonParserExceptionTests() { boolean pass = true; // Trip JsonParsingException for JsonParser.next() if incorrect JSON is // encountered try { LOGGER.info( "Trip JsonParsingException for JsonParser.next() if incorrect JSON is encountered"); InputStream is = JSONP_Util.getInputStreamFromString("}{"); JsonParser parser = Json.createParser(is); parser.next(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip NoSuchElementException for JsonParser.next() if no more parsing // states try { LOGGER.info( "Trip NoSuchElementException for JsonParser.next() if no more parsing states"); InputStream is = JSONP_Util.getInputStreamFromString("{}"); JsonParser parser = Json.createParser(is); parser.next(); // Event -> START_OBJECT { parser.next(); // Event -> END_OBJECT } parser.next(); // Event -> NoSuchElementException should be thrown LOGGER.warning("Did not get expected NoSuchElementException"); pass = false; } catch (NoSuchElementException e) { LOGGER.info("Caught expected NoSuchElementException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonParserExceptionTests Failed"); } /* * @testName: invalidLiteralNamesTest * * @assertion_ids: JSONP:JAVADOC:133; JSONP:JAVADOC:390; * * @test_Strategy: This test trips various JsonParsingException conditions * when parsing an uppercase literal name that must be lowercase per JSON RFC * for the literal values (true, false or null). * */ @Test public void invalidLiteralNamesTest() { boolean pass = true; // Trip JsonParsingException for JsonParser.next() if invalid liternal TRUE // instead of true try { LOGGER.info( "Trip JsonParsingException for JsonParser.next() if invalid liternal TRUE instead of true."); LOGGER.info("Reading " + "[TRUE]"); JsonParser parser = Json.createParser(new StringReader("[TRUE]")); parser.next(); // Event -> START_OBJECT { parser.next(); // Event -> JsonParsingException (invalid literal TRUE) LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonParser.next() if invalid liternal FALSE // instead of false try { LOGGER.info( "Trip JsonParsingException for JsonParser.next() if invalid liternal FALSE instead of false."); LOGGER.info("Reading " + "[FALSE]"); JsonParser parser = Json.createParser(new StringReader("[FALSE]")); parser.next(); // Event -> START_OBJECT { parser.next(); // Event -> JsonParsingException (invalid literal FALSE) LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonParser.next() if invalid liternal NULL // instead of null try { LOGGER.info( "Trip JsonParsingException for JsonParser.next() if invalid liternal NULL instead of null."); LOGGER.info("Reading " + "[NULL]"); JsonParser parser = Json.createParser(new StringReader("[NULL]")); parser.next(); // Event -> START_OBJECT { parser.next(); // Event -> JsonParsingException (invalid literal NULL) LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "invalidLiteralNamesTest Failed"); } /* * @testName: jsonParser11Test * * @assertion_ids: JSONP:JAVADOC:673; JSONP:JAVADOC:674; JSONP:JAVADOC:675; * JSONP:JAVADOC:676; JSONP:JAVADOC:677; JSONP:JAVADOC:678; JSONP:JAVADOC:679; * JSONP:JAVADOC:680; JSONP:JAVADOC:583; JSONP:JAVADOC:584; JSONP:JAVADOC:585; * JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; JSONP:JAVADOC:662; * JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; JSONP:JAVADOC:666; * JSONP:JAVADOC:667; * * @test_Strategy: Tests JsonParser API methods added in JSON-P 1.1. */ @Test public void jsonParser11Test() { Parser parserTest = new Parser(); final TestResult result = parserTest.test(); result.eval(); } /* * @testName: jsonParserCurrentEvent * * @assertion_ids: JSONP:JAVADOC:683; * * @test_Strategy: Tests JsonParser API methods added in JSON-P 2.1. */ @Test public void jsonParserCurrentEvent() { try (JsonParser parser = Json.createParser(new StringReader("{\"a\":\"v\",\"b\":\"w\"}"))) { assertNull(parser.currentEvent()); int events = 0; while (parser.hasNext()) { Event next = parser.next(); assertNotNull(next); assertEquals(next, parser.currentEvent()); assertEquals(parser.currentEvent(), parser.currentEvent()); events++; } assertEquals(6, events); } } } Parser.java000066400000000000000000000662441451447132700336370ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonparsertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonparsertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.io.StringReader; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Stream; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonStructure; import jakarta.json.JsonValue; import jakarta.json.stream.JsonParser; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: {@link JsonParser} API * methods added in JSON-P 1.1. */ public class Parser { private static final Logger LOGGER = Logger.getLogger(Parser.class.getName()); /** Tests input data with various JsonValue instances. */ private static final JsonValue[] VALUES = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.STR_VALUE), // Non JsonObject with String SimpleValues.toJsonValue(SimpleValues.INT_VALUE), // Non JsonObject with int SimpleValues.toJsonValue(SimpleValues.LNG_VALUE), // Non JsonObject with long SimpleValues.toJsonValue(SimpleValues.DBL_VALUE), // Non JsonObject with double SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), // Non JsonObject with boolean SimpleValues.toJsonValue(SimpleValues.BDC_VALUE), // Non JsonObject with BigDecimal SimpleValues.toJsonValue(SimpleValues.BIN_VALUE), // Non JsonObject with BigInteger SimpleValues.createSimpleObjectStr(), // JsonObject with String SimpleValues.createSimpleObjectInt(), // JsonObject with int SimpleValues.createSimpleObjectBool(), // JsonObject with boolean SimpleValues.createSimpleObjectObject(), // JsonObject with JsonObject SimpleValues.createEmptyArrayWithStr(), // JsonArray with String SimpleValues.createEmptyArrayWithInt(), // JsonArray with int SimpleValues.createEmptyArrayWithBool(), // JsonArray with boolean SimpleValues.createEmptyArrayWithObject() // JsonArray with JsonObject }; // /** Tests input data with simple JsonValue instances. */ // private static final JsonValue[] SIMPLE_VALUES = new JsonValue[] { // toJsonValue(STR_VALUE), // Non JsonObject with String // toJsonValue(INT_VALUE), // Non JsonObject with int // toJsonValue(LNG_VALUE), // Non JsonObject with long // toJsonValue(BOOL_VALUE), // Non JsonObject with boolean // toJsonValue(BDC_VALUE), // Non JsonObject with BigDecimal // toJsonValue(BIN_VALUE) // Non JsonObject with BigInteger // }; /** Tests input data with compound JsonValue instances (object or array). */ private static final JsonStructure[] COMPOUND_VALUES = new JsonStructure[] { SimpleValues.createSimpleObjectStr(), // JsonObject with String SimpleValues.createSimpleObjectInt(), // JsonObject with int SimpleValues.createSimpleObjectBool(), // JsonObject with boolean SimpleValues.createSimpleObjectObject(), // JsonObject with JsonObject SimpleValues.createEmptyArrayWithStr(), // JsonArray with String SimpleValues.createEmptyArrayWithInt(), // JsonArray with int SimpleValues.createEmptyArrayWithBool(), // JsonArray with boolean SimpleValues.createEmptyArrayWithObject() // JsonArray with JsonObject }; /** Tests input data with empty JsonObject and JsonArray instances. */ private static final JsonStructure[] EMPTY_VALUES = new JsonStructure[] { SimpleValues.createEmptyObject(), // Empty JsonObject SimpleValues.createEmptyArray() // Empty JsonArray }; /** Tests input data with JsonObject instances. */ private static final JsonObject[] OBJ_VALUES = new JsonObject[] { SimpleValues.createSimpleObjectStr(), // JsonObject with String SimpleValues.createSimpleObjectInt(), // JsonObject with int SimpleValues.createSimpleObjectBool(), // JsonObject with boolean SimpleValues.createSimpleObjectObject(), // JsonObject with JsonObject SimpleValues.createSimpleObjectWithStr() // JsonObject with default value (String) and // another String }; /** Tests input data with non JsonObject instances. */ private static final JsonValue[] NON_OBJ_VALUES = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.STR_VALUE), // Non JsonObject with String SimpleValues.toJsonValue(SimpleValues.INT_VALUE), // Non JsonObject with int SimpleValues.toJsonValue(SimpleValues.LNG_VALUE), // Non JsonObject with long SimpleValues.toJsonValue(SimpleValues.DBL_VALUE), // Non JsonObject with double SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), // Non JsonObject with boolean SimpleValues.toJsonValue(SimpleValues.BDC_VALUE), // Non JsonObject with BigDecimal SimpleValues.toJsonValue(SimpleValues.BIN_VALUE), // Non JsonObject with BigInteger SimpleValues.createEmptyArrayWithStr(), // JsonArray with String SimpleValues.createEmptyArrayWithInt(), // JsonArray with int SimpleValues.createEmptyArrayWithBool(), // JsonArray with boolean SimpleValues.createEmptyArrayWithObject() // JsonArray with JsonObject }; /** Tests input data with JsonArray instances. */ private static final JsonArray[] ARRAY_VALUES = new JsonArray[] { SimpleValues.createEmptyArrayWithStr(), // JsonArray with String SimpleValues.createEmptyArrayWithInt(), // JsonArray with int SimpleValues.createEmptyArrayWithBool(), // JsonArray with boolean SimpleValues.createEmptyArrayWithObject() // JsonArray with JsonObject }; /** Tests input data with non JsonArray instances. */ private static final JsonValue[] NON_ARRAY_VALUES = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.STR_VALUE), // Non JsonObject with String SimpleValues.toJsonValue(SimpleValues.INT_VALUE), // Non JsonObject with int SimpleValues.toJsonValue(SimpleValues.LNG_VALUE), // Non JsonObject with long SimpleValues.toJsonValue(SimpleValues.DBL_VALUE), // Non JsonObject with double SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), // Non JsonObject with boolean SimpleValues.toJsonValue(SimpleValues.BDC_VALUE), // Non JsonObject with BigDecimal SimpleValues.toJsonValue(SimpleValues.BIN_VALUE), // Non JsonObject with BigInteger SimpleValues.createSimpleObjectStr(), // JsonObject with String SimpleValues.createSimpleObjectInt(), // JsonObject with int SimpleValues.createSimpleObjectBool(), // JsonObject with boolean SimpleValues.createSimpleObjectObject() // JsonObject with JsonObject }; /** * Creates an instance of {@link JsonParser} API methods added in JSON-P 1.1 * test. */ Parser() { super(); } /** * Test {@link JsonParser} API methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonParser API methods added in JSON-P 1.1."); LOGGER.info("JsonParser API methods added in JSON-P 1.1."); testGetObject(result); testGetNonObject(result); testGetArray(result); testGetNonArray(result); testGetValue(result); testGetIllegalValue(result); testGetObjectStream(result); testGetNonObjectStream(result); testGetArrayStream(result); testGetNonArrayStream(result); testGetValueStream(result); testGetCompoundValueStream(result); testSkipArray(result); testSkipNonArray(result); testSkipObject(result); testSkipNonObject(result); return result; } /** * Test {@code JsonParser getObject()} method on JSON object values. */ private void testGetObject(final TestResult result) { for (JsonObject value : OBJ_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getObject() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); JsonObject out = parser.getObject(); if (operationFailed(value, out)) { result.fail("getObject()", "Output value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(value)); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("getObject()", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code JsonParser getObject()} method on non JSON object values. */ private void testGetNonObject(final TestResult result) { for (JsonValue value : NON_OBJ_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getObject() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.getObject(); result.fail("getObject()", "Calling method on non object value shall throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info(" Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("getObject()", "Calling method on non object value shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonParser getArray()} method on JSON array values. */ private void testGetArray(final TestResult result) { for (JsonArray value : ARRAY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getArray() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); JsonArray out = parser.getArray(); if (operationFailed(value, out)) { result.fail("getArray()", "Output value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(value)); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("getArray()", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code JsonParser getArray()} method on non JSON object values. */ private void testGetNonArray(final TestResult result) { for (JsonValue value : NON_ARRAY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getArray() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.getArray(); result.fail("getArray()", "Calling method on non array value shall throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info(" Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("getArray()", "Calling method on non array value shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonParser getValue()} method on common JSON values. */ private void testGetValue(final TestResult result) { for (JsonValue value : VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getValue() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); JsonValue out = parser.getValue(); if (operationFailed(value, out)) { result.fail("getValue()", "Output value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(value)); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("getValue()", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code JsonParser getValue()} method on END_OBJECT and END_ARRAY * lexical elements. */ private void testGetIllegalValue(final TestResult result) { for (JsonValue value : EMPTY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getValue() on 2nd lexical element of " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); // Skip to START ELEMENT parser.next(); // Skip to END ELEMENT parser.getValue(); result.fail("getValue()", "Calling method on END_OBJECT and END_ARRAY lexical elements shall throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info(" Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("getValue()", "Calling method on END_OBJECT and END_ARRAY lexical elements shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonParser getObjectStream()} method on JSON object values. */ private void testGetObjectStream(final TestResult result) { for (JsonObject value : OBJ_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getObjectStream() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); Stream> out = parser.getObjectStream(); if (operationFailed(value, out)) { result.fail("getObjectStream()", "Output Stream shall contain " + JsonAssert.valueToString(value)); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("getObjectStream()", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code JsonParser getObjectStream()} method on non JSON object values. */ private void testGetNonObjectStream(final TestResult result) { for (JsonValue value : NON_OBJ_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getObjectStream() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.getObjectStream(); result.fail("getObjectStream()", "Calling method on non object value shall throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info(" Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("getObjectStream()", "Calling method on non object value shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonParser getArrayStream()} method on JSON array values. */ private void testGetArrayStream(final TestResult result) { for (JsonArray value : ARRAY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getArrayStream() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); Stream out = parser.getArrayStream(); if (operationFailed(value, out)) { result.fail("getArrayStream()", "Output Stream shall contain " + JsonAssert.valueToString(value)); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("getArrayStream()", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code JsonParser getArrayStream()} method on non JSON array values. */ private void testGetNonArrayStream(final TestResult result) { for (JsonValue value : NON_ARRAY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getArrayStream() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.getArrayStream(); result.fail("getArrayStream()", "Calling method on non array value shall throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info(" Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("getArrayStream()", "Calling method on non array value shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonParser getValueStream()} method on simple JSON values in * document root. */ private void testGetValueStream(final TestResult result) { for (final JsonValue value : VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getValueStream() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { final Stream outStream = parser.getValueStream(); int count = 0; for (final Iterator i = outStream.iterator(); i.hasNext();) { final JsonValue out = i.next(); if (operationFailed(value, out)) { result.fail("getValueStream()", "Output Stream value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(value)); } count++; } if (count != 1) { LOGGER.info(" Output Stream contains " + Integer.toString(count) + " values, not 1"); result.fail("getValueStream()", "Output Stream does not contain exactly 1 JSON value"); } } } } /** * Test {@code JsonParser getValueStream()} method inside compound JSON values * in document root. */ private void testGetCompoundValueStream(final TestResult result) { for (final JsonValue value : COMPOUND_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - getValueStream() inside " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.getValueStream(); result.fail("getValueStream()", "Calling method on non object value shall throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info(" Expected exception: " + e.getMessage()); } catch (Throwable t) { result.fail("getValueStream()", "Calling method on non object value shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonParser skipArray()} method inside JSON array values. * Expected result: Parser shall advance to the end of the stream after * skipping an array which is the only value in the stream. */ private void testSkipArray(final TestResult result) { for (final JsonArray value : ARRAY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - skipArray() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.skipArray(); if (parser.hasNext()) { result.fail("skipArray()", "Parser did not davance to the end of the array"); } } catch (Throwable t) { LOGGER.info( " " + t.getClass().getSimpleName() + ": " + t.getMessage()); result.fail("skipArray()", t.getClass().getSimpleName() + ": " + t.getMessage()); } } } /** * Test {@code JsonParser skipArray()} method outside JSON array values. * Expected result: Parser shall not advance anywhere when called outside an * array. Whole value shall match after {@code skipArray()} call because * nothing shall happen in it. */ private void testSkipNonArray(final TestResult result) { for (final JsonValue value : NON_ARRAY_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - skipArray() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.skipArray(); final JsonValue out = parser.getValue(); if (operationFailed(value, out)) { result.fail("skipArray()", "Output value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(value) + " even after skipArray()"); } } catch (Throwable t) { LOGGER.info( " " + t.getClass().getSimpleName() + ": " + t.getMessage()); result.fail("skipArray()", t.getClass().getSimpleName() + ": " + t.getMessage()); } } } /** * Test {@code JsonParser skipObject()} method inside JSON object values. * Expected result: Parser shall advance to the end of the stream after * skipping an object which is the only value in the stream. */ private void testSkipObject(final TestResult result) { for (final JsonObject value : OBJ_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - skipObject() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.skipObject(); if (parser.hasNext()) { result.fail("skipObject()", "Parser did not davance to the end of the object"); } } catch (Throwable t) { LOGGER.info( " " + t.getClass().getSimpleName() + ": " + t.getMessage()); result.fail("skipObject()", t.getClass().getSimpleName() + ": " + t.getMessage()); } } } /** * Test {@code JsonParser skipObject()} method outside JSON object values. * Expected result: Parser shall not advance anywhere when called outside an * object. Whole value shall match after {@code skipObject()} call because * nothing shall happen in it. */ private void testSkipNonObject(final TestResult result) { for (final JsonValue value : NON_OBJ_VALUES) { final String data = SimpleValues.jsonData(value); LOGGER.info(" - skipObject() on " + data); final StringReader strReader = new StringReader(data); try (final JsonParser parser = Json.createParser(strReader)) { parser.next(); parser.skipObject(); final JsonValue out = parser.getValue(); if (operationFailed(value, out)) { result.fail("skipObject()", "Output value " + JsonAssert.valueToString(out) + " shall be " + JsonAssert.valueToString(value) + " even after skipObject()"); } } catch (Throwable t) { LOGGER.info( " " + t.getClass().getSimpleName() + ": " + t.getMessage()); result.fail("skipObject()", t.getClass().getSimpleName() + ": " + t.getMessage()); } } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { LOGGER.info(" Checking " + JsonAssert.valueToString(out)); return out == null || !JsonAssert.assertEquals(check, out); } /** * Operation result check. * * @param check * Expected Stream content. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonObject check, final Stream> out) { // Operation failed for null. if (out == null) { LOGGER.info(" Output is null"); return true; } final Set keys = new HashSet<>(check.size()); // Clone key Set for (final String key : check.keySet()) { keys.add(key); } for (final Iterator> i = out.iterator(); i .hasNext();) { final Map.Entry item = i.next(); final JsonValue checkValue = check.get(item.getKey()); LOGGER.info(" Checking " + JsonAssert.valueToString(item.getValue())); // Operation failed if values with the same key are not equal. if (!item.getValue().equals(checkValue)) { LOGGER.info(" check: " + JsonAssert.valueToString(checkValue) + " stream: " + JsonAssert.valueToString(checkValue)); return true; } keys.remove(item.getKey()); } // Operation failed if some unmatched keys remain in the set. return !keys.isEmpty(); } /** * Operation result check. * * @param check * Expected Stream content. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonArray check, final Stream out) { // Operation failed for null. if (out == null) { LOGGER.info(" Output is null"); return true; } final Iterator ci = check.iterator(); final Iterator oi = out.iterator(); // To exit cycle, at least one of iterators does not have next value. while (ci.hasNext() && oi.hasNext()) { final JsonValue checkValue = ci.next(); final JsonValue outValue = oi.next(); LOGGER.info(" Checking " + JsonAssert.valueToString(outValue)); if (!checkValue.equals(outValue)) { LOGGER.info(" check: " + JsonAssert.valueToString(checkValue) + " stream: " + JsonAssert.valueToString(checkValue)); return true; } } // Check still has values, something was missing in output. if (ci.hasNext()) { LOGGER.info(" Output contains less values than expected"); return true; } // Output still has values, it contains more than expected. if (oi.hasNext()) { LOGGER.info(" Output contains more values than expected"); return true; } return false; } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonreaderfactorytests/000077500000000000000000000000001451447132700331415ustar00rootroot00000000000000ClientTests.java000066400000000000000000000247241451447132700361770ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonreaderfactorytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonreaderfactorytests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import java.io.*; import java.util.Map; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonReaderFactoryTest1 * * @assertion_ids: JSONP:JAVADOC:419; JSONP:JAVADOC:449; JSONP:JAVADOC:185; * JSONP:JAVADOC:459; * * @test_Strategy: Tests the JsonReaderFactory API. * * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); * JsonReader reader1 = readerFactory.createReader(Reader) JsonReader reader2 * = readerFactory.createReader(Reader) */ @Test public void jsonReaderFactoryTest1() { boolean pass = true; JsonReader reader1 = null; JsonReader reader2 = null; JsonObject jsonObject = null; String jsonObjectText = "{\"foo\":\"bar\"}"; try { LOGGER.info("Create JsonReaderFactory with Map with EMPTY config"); JsonReaderFactory readerFactory = Json .createReaderFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = readerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("--------------------------------------------------"); LOGGER.info("TEST CASE [JsonReaderFactory.createReader(Reader)]"); LOGGER.info("--------------------------------------------------"); LOGGER.info("Create 1st JsonReader using JsonReaderFactory"); reader1 = readerFactory.createReader(new StringReader(jsonObjectText)); if (reader1 == null) { LOGGER.warning("ReaderFactory failed to create reader1"); pass = false; } else { jsonObject = reader1.readObject(); reader1.close(); if (!JSONP_Util.assertEquals(jsonObject.size(), 1) || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) pass = false; } LOGGER.info("Create 2nd JsonReader using JsonReaderFactory"); reader2 = readerFactory.createReader(new StringReader(jsonObjectText)); if (reader2 == null) { LOGGER.warning("ReaderFactory failed to create reader2"); pass = false; } else { jsonObject = reader2.readObject(); reader2.close(); if (!JSONP_Util.assertEquals(jsonObject.size(), 1) || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) pass = false; } } catch (Exception e) { fail("jsonReaderFactoryTest1 Failed: ", e); } assertTrue(pass, "jsonReaderFactoryTest1 Failed"); } /* * @testName: jsonReaderFactoryTest2 * * @assertion_ids: JSONP:JAVADOC:420; JSONP:JAVADOC:449; JSONP:JAVADOC:185; * JSONP:JAVADOC:459; * * @test_Strategy: Tests the JsonReaderFactory API. * * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); * JsonReader reader1 = readerFactory.createReader(InputStream, Charset) * JsonReader reader2 = readerFactory.createReader(InputStream, Charset) * * Create reader with both UTF-8 and UTF-16BE. */ @Test public void jsonReaderFactoryTest2() { boolean pass = true; JsonReader reader1 = null; JsonReader reader2 = null; JsonObject jsonObject = null; String jsonObjectText = "{\"foo\":\"bar\"}"; try { LOGGER.info("Create JsonReaderFactory with Map with EMPTY config"); JsonReaderFactory readerFactory = Json .createReaderFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = readerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info( "----------------------------------------------------------------"); LOGGER.info( "TEST CASE [JsonReaderFactory.createReader(InputStream, Charset)]"); LOGGER.info( "----------------------------------------------------------------"); LOGGER.info( "Create 1st JsonReader using JsonReaderFactory with UTF-8 encoding"); InputStream is1 = JSONP_Util.getInputStreamFromString(jsonObjectText); reader1 = readerFactory.createReader(is1, JSONP_Util.UTF_8); if (reader1 == null) { LOGGER.warning("ReaderFactory failed to create reader1"); pass = false; } else { jsonObject = reader1.readObject(); reader1.close(); if (!JSONP_Util.assertEquals(jsonObject.size(), 1) || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) pass = false; } LOGGER.info( "Create 2nd JsonReader using JsonReaderFactory with UTF-8 encoding"); InputStream is2 = JSONP_Util.getInputStreamFromString(jsonObjectText); reader2 = readerFactory.createReader(is2, JSONP_Util.UTF_8); if (reader2 == null) { LOGGER.warning("ReaderFactory failed to create reader2"); pass = false; } else { jsonObject = reader2.readObject(); reader2.close(); if (!JSONP_Util.assertEquals(jsonObject.size(), 1) || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) pass = false; } } catch (Exception e) { fail("jsonReaderFactoryTest2 Failed: ", e); } assertTrue(pass, "jsonReaderFactoryTest2 Failed"); } /* * @testName: jsonReaderFactoryTest3 * * @assertion_ids: JSONP:JAVADOC:429; JSONP:JAVADOC:449; JSONP:JAVADOC:185; * JSONP:JAVADOC:459; * * @test_Strategy: Tests the JsonReaderFactory API. * * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); * JsonReader reader1 = readerFactory.createReader(InputStream) JsonReader * reader2 = readerFactory.createReader(InputStream) */ @Test public void jsonReaderFactoryTest3() { boolean pass = true; JsonReader reader1 = null; JsonReader reader2 = null; JsonObject jsonObject = null; String jsonObjectText = "{\"foo\":\"bar\"}"; try { LOGGER.info("Create JsonReaderFactory with Map with EMPTY config"); JsonReaderFactory readerFactory = Json .createReaderFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = readerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-------------------------------------------------------"); LOGGER.info("TEST CASE [JsonReaderFactory.createReader(InputStream)]"); LOGGER.info("-------------------------------------------------------"); LOGGER.info("Create 1st JsonReader using JsonReaderFactory"); InputStream is1 = JSONP_Util.getInputStreamFromString(jsonObjectText); reader1 = readerFactory.createReader(is1); if (reader1 == null) { LOGGER.warning("ReaderFactory failed to create reader1"); pass = false; } else { jsonObject = reader1.readObject(); reader1.close(); if (!JSONP_Util.assertEquals(jsonObject.size(), 1) || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) pass = false; } LOGGER.info("Create 2nd JsonReader using JsonReaderFactory"); InputStream is2 = JSONP_Util.getInputStreamFromString(jsonObjectText); reader2 = readerFactory.createReader(is2); if (reader2 == null) { LOGGER.warning("ReaderFactory failed to create reader2"); pass = false; } else { jsonObject = reader2.readObject(); reader2.close(); if (!JSONP_Util.assertEquals(jsonObject.size(), 1) || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) pass = false; } } catch (Exception e) { fail("jsonReaderFactoryTest3 Failed: ", e); } assertTrue(pass, "jsonReaderFactoryTest3 Failed"); } /* * @testName: jsonReaderFactoryTest4 * * @assertion_ids: JSONP:JAVADOC:449; JSONP:JAVADOC:459; * * @test_Strategy: Tests the JsonReaderFactory API. * * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); * Map config = JsonReaderFactory.getConfigInUse(); * * Test for the following 3 scenarios: 1) no supported provider property * (empty config) 2) non supported provider property */ @Test public void jsonReaderFactoryTest4() { boolean pass = true; JsonReaderFactory readerFactory; Map config; try { LOGGER.info("----------------------------------------------"); LOGGER.info("Test scenario1: no supported provider property"); LOGGER.info("----------------------------------------------"); LOGGER.info("Create JsonReaderFactory with Map with EMPTY config"); readerFactory = Json.createReaderFactory(JSONP_Util.getEmptyConfig()); config = readerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-----------------------------------------------"); LOGGER.info("Test scenario2: non supported provider property"); LOGGER.info("-----------------------------------------------"); LOGGER.info("Create JsonReaderFactory with Map with FOO config"); readerFactory = Json.createReaderFactory(JSONP_Util.getFooConfig()); config = readerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; } catch (Exception e) { fail("jsonReaderFactoryTest4 Failed: ", e); } assertTrue(pass, "jsonReaderFactoryTest4 Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonreadertests/000077500000000000000000000000001451447132700315515ustar00rootroot00000000000000ClientTests.java000066400000000000000000003521721451447132700346100ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonreadertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonreadertests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Data; import ee.jakarta.tck.jsonp.common.JSONP_Util; import ee.jakarta.tck.jsonp.common.MyBufferedInputStream; import ee.jakarta.tck.jsonp.common.MyBufferedReader; import java.io.*; import java.util.*; import java.util.logging.Logger; import jakarta.json.*; import jakarta.json.stream.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; // $Id$ public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Utility Methods */ /* * compareJsonObjectForUTFEncodedTests */ private boolean compareJsonObjectForUTFEncodedTests(JsonObject jsonObject) { boolean pass = true; LOGGER.info("Comparing JsonObject values to expected results."); String expString = "stringValue"; String actString = jsonObject.getJsonString("stringName").getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; JsonObject actObject = jsonObject.getJsonObject("objectName"); expString = "bar"; actString = actObject.getJsonString("foo").getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; JsonArray actArray = jsonObject.getJsonArray("arrayName"); if (!JSONP_Util.assertEquals(1, actArray.getJsonNumber(0).intValue()) || !JSONP_Util.assertEquals(2, actArray.getJsonNumber(1).intValue()) || !JSONP_Util.assertEquals(3, actArray.getJsonNumber(2).intValue())) pass = false; return pass; } /* Tests */ /* * @testName: readEmptyArrayTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; * * @test_Strategy: Test read of an empty array "[]" from stream. Use * JsonReader.readArray() API call. * */ @Test public void readEmptyArrayTest() { JsonReader reader = null; try { String expJsonText = "[]"; LOGGER.info("Testing read of " + expJsonText); reader = Json.createReader(new StringReader(expJsonText)); JsonArray array = reader.readArray(); assertTrue(JSONP_Util.assertEqualsEmptyArrayList(array), "readEmptyArrayTest Failed"); } catch (Exception e) { fail("readEmptyArrayTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readEscapeCharsInArrayTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; * * @test_Strategy: Test read of an array from a resource file with special * chars in data. Use JsonReader.readArray() API call. Test scenario: Read * string of JSON text containing a JSON array from resource file with * following data: [ "popeye\"\\\/\b\f\n\r\tolive" ] * * These characters are backslash escape'd as follows: \" \\ \/ \b \f \n \r \t * * Create a JsonWriter to write above JsonArray to a string of JSON text. * Re-read JsonWriter text back into a JsonArray Compare expected JSON array * with actual JSON array for equality. * */ @Test public void readEscapeCharsInArrayTest() { boolean pass = true; JsonReader reader = null; String resourceFile = "jsonArrayWithEscapeCharsData.json"; String expString = "popeye" + JSONP_Data.escapeCharsAsString + "olive"; try { LOGGER.info("Reading contents of resource file " + resourceFile); String readerContents = JSONP_Util .getContentsOfResourceAsString(resourceFile); LOGGER.info("readerContents=" + readerContents); LOGGER.info("Testing read of resource contents: " + readerContents); reader = Json.createReader(new StringReader(readerContents)); JsonArray expJsonArray = reader.readArray(); LOGGER.info("Dump of expJsonArray"); JSONP_Util.dumpJsonArray(expJsonArray); LOGGER.info("Comparing JsonArray values with expected results."); String actString = expJsonArray.getJsonString(0).getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; LOGGER.info("Write the JsonArray 'expJsonArray' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeArray(expJsonArray); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("Create actJsonArray from read of writer contents: " + writerContents); reader = Json.createReader(new StringReader(writerContents)); JsonArray actJsonArray = reader.readArray(); LOGGER.info("Dump of actJsonArray"); JSONP_Util.dumpJsonArray(actJsonArray); LOGGER.info("Compare expJsonArray and actJsonArray for equality"); if (!JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray)) pass = false; } catch (Exception e) { fail("readEscapeCharsInArrayTest Failed: ", e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "readEscapeCharsInArrayTest Failed"); } /* * @testName: readEscapeUnicodeCharsInArrayTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; * * @test_Strategy: Test read of an array with unicode chars escaped and not * escaped. Use JsonReader.readArray() API call. Test scenario: Read string of * JSON text containing a JSON array with the following data: [ * "\\u0000\u00ff\\uff00\uffff" ] * * Notice unicode \u0000 and \uff00 is escaped but \u00ff and \uffff is not. * * Compare expected JSON String with actual JSON String for equality. * */ @Test public void readEscapeUnicodeCharsInArrayTest() { JsonReader reader = null; String unicodeTextString = "[\"\\u0000\u00ff\\uff00\uffff\"]"; String expResult = "\u0000\u00ff\uff00\uffff"; try { LOGGER.info("Reading array of escaped and non escaped unicode chars."); reader = Json.createReader(new StringReader(unicodeTextString)); JsonArray array = reader.readArray(); String actResult = array.getJsonString(0).getString(); assertTrue(JSONP_Util.assertEquals(expResult, actResult), "readEscapeUnicodeCharsInArrayTest Failed"); } catch (Exception e) { fail("readEscapeUnicodeCharsInArrayTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readEscapeUnicodeControlCharsInArrayTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; * * @test_Strategy: Test read of an array with unicode control chars escaped. * Use JsonReader.readArray() API call. Test scenario: Read string of JSON * text containing unicode control chars escaped as a Json Array. * * Compare expected JSON String with actual JSON String for equality. * */ @Test public void readEscapeUnicodeControlCharsInArrayTest() { JsonReader reader = null; String unicodeTextString = "[\"" + JSONP_Data.unicodeControlCharsEscaped + "\"]"; String expResult = JSONP_Data.unicodeControlCharsNonEscaped; try { LOGGER.info("Reading array of escaped and non escaped unicode chars."); reader = Json.createReader(new StringReader(unicodeTextString)); JsonArray array = reader.readArray(); String actResult = array.getJsonString(0).getString(); assertTrue(JSONP_Util.assertEquals(expResult, actResult), "readEscapeUnicodeControlCharsInArrayTest Failed"); } catch (Exception e) { fail("readEscapeUnicodeControlCharsInArrayTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readEmptyObjectTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; * * @test_Strategy: Test read of an empty object "{}" from stream. Use * JsonReader.readObject() API call. * */ @Test public void readEmptyObjectTest() { JsonReader reader = null; try { String expJsonText = "{}"; LOGGER.info("Testing read of " + expJsonText); reader = Json.createReader(new StringReader(expJsonText)); JsonObject object = reader.readObject(); assertTrue(JSONP_Util.assertEqualsEmptyObjectMap(object), "readEmptyObjectTest Failed"); } catch (Exception e) { fail("readEmptyObjectTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readEscapeCharsInObjectTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; * * @test_Strategy: Test read of an object from a resource file with special * chars in data. Use JsonReader.readObject() API call. Test scenario: Read * string of JSON text containing a JSON object from resource file with * following data: { "specialChars" : "popeye\"\\\/\b\f\n\r\tolive" } * * These characters are backslash escape'd as follows: \" \\ \/ \b \f \n \r \t * * Create a JsonWriter to write above JsonObject to a string of JSON text. * Re-read JsonWriter text back into a JsonObject Compare expected JSON object * with actual JSON object for equality. * */ @Test public void readEscapeCharsInObjectTest() { boolean pass = true; JsonReader reader = null; String resourceFile = "jsonObjectWithEscapeCharsData.json"; String expString = "popeye" + JSONP_Data.escapeCharsAsString + "olive"; try { LOGGER.info("Reading contents of resource file " + resourceFile); String readerContents = JSONP_Util .getContentsOfResourceAsString(resourceFile); LOGGER.info("readerContents=" + readerContents); LOGGER.info("Testing read of resource contents: " + readerContents); reader = Json.createReader(new StringReader(readerContents)); JsonObject expJsonObject = reader.readObject(); LOGGER.info("Dump of expJsonObject"); JSONP_Util.dumpJsonObject(expJsonObject); LOGGER.info("Comparing JsonArray values with expected results."); String actString = expJsonObject.getJsonString("escapeChars").getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; LOGGER.info("Write the JsonObject 'expJsonObject' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeObject(expJsonObject); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("Create actJsonObject from read of writer contents: " + writerContents); reader = Json.createReader(new StringReader(writerContents)); JsonObject actJsonObject = reader.readObject(); LOGGER.info("Dump of actJsonObject"); JSONP_Util.dumpJsonObject(actJsonObject); LOGGER.info("Compare expJsonObject and actJsonObject for equality"); if (!JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject)) pass = false; } catch (Exception e) { fail("readEscapeCharsInObjectTest Failed: ", e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "readEscapeCharsInObjectTest Failed"); } /* * @testName: readEscapeUnicodeCharsInObjectTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; * * @test_Strategy: Test read of an object with unicode chars escaped and not * escaped. Use JsonReader.readObject() API call. Test scenario: Read string * of JSON text containing a JSON object with the following data: { * "unicodechars":"\\u0000\u00ff\\uff00\uffff" ] * * Notice unicode \u0000 and \uff00 is escaped but \u00ff and \uffff is not. * * Compare expected JSON String with actual JSON String for equality. * */ @Test public void readEscapeUnicodeCharsInObjectTest() { JsonReader reader = null; String unicodeTextString = "{\"unicodechars\":\"\\u0000\u00ff\\uff00\uffff\"}"; String expResult = "\u0000\u00ff\uff00\uffff"; try { LOGGER.info("Reading object of escaped and non escaped unicode chars."); reader = Json.createReader(new StringReader(unicodeTextString)); JsonObject object = reader.readObject(); String actResult = object.getJsonString("unicodechars").getString(); assertTrue(JSONP_Util.assertEquals(expResult, actResult), "readEscapeUnicodeCharsInObjectTest Failed"); } catch (Exception e) { fail("readEscapeUnicodeCharsInObjectTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readEscapeUnicodeControlCharsInObjectTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; * * @test_Strategy: Test read of an array with unicode control chars escaped. * Use JsonReader.readObject() API call. Test scenario: Read string of JSON * text containing unicode control chars escaped as a Json Object. * * Compare expected JSON String with actual JSON String for equality. * */ @Test public void readEscapeUnicodeControlCharsInObjectTest() { JsonReader reader = null; String unicodeTextString = "{\"unicodechars\":\"" + JSONP_Data.unicodeControlCharsEscaped + "\"}"; String expResult = JSONP_Data.unicodeControlCharsNonEscaped; try { LOGGER.info("Reading array of escaped and non escaped unicode chars."); reader = Json.createReader(new StringReader(unicodeTextString)); JsonObject object = reader.readObject(); String actResult = object.getJsonString("unicodechars").getString(); assertTrue(JSONP_Util.assertEquals(expResult, actResult), "readEscapeUnicodeControlCharsInObjectTest Failed"); } catch (Exception e) { fail("readEscapeUnicodeControlCharsInObjectTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readArrayTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; * * @test_Strategy: Test read of an array containing various types from stream. * Use JsonReader.readArray() API call. [true, false, null, "booyah", * 2147483647, 9223372036854775807, 1.7976931348623157E308, * [true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324], * {"true":true,"false":false,"null":null,"bonga":"boo","int":1,"double":10.4} * ] Test scenario: Read string of JSON text above consisting of a JSON array * into a JsonArray object. Create an expected List of JsonArray values for * use in test comparison. Compare expected list of JsonArray values with * actual list for equality. * */ @Test public void readArrayTest() { JsonReader reader = null; try { String jsonText = "[true,false,null,\"booyah\",2147483647,9223372036854775807,1.7976931348623157E308," + "[true,false,null,\"bingo\",-2147483648,-9223372036854775808,4.9E-324]," + "{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1," + "\"double\":10.4}]"; LOGGER.info("Create the expected list of JsonArray values"); List expList = new ArrayList<>(); expList.add(JsonValue.TRUE); expList.add(JsonValue.FALSE); expList.add(JsonValue.NULL); expList.add(JSONP_Util.createJsonString("booyah")); expList.add(JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); expList.add(JSONP_Util.createJsonNumber(Long.MAX_VALUE)); expList.add(JSONP_Util.createJsonNumber(Double.MAX_VALUE)); JsonArray array = Json.createArrayBuilder().add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL).add("bingo") .add(Integer.MIN_VALUE).add(Long.MIN_VALUE).add(Double.MIN_VALUE) .build(); JsonObject object = Json.createObjectBuilder().add("true", JsonValue.TRUE) .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) .add("bonga", "boo").add("int", 1).add("double", 10.4).build(); expList.add(array); expList.add(object); LOGGER.info("Testing read of " + jsonText); reader = Json.createReader(new StringReader(jsonText)); JsonArray myJsonArray = reader.readArray(); List actList = myJsonArray; LOGGER.info( "Compare actual list of JsonArray values with expected list of JsonArray values"); assertTrue(JSONP_Util.assertEqualsList(expList, actList), "readArrayTest Failed"); } catch (Exception e) { fail("readArrayTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readArrayTest2 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; * JSONP:JAVADOC:178; * * @test_Strategy: Test read of an array containing various types from stream. * Use JsonReader.readArray() API call. [true, false, null, "booyah", * 2147483647, 9223372036854775807, 1.7976931348623157E308, * [true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324], * {"true":true,"false":false,"null":null,"bonga":"boo","int":1,"double":10.4} * ] Test Scenario: Create an expected JsonArray of the above JSON array for * use in test comparison. Create a JsonWriter to write the above JsonArray to * a string of JSON text. Next call JsonReader to read the JSON text from the * JsonWriter to a JsonArray object. Compare expected JsonArray object with * actual JsonArray object for equality. * */ @Test public void readArrayTest2() { JsonReader reader = null; try { LOGGER.info("Create the expected list of JsonArray values"); JsonArray expJsonArray = Json.createArrayBuilder().add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL).add("booyah") .add(Integer.MAX_VALUE).add(Long.MAX_VALUE).add(Double.MAX_VALUE) .add(Json.createArrayBuilder().add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL).add("bingo") .add(Integer.MIN_VALUE).add(Long.MIN_VALUE).add(Double.MIN_VALUE)) .add(Json.createObjectBuilder().add("true", JsonValue.TRUE) .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) .add("bonga", "boo").add("int", 1).add("double", 10.4)) .build(); LOGGER.info("Write the JsonArray 'expJsonArray' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeArray(expJsonArray); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String jsonText = sWriter.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + jsonText); LOGGER.info("Testing read of " + jsonText); reader = Json.createReader(JSONP_Util.getInputStreamFromString(jsonText)); JsonArray actJsonArray = reader.readArray(); LOGGER.info("Compare expJsonArray and actJsonArray for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray), "readArrayTest2 Failed"); } catch (Exception e) { fail("readArrayTest2 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readArrayTest3 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:449; JSONP:JAVADOC:184; * JSONP:JAVADOC:419; * * @test_Strategy: Test read of an array containing various types from stream. * Use JsonReader.readArray() API call. [true, false, null, "booyah", * 2147483647, 9223372036854775807, * [true,false,null,"bingo",-2147483648,-9223372036854775808], * {"true":true,"false":false,"null":null,"bonga":"boo","int":1} ] Test * scenario: Read string of JSON text above consisting of a JSON array into a * JsonArray object with an empty configuration. Create a JsonWriter to write * the above JsonArray to a string of JSON text. Compare expected JSON text * with actual JSON text for equality. * * Tests the following API's: JsonReader = * Json.createReaderFactory(Map).createReader(Reader) JsonArray * array = JsonReader.readArray() * */ @Test public void readArrayTest3() { JsonReader reader = null; try { String expJsonText = "[true,false,null,\"booyah\",2147483647,9223372036854775807," + "[true,false,null,\"bingo\",-2147483648,-9223372036854775808]," + "{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1}]"; LOGGER.info("Testing read of " + expJsonText); reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) .createReader(new StringReader(expJsonText)); JsonArray myJsonArray = reader.readArray(); LOGGER.info("Write the JsonArray 'myJsonArray' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeArray(myJsonArray); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonText = sWriter.toString(); LOGGER.info("Compare actual JSON text with expected JSON text"); assertTrue(JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText), "readArrayTest3 Failed"); } catch (Exception e) { fail("readArrayTest3 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readArrayTest4 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:184; * JSONP:JAVADOC:449; * * @test_Strategy: Test read of an array from a resource file with various * amounts of data. Use JsonReader.readArray() API call. Test scenario: Read * InputStream of JSON text containing a JSON array from resource file with * various amounts of data use UTF-8 encoding. Create a JsonWriter to write * above JsonArray to a string of JSON text. Re-read JsonWriter text back into * a JsonArray Compare expected JSON array with actual JSON array for * equality. * */ @Test public void readArrayTest4() { JsonReader reader = null; String resourceFile = "jsonArrayWithAllTypesOfData.json"; try { LOGGER.info( "Read contents of InputStream from resource file: " + resourceFile); Map config = JSONP_Util.getEmptyConfig(); reader = Json.createReaderFactory(config).createReader( JSONP_Util.getInputStreamFromResource(resourceFile), JSONP_Util.UTF_8); JsonArray expJsonArray = reader.readArray(); LOGGER.info("Dump of expJsonArray"); JSONP_Util.dumpJsonArray(expJsonArray); LOGGER.info("Write the JsonArray 'expJsonArray' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeArray(expJsonArray); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("Create actJsonArray from read of writer contents: " + writerContents); reader = Json.createReader(new StringReader(writerContents)); JsonArray actJsonArray = reader.readArray(); LOGGER.info("Dump of actJsonArray"); JSONP_Util.dumpJsonArray(actJsonArray); LOGGER.info("Compare expJsonArray and actJsonArray for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray), "readArrayTest4 Failed"); } catch (Exception e) { fail("readArrayTest4 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readArrayTest5 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:181; * JSONP:JAVADOC:420; JSONP:JAVADOC:449; * * @test_Strategy: Test read of an array from a resource file with lots of * nesting. Use JsonReader.read() API call. Test scenario: Read InputStream of * JSON text containing a JSON array from resource file with lots of nesting * use UTF-8 encoding with empty configuration. Create a JsonWriter to write * above JsonArray to a string of JSON text. Compare expected JSON text with * actual JSON text for equality. Filter all text output to remove whitespace * before comparison. * * Tests the following API's: JsonReader = * Json.createReaderFactory(Map).createReader(InputStream, Charset) * JsonArray array = (JsonArray)JsonReader.read() * * */ @Test public void readArrayTest5() { JsonReader reader = null; String resourceFile = "jsonArrayWithLotsOfNestedObjectsData.json"; try { LOGGER.info("Reading contents of resource file " + resourceFile); String readerContents = JSONP_Util .getContentsOfResourceAsString(resourceFile); LOGGER.info("readerContents=" + readerContents); // Create expected JSON text from resource contents filtered of whitespace // for comparison LOGGER.info("Filter readerContents of whitespace for comparison"); String expJsonText = JSONP_Util.removeWhitespace(readerContents); LOGGER.info( "Read contents of InputStream from resource file: " + resourceFile); reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) .createReader(JSONP_Util.getInputStreamFromResource(resourceFile), JSONP_Util.UTF_8); JsonArray myJsonArray = (JsonArray) reader.read(); LOGGER.info("Write the JsonArray 'myJsonArray' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeArray(myJsonArray); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("Dump contents of the JsonWriter as a String"); LOGGER.info("writerContents=" + writerContents); LOGGER.info("Filter writerContents of whitespace for comparison"); String actJsonText = JSONP_Util.removeWhitespace(writerContents); LOGGER.info("Compare actual JSON text with expected JSON text"); assertTrue(JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText), "readArrayTest5 Failed"); } catch (Exception e) { fail("readArrayTest5 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readArrayEncodingTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:449; * JSONP:JAVADOC:184; * * @test_Strategy: Test read of a JsonArray from a resource file using both * encodings of UTF-8 and UTF-16BE. * * Test scenario: For each encoding read the appropriate resource file * containing a string value. Call JsonArray.getJsonString() to get the value * of the JsonString. Compare expected string with actual string for equality. */ @Test public void readArrayEncodingTest() { boolean pass = true; JsonReader reader = null; String expString = "a\u65e8\u452c\u8b9e\u6589\u5c57\u5217z"; String resourceFileUTF8 = "jsonArrayUTF8.json"; String resourceFileUTF16BE = "jsonArrayUTF16BE.json"; Map config = JSONP_Util.getEmptyConfig(); try { LOGGER.info("Reading contents of resource file using UTF-8 encoding " + resourceFileUTF8); InputStream is = JSONP_Util.getInputStreamFromResource(resourceFileUTF8); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_8); JsonArray jsonArray = reader.readArray(); LOGGER.info("Comparing JsonArray values with expected results."); String actString = jsonArray.getJsonString(0).getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; } catch (Exception e) { fail("readArrayEncodingTest Failed: ", e); } finally { if (reader != null) reader.close(); } try { LOGGER.info("Reading contents of resource file using UTF-16BE encoding " + resourceFileUTF16BE); InputStream is = JSONP_Util .getInputStreamFromResource(resourceFileUTF16BE); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_16BE); JsonArray jsonArray = reader.readArray(); LOGGER.info("Comparing JsonArray values with expected results."); String actString = jsonArray.getJsonString(0).getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; } catch (Exception e) { fail("readArrayEncodingTest Failed: ", e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "readArrayEncodingTest Failed"); } /* * @testName: readObjectTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; * * @test_Strategy: Test read of an object containing various types from * stream. Use JsonReader.readObject() API call. {"true":true, "false":false, * "null":null, "booyah":"booyah", "int":2147483647, * "long":9223372036854775807, "double":1.7976931348623157E308, * "array":[true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324] * , "object":{"true":true,"false":false,"null":null,"bonga":"boo","int":1, * "double":10.4} } Test scenario: Read string of JSON text above consisting * of a JSON object into a JsonObject object. Create an expected map of * JsonObject values for use in test comparison. Compare expected map of * JsonObject values with actual map for equality. * */ @Test public void readObjectTest() { JsonReader reader = null; try { String expJsonText = "{\"true\":true,\"false\":false,\"null\":null,\"booyah\":\"booyah\",\"int\":2147483647," + "\"long\":9223372036854775807,\"double\":1.7976931348623157E308," + "\"array\":[true,false,null,\"bingo\",-2147483648,-9223372036854775808,4.9E-324]," + "\"object\":{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1," + "\"double\":10.4}}"; LOGGER.info("Create the expected map of JsonObject values"); Map expMap = new HashMap<>(); expMap.put("true", JsonValue.TRUE); expMap.put("false", JsonValue.FALSE); expMap.put("null", JsonValue.NULL); expMap.put("booyah", JSONP_Util.createJsonString("booyah")); expMap.put("int", JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); expMap.put("long", JSONP_Util.createJsonNumber(Long.MAX_VALUE)); expMap.put("double", JSONP_Util.createJsonNumber(Double.MAX_VALUE)); JsonArray array = Json.createArrayBuilder().add(JsonValue.TRUE) .add(JsonValue.FALSE).add(JsonValue.NULL).add("bingo") .add(Integer.MIN_VALUE).add(Long.MIN_VALUE).add(Double.MIN_VALUE) .build(); JsonObject object = Json.createObjectBuilder().add("true", JsonValue.TRUE) .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) .add("bonga", "boo").add("int", 1).add("double", 10.4).build(); expMap.put("array", array); expMap.put("object", object); LOGGER.info("Testing read of " + expJsonText); reader = Json.createReader(new StringReader(expJsonText)); JsonObject myJsonObject = reader.readObject(); Map actMap = myJsonObject; LOGGER.info( "Compare actual map of JsonObject values with expected map of JsonObject values"); assertTrue(JSONP_Util.assertEqualsMap(expMap, actMap), "readObjectTest Failed"); } catch (Exception e) { fail("readObjectTest Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readObjectTest2 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:178; JSONP:JAVADOC:185; * * @test_Strategy: Test read of an object containing various types from * stream. Use JsonReader.readObject() API call. {"true":true, "false":false, * "null":null, "booyah":"booyah", "int":2147483647, * "long":9223372036854775807, "double":1.7976931348623157E308, * "array":[true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324] * , "object":{"true":true,"false":false,"null":null,"bonga":"boo","int":1, * "double":10.4} } Test Scenario: Create an expected JsonObject of the above * JSON object for use in test comparison. Create a JsonWriter to write the * above JsonObject to a string of JSON text. Next call JsonReader to read the * JSON text from the JsonWriter to a JsonObject object. Compare expected * JsonObject object with actual JsonObject object for equality. * */ @Test public void readObjectTest2() { JsonReader reader = null; try { LOGGER.info("Create the expected list of JsonObject values"); JsonObject expJsonObject = Json.createObjectBuilder() .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) .add("null", JsonValue.NULL).add("booyah", "booyah") .add("int", Integer.MAX_VALUE).add("long", Long.MAX_VALUE) .add("double", Double.MAX_VALUE) .add("array", Json.createArrayBuilder().add(JsonValue.TRUE).add(JsonValue.FALSE) .add(JsonValue.NULL).add("bingo").add(Integer.MIN_VALUE) .add(Long.MIN_VALUE).add(Double.MIN_VALUE)) .add("object", Json.createObjectBuilder().add("true", JsonValue.TRUE) .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) .add("bonga", "boo").add("int", 1).add("double", 10.4)) .build(); LOGGER.info("Write the JsonObject 'expJsonObject' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeObject(expJsonObject); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String jsonText = sWriter.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + jsonText); LOGGER.info("Testing read of " + jsonText); reader = Json.createReader(JSONP_Util.getInputStreamFromString(jsonText)); JsonObject actJsonObject = reader.readObject(); LOGGER.info("Compare expJsonObject and actJsonObject for equality"); assertTrue(JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject), "readObjectTest2 Failed"); } catch (Exception e) { fail("readObjectTest2 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readObjectTest3 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:185; JSONP:JAVADOC:419; * JSONP:JAVADOC:449; * * @test_Strategy: Test read of an object containing various types from * stream. Use JsonReader.readObject() API call. {"true":true, "false":false, * "null":null, "booyah":"booyah", "int":2147483647, * "long":9223372036854775807, * "array":[true,false,null,"bingo",-2147483648,-9223372036854775808], * "object":{"true":true,"false":false,"null":null,"bonga":"boo","int":1} } * Test scenario: Read string of JSON text above consisting of a JSON object * into a JsonObject object with an empty configuration. Create a JsonWriter * to write the above JsonObject to a string of JSON text. Compare expected * JSON text with actual JSON text for equality. * * Tests the following API's: JsonReader = * Json.createReaderFactory(Map).createReader(Reader) JsonObject * object = JsonReader.readObject() * * */ @Test public void readObjectTest3() { JsonReader reader = null; try { String expJsonText = "{\"true\":true,\"false\":false,\"null\":null,\"booyah\":\"booyah\",\"int\":2147483647,\"long\":9223372036854775807," + "\"array\":[true,false,null,\"bingo\",-2147483648,-9223372036854775808]," + "\"object\":{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1}}"; LOGGER.info("Testing read of " + expJsonText); reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) .createReader(new StringReader(expJsonText)); JsonObject myJsonObject = reader.readObject(); LOGGER.info("Write the JsonObject 'myJsonObject' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeObject(myJsonObject); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonText = sWriter.toString(); LOGGER.info("Compare actual JSON text with expected JSON text"); assertTrue(JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText), "readObjectTest3 Failed"); } catch (Exception e) { fail("readObjectTest3 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readObjectTest4 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:420; * JSONP:JAVADOC:449; * * @test_Strategy: Test read of an object from a resource file with various * amounts of data. Use JsonReader.readObject() API call. Test scenario: Read * InputStream of JSON text containing a JSON object from resource file with * various amounts of data use UTF-8 encoding. Create a JsonWriter to write * above JsonObject to a string of JSON text. Re-read JsonWriter text back * into a JsonObject Compare expected JSON object with actual JSON object for * equality. * */ @Test public void readObjectTest4() { JsonReader reader = null; String resourceFile = "jsonObjectWithAllTypesOfData.json"; try { LOGGER.info( "Read contents of InputStream from resource file: " + resourceFile); Map config = JSONP_Util.getEmptyConfig(); reader = Json.createReaderFactory(config).createReader( JSONP_Util.getInputStreamFromResource(resourceFile), JSONP_Util.UTF_8); JsonObject expJsonObject = reader.readObject(); LOGGER.info("Dump of expJsonObject"); JSONP_Util.dumpJsonObject(expJsonObject); LOGGER.info("Write the JsonObject 'expJsonObject' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeObject(expJsonObject); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("Create actJsonObject from read of writer contents: " + writerContents); reader = Json.createReader(new StringReader(writerContents)); JsonObject actJsonObject = reader.readObject(); LOGGER.info("Dump of actJsonObject"); JSONP_Util.dumpJsonObject(actJsonObject); LOGGER.info("Compare expJsonObject and actJsonObject for equality"); assertTrue(JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject), "readObjectTest4 Failed"); } catch (Exception e) { fail("readObjectTest4 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readObjectTest5 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:181; * JSONP:JAVADOC:420; JSONP:JAVADOC:449; * * @test_Strategy: Test read of an object from a resource file with lots of * nesting. Use JsonReader.read() API call. Test scenario: Read InputStream of * JSON text containing a JSON object from resource file with lots of nesting * use UTF-8 encoding with empty configuration. Create a JsonWriter to write * above JsonObject to a string of JSON text. Compare expected JSON text with * actual JSON text for equality. Filter all text output to remove whitespace * before comparison. * * Tests the following API's: JsonReader = * Json.createReaderFactory(Map).createReader(InputStream, Charset) * JsonReader.read() JsonObject object = (JsonObject)JsonReader.read() * * */ @Test public void readObjectTest5() { JsonReader reader = null; String resourceFile = "jsonObjectWithLotsOfNestedObjectsData.json"; try { LOGGER.info("Reading contents of resource file " + resourceFile); String readerContents = JSONP_Util .getContentsOfResourceAsString(resourceFile); LOGGER.info("readerContents=" + readerContents); // Create expected JSON text from resource contents filtered of whitespace // for comparison LOGGER.info("Filter readerContents of whitespace for comparison"); String expJsonText = JSONP_Util.removeWhitespace(readerContents); LOGGER.info( "Read contents of InputStream from resource file: " + resourceFile); reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) .createReader(JSONP_Util.getInputStreamFromResource(resourceFile), JSONP_Util.UTF_8); JsonObject myJsonObject = (JsonObject) reader.read(); LOGGER.info("Write the JsonObject 'myJsonObject' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeObject(myJsonObject); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("Dump contents of the JsonWriter as a String"); LOGGER.info("writerContents=" + writerContents); LOGGER.info("Filter writerContents of whitespace for comparison"); String actJsonText = JSONP_Util.removeWhitespace(writerContents); LOGGER.info("Compare actual JSON text with expected JSON text"); assertTrue(JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText), "readObjectTest5 Failed"); } catch (Exception e) { fail("readObjectTest5 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: readObjectEncodingTest * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:185; * JSONP:JAVADOC:449; * * @test_Strategy: Test read of a JsonObject from a resource file using both * encodings of UTF-8 and UTF-16LE. * * Test scenario: For each encoding read the appropriate resource file * containing a string value. Call JsonObject.getJsonString() to get the value * of the JsonString. Compare expected string with actual string for equality. */ @Test public void readObjectEncodingTest() { boolean pass = true; JsonReader reader = null; String expString = "a\u65e8\u452c\u8b9e\u6589\u5c57\u5217z"; String resourceFileUTF8 = "jsonObjectUTF8.json"; String resourceFileUTF16LE = "jsonObjectUTF16LE.json"; try { LOGGER.info("Reading contents of resource file using UTF-8 encoding " + resourceFileUTF8); InputStream is = JSONP_Util.getInputStreamFromResource(resourceFileUTF8); Map config = JSONP_Util.getEmptyConfig(); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_8); JsonObject jsonObject = reader.readObject(); LOGGER.info("Comparing JsonObject values with expected results."); String actString = jsonObject.getJsonString("unicodeChars").getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; } catch (Exception e) { fail("readObjectEncodingTest Failed: ", e); } finally { if (reader != null) reader.close(); } try { LOGGER.info("Reading contents of resource file using UTF-16LE encoding " + resourceFileUTF16LE); InputStream is = JSONP_Util .getInputStreamFromResource(resourceFileUTF16LE); Map config = JSONP_Util.getEmptyConfig(); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_16LE); JsonObject jsonObject = reader.readObject(); LOGGER.info("Comparing JsonObject values with expected results."); String actString = jsonObject.getJsonString("unicodeChars").getString(); if (!JSONP_Util.assertEquals(expString, actString)) pass = false; } catch (Exception e) { fail("readObjectEncodingTest Failed: ", e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "readObjectEncodingTest Failed"); } /* * @testName: readUTFEncodedTests * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:185; * JSONP:JAVADOC:449; * * @test_Strategy: Tests the JsonReader reader. Verifies READING of the * JsonObject defined in resource files: * * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16.json * jsonObjectEncodingUTF16LE.json jsonObjectEncodingUTF16BE.json * jsonObjectEncodingUTF32LE.json jsonObjectEncodingUTF32BE.json * * Creates the JsonReader via the API: * * JsonReader reader = * Json.createReaderFactory(Map).createReader(InputStream, Charset) * * For each supported encoding supported by JSON RFC read the JsonObject and * verify we get the expected results. The Charset encoding is passed in as * argument for each encoding type read. */ @Test public void readUTFEncodedTests() { boolean pass = true; JsonReader reader = null; Map config = JSONP_Util.getEmptyConfig(); try { LOGGER.info( "-----------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-8]"); LOGGER.info( "-----------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); LOGGER.info( "Create JsonReader from the InputStream with character encoding UTF-8"); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_8); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-8 encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info( "------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-16]"); LOGGER.info( "------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16.json"); LOGGER.info( "Create JsonReader from the InputStream with character encoding UTF-16"); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_16); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-16 encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-16LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); LOGGER.info( "Create JsonReader from the InputStream with character encoding UTF-16LE"); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_16LE); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-16LE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-16BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); LOGGER.info( "Create JsonReader from the InputStream with character encoding UTF-16BE"); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_16BE); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-16BE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-32LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); LOGGER.info( "Create JsonReader from the InputStream with character encoding UTF-32LE"); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_32LE); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-32LE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-32BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); LOGGER.info( "Create JsonReader from the InputStream with character encoding UTF-32BE"); reader = Json.createReaderFactory(config).createReader(is, JSONP_Util.UTF_32BE); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-32BE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } assertTrue(pass, "readUTFEncodedTests Failed"); } /* * @testName: readUTFEncodedTests2 * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:178; JSONP:JAVADOC:185; * * @test_Strategy: Tests the JsonReader reader. Verifies READING of the * JsonObject defined in resource files: * * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16LE.json * jsonObjectEncodingUTF16BE.json jsonObjectEncodingUTF32LE.json * jsonObjectEncodingUTF32BE.json * * Creates the JsonReader via the API: * * JsonReader reader = Json.createReader(InputStream istream) * * For each supported encoding supported by JSON RFC read the JsonObject and * verify we get the expected results. The character encoding of the stream is * auto-detected and determined as per the RFC. */ @Test public void readUTFEncodedTests2() { boolean pass = true; JsonReader reader = null; try { LOGGER.info("---------------------------------------------------"); LOGGER.info("TEST CASE [Json.createReader(InputStream) as UTF-8]"); LOGGER.info("---------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); LOGGER.info( "Create JsonReader from the InputStream and auto-detect character encoding UTF-8"); reader = Json.createReader(is); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-8 encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info("------------------------------------------------------"); LOGGER.info("TEST CASE [Json.createReader(InputStream) as UTF-16LE]"); LOGGER.info("------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); LOGGER.info( "Create JsonReader from the InputStream and auto-detect character encoding UTF-16LE"); reader = Json.createReader(is); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-16LE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info("------------------------------------------------------"); LOGGER.info("TEST CASE [Json.createReader(InputStream) as UTF-16BE]"); LOGGER.info("------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); LOGGER.info( "Create JsonReader from the InputStream and auto-detect character encoding UTF-16BE"); reader = Json.createReader(is); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-16BE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info("------------------------------------------------------"); LOGGER.info("TEST CASE [Json.createReader(InputStream) as UTF-32LE]"); LOGGER.info("------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); LOGGER.info( "Create JsonReader from the InputStream and auto-detect character encoding UTF-32LE"); reader = Json.createReader(is); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-32LE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } try { LOGGER.info("------------------------------------------------------"); LOGGER.info("TEST CASE [Json.createReader(InputStream) as UTF-32BE]"); LOGGER.info("------------------------------------------------------"); LOGGER.info( "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); InputStream is = JSONP_Util .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); LOGGER.info( "Create JsonReader from the InputStream and auto-detect character encoding UTF-32BE"); reader = Json.createReader(is); JsonObject jsonObject = reader.readObject(); if (!compareJsonObjectForUTFEncodedTests(jsonObject)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing reading of UTF-32BE encoding: " + e); } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } assertTrue(pass, "readUTFEncodedTests2 Failed"); } /* * @testName: negativeObjectTests * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:413; * * @test_Strategy: Test various Json Syntax Errors when reading a JsonObject. * The tests trip various JsonParsingException/JsonException conditions when * reading an object. * */ @Test public void negativeObjectTests() { boolean pass = true; JsonReader reader = null; // Not an object [] try { LOGGER.info("Testing for not an object '[]'"); reader = Json.createReader(new StringReader("[]")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonException"); } catch (JsonException e) { LOGGER.info("Got expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Trip JsonParsingException for JsonReader.readObject() if incorrect // representation for object try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if incorrect representation for object."); LOGGER.info("Reading " + "{\"name\":\"value\",1,2,3}"); reader = Json .createReader(new StringReader("{\"name\":\"value\",1,2,3}")); JsonObject jsonObject = reader.readObject(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Missing [ try { LOGGER.info("Testing for missing '['"); reader = Json.createReader(new StringReader("{1,2]}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing ] try { LOGGER.info("Testing for missing ']'"); reader = Json.createReader(new StringReader("{[1,2}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing { try { LOGGER.info("Testing for missing '{'"); reader = Json.createReader(new StringReader("}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing } try { LOGGER.info("Testing for missing '}'"); reader = Json.createReader(new StringReader("{")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between array elements test case 1 try { LOGGER.info("Testing for missing ',' between array elements test case 1"); reader = Json.createReader(new StringReader("{[5\"foo\"]}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between array elements test case 2 try { LOGGER.info("Testing for missing ',' between array elements test case 2"); reader = Json.createReader(new StringReader("{[5{}]}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between object elements test case 1 try { LOGGER.info("Testing for missing ',' between object elements test case 1"); reader = Json.createReader(new StringReader("{\"foo\":\"bar\"5}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between object elements test case 2 try { LOGGER.info("Testing for missing ',' between object elements test case 2"); reader = Json.createReader(new StringReader("{\"one\":1[]}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing key name in object element try { LOGGER.info("Testing for missing key name in object element"); reader = Json.createReader(new StringReader("{:\"bar\"}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing value name in object element try { LOGGER.info("Testing for missing value name in object element"); reader = Json.createReader(new StringReader("{\"foo\":}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing double quote on a name try { LOGGER.info("Test for missing double quote on a name"); reader = Json.createReader(new StringReader("{name\" : \"value\"}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing double quote on a value try { LOGGER.info("Test for missing double quote on a value"); reader = Json.createReader(new StringReader("{\"name\" : value\"}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 1 try { LOGGER.info("Incorrect digit value -foo"); reader = Json.createReader(new StringReader("{\"number\" : -foo}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 2 try { LOGGER.info("Incorrect digit value +foo"); reader = Json.createReader(new StringReader("{\"number\" : +foo}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 3 try { LOGGER.info("Incorrect digit value -784foo"); reader = Json.createReader(new StringReader("{\"number\" : -784foo}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 4 try { LOGGER.info("Incorrect digit value +784foo"); reader = Json.createReader(new StringReader("{\"number\" : +784foo}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 5 try { LOGGER.info("Incorrect digit value 0.1E5E5"); reader = Json.createReader(new StringReader("{\"number\" : 0.1E5E5}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 6 try { LOGGER.info("Incorrect digit value 0.F10"); reader = Json.createReader(new StringReader("{\"number\" : 0.F10}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 7 try { LOGGER.info("Incorrect digit value string"); reader = Json.createReader(new StringReader("{\"number\" : string}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 8 (hex numbers invalid per JSON RFC) try { LOGGER.info("Incorrect digit value hex numbers invalid per JSON RFC"); reader = Json.createReader(new StringReader("{\"number\" : 0x137a}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 9 (octal numbers invalid per JSON RFC) try { LOGGER.info("Incorrect digit value octal numbers invalid per JSON RFC"); reader = Json.createReader(new StringReader("{\"number\" : 0137}")); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "negativeObjectTests Failed"); } /* * @testName: negativeArrayTests * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:412; * * @test_Strategy: Test various Json Syntax Errors when reading a JsonArray. * The tests trip various JsonParsingException/JsonException conditions when * reading an array. * */ @Test public void negativeArrayTests() { boolean pass = true; JsonReader reader = null; // Not an array {} try { LOGGER.info("Testing for not an array '{}'"); reader = Json.createReader(new StringReader("{}")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonException"); } catch (JsonException e) { LOGGER.info("Got expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Trip JsonParsingException for JsonReader.readArray() if incorrect // representation for array try { LOGGER.info( "Trip JsonParsingException for JsonReader.readArray() if incorrect representation for array."); LOGGER.info("Reading " + "[foo,10,\"name\":\"value\"]"); reader = Json .createReader(new StringReader("[foo,10,\"name\":\"value\"]")); JsonArray jsonArray = reader.readArray(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Missing [ try { LOGGER.info("Testing for missing '['"); reader = Json.createReader(new StringReader("]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing ] try { LOGGER.info("Testing for missing ']'"); reader = Json.createReader(new StringReader("[")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing { try { LOGGER.info("Testing for missing '{'"); reader = Json.createReader(new StringReader("[1,\"name\":\"value\"}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing } try { LOGGER.info("Testing for missing '}'"); reader = Json.createReader(new StringReader("[1,{\"name\":\"value\"]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between array elements test case 1 try { LOGGER.info("Testing for missing ',' between array elements test case 1"); reader = Json.createReader(new StringReader("[5\"foo\"]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between array elements test case 2 try { LOGGER.info("Testing for missing ',' between array elements test case 2"); reader = Json.createReader(new StringReader("[5{}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between object elements test case 1 try { LOGGER.info("Testing for missing ',' between object elements test case 1"); reader = Json.createReader(new StringReader("[{\"foo\":\"bar\"5}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between object elements test case 2 try { LOGGER.info("Testing for missing ',' between object elements test case 2"); reader = Json.createReader(new StringReader("[{\"one\":1[]}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing key name in object element try { LOGGER.info("Testing for missing key name in object element"); reader = Json.createReader(new StringReader("[{:\"bar\"}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing value name in object element try { LOGGER.info("Testing for missing value name in object element"); reader = Json.createReader(new StringReader("[{\"foo\":}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing double quote on a name try { LOGGER.info("Test for missing double quote on a name"); reader = Json.createReader(new StringReader("[{name\" : \"value\"}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing double quote on a value try { LOGGER.info("Test for missing double quote on a value"); reader = Json.createReader(new StringReader("[{\"name\" : value\"}]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 1 try { LOGGER.info("Incorrect digit value -foo"); reader = Json.createReader(new StringReader("[-foo]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 2 try { LOGGER.info("Incorrect digit value +foo"); reader = Json.createReader(new StringReader("[+foo]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 3 try { LOGGER.info("Incorrect digit value -784foo"); reader = Json.createReader(new StringReader("[-784foo]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 4 try { LOGGER.info("Incorrect digit value +784foo"); reader = Json.createReader(new StringReader("[+784foo]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 5 try { LOGGER.info("Incorrect digit value 0.1E5E5"); reader = Json.createReader(new StringReader("[0.1E5E5]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 6 try { LOGGER.info("Incorrect digit value 0.F10"); reader = Json.createReader(new StringReader("[0.F10]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 7 try { LOGGER.info("Incorrect digit value string"); reader = Json.createReader(new StringReader("[string]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 8 (hex numbers invalid per JSON RFC) try { LOGGER.info("Incorrect digit value hex numbers invalid per JSON RFC"); reader = Json.createReader(new StringReader("[0x137a]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 9 (octal numbers invalid per JSON RFC) try { LOGGER.info("Incorrect digit value octal numbers invalid per JSON RFC"); reader = Json.createReader(new StringReader("[0137]")); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "negativeArrayTests Failed"); } /* * @testName: illegalStateExceptionTests * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:218; * JSONP:JAVADOC:220; JSONP:JAVADOC:183; * * @test_Strategy: Test IllegalStateException test conditions. * */ @Test public void illegalStateExceptionTests() { boolean pass = true; JsonReader reader = null; // IllegalStateException if reader.close() called before reader.read() try { reader = Json.createReader(new StringReader("{}")); reader.close(); LOGGER.info( "Calling reader.read() after reader.close() is called is illegal."); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // IllegalStateException if reader.read() called after reader.readObject() try { reader = Json.createReader(new StringReader("{}")); JsonObject value = reader.readObject(); LOGGER.info( "Calling reader.readObject() after reader.readObject() was called is illegal."); value = (JsonObject) reader.read(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // IllegalStateException if reader.read() called after reader.readArray() try { reader = Json.createReader(new StringReader("[]")); JsonArray value = reader.readArray(); LOGGER.info( "Calling reader.read() after reader.readArray() was called is illegal."); value = (JsonArray) reader.read(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // IllegalStateException if reader.close() called before reader.readObject() try { reader = Json.createReader(new StringReader("{}")); reader.close(); LOGGER.info( "Calling reader.readObject() after reader.close() is called is illegal."); JsonObject value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // IllegalStateException if reader.readObject() called after // reader.readObject() try { reader = Json.createReader(new StringReader("{}")); JsonObject value = reader.readObject(); LOGGER.info( "Calling reader.readObject() after reader.readObject() was called is illegal."); value = reader.readObject(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // IllegalStateException if reader.readArray() called after // reader.readObject() try { reader = Json.createReader(new StringReader("{}")); JsonObject obj = reader.readObject(); LOGGER.info( "Calling reader.readArray() after reader.readObject() was called is illegal."); JsonArray arr = reader.readArray(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // IllegalStateException if reader.close() called before reader.readArray() try { reader = Json.createReader(new StringReader("[]")); reader.close(); LOGGER.info( "Calling reader.readArray() after reader.close() is called is illegal."); JsonArray value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // IllegalStateException if reader.readArray() called after // reader.readArray() try { reader = Json.createReader(new StringReader("[]")); JsonArray value = reader.readArray(); LOGGER.info( "Calling reader.readArray() after reader.readArray() was called is illegal."); value = reader.readArray(); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // IllegalStateException if reader.readObject() called after // reader.readArray() try { reader = Json.createReader(new StringReader("[]")); JsonArray arr = reader.readArray(); LOGGER.info( "Calling reader.readObject() after reader.readArray() was called is illegal."); JsonObject obj = reader.readObject(); pass = false; LOGGER.info("obj=" + obj); LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "illegalStateExceptionTests Failed"); } /* * @testName: negativeJsonStructureTests * * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:411; * * @test_Strategy: Test various Json Syntax Errors when reading a * JsonStructure. The tests trip various JsonParsingException conditions when * doing a read. * */ @Test public void negativeJsonStructureTests() { boolean pass = true; JsonReader reader = null; // Trip JsonParsingException for JsonReader.read() if incorrect // representation for array try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if incorrect representation for array."); LOGGER.info("Reading " + "[foo,10,\"name\":\"value\"]"); reader = Json .createReader(new StringReader("[foo,10,\"name\":\"value\"]")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonReader.read() if incorrect // representation for object try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if incorrect representation for object."); LOGGER.info("Reading " + "{\"name\":\"value\",1,2,3}"); reader = Json .createReader(new StringReader("{\"name\":\"value\",1,2,3}")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // incorrect representation {] try { LOGGER.info("Testing for incorrect representation '{]'"); reader = Json.createReader(new StringReader("{]")); LOGGER.info( "Calling reader.read() with incorrect representation should throw JsonParsingException"); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Missing [ try { LOGGER.info("Testing for missing '['"); reader = Json.createReader(new StringReader("{1,2]}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing ] try { LOGGER.info("Testing for missing ']'"); reader = Json.createReader(new StringReader("{[1,2}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing { try { LOGGER.info("Testing for missing '{'"); reader = Json.createReader(new StringReader("}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing } try { LOGGER.info("Testing for missing '}'"); reader = Json.createReader(new StringReader("{")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between array elements test case 1 try { LOGGER.info("Testing for missing ',' between array elements test case 1"); reader = Json.createReader(new StringReader("{[5\"foo\"]}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between array elements test case 2 try { LOGGER.info("Testing for missing ',' between array elements test case 2"); reader = Json.createReader(new StringReader("{[5{}]}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between object elements test case 1 try { LOGGER.info("Testing for missing ',' between object elements test case 1"); reader = Json.createReader(new StringReader("{\"foo\":\"bar\"5}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing , between object elements test case 2 try { LOGGER.info("Testing for missing ',' between object elements test case 2"); reader = Json.createReader(new StringReader("{\"one\":1[]}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing key name in object element try { LOGGER.info("Testing for missing key name in object element"); reader = Json.createReader(new StringReader("{:\"bar\"}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing value name in object element try { LOGGER.info("Testing for missing value name in object element"); reader = Json.createReader(new StringReader("{\"foo\":}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing double quote on a name try { LOGGER.info("Test for missing double quote on a name"); reader = Json.createReader(new StringReader("{name\" : \"value\"}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Missing double quote on a value try { LOGGER.info("Test for missing double quote on a value"); reader = Json.createReader(new StringReader("{\"name\" : value\"}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 1 try { LOGGER.info("Incorrect digit value -foo"); reader = Json.createReader(new StringReader("{\"number\" : -foo}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 2 try { LOGGER.info("Incorrect digit value +foo"); reader = Json.createReader(new StringReader("{\"number\" : +foo}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 3 try { LOGGER.info("Incorrect digit value -784foo"); reader = Json.createReader(new StringReader("{\"number\" : -784foo}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 4 try { LOGGER.info("Incorrect digit value +784foo"); reader = Json.createReader(new StringReader("{\"number\" : +784foo}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 5 try { LOGGER.info("Incorrect digit value 0.1E5E5"); reader = Json.createReader(new StringReader("{\"number\" : 0.1E5E5}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 6 try { LOGGER.info("Incorrect digit value 0.F10"); reader = Json.createReader(new StringReader("{\"number\" : 0.F10}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } // Incorrect digit value test case 7 try { LOGGER.info("Incorrect digit value string"); reader = Json.createReader(new StringReader("{\"number\" : string}")); JsonStructure value = reader.read(); pass = false; LOGGER.warning("Failed to throw JsonParsingException"); } catch (JsonParsingException e) { LOGGER.info("Got expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (reader != null) reader.close(); } assertTrue(pass, "negativeJsonStructureTests Failed"); } /* * @testName: jsonReaderIOErrorTests * * @assertion_ids: JSONP:JAVADOC:182; JSONP:JAVADOC:217; JSONP:JAVADOC:219; * JSONP:JAVADOC:410; * * @test_Strategy: Tests for JsonException for testable i/o errors. * */ @Test public void jsonReaderIOErrorTests() { boolean pass = true; String jsonArrayText = "[\"name1\",\"value1\"]"; String jsonObjectText = "{\"name1\":\"value1\"}"; // Trip JsonException if there is an i/o error on JsonReader.close() try { LOGGER.info( "Trip JsonException if there is an i/o error on JsonReader.close()."); LOGGER.info("Reading object " + jsonObjectText); InputStream is = JSONP_Util.getInputStreamFromString(jsonObjectText); MyBufferedInputStream mbi = new MyBufferedInputStream(is); try (JsonReader reader = Json.createReader(mbi)) { JsonObject jsonObject = reader.readObject(); LOGGER.info("jsonObject=" + jsonObject); mbi.setThrowIOException(true); LOGGER.info("Calling JsonReader.close()"); mbi.setThrowIOException(true); } LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException for JsonReader.read() if i/o error try { LOGGER.info("Trip JsonException for JsonReader.read() if i/o error."); LOGGER.info("Reading array " + jsonArrayText); MyBufferedReader mbr = new MyBufferedReader( new StringReader(jsonArrayText)); JsonReader reader = Json.createReader(mbr); mbr.setThrowIOException(true); LOGGER.info("Calling JsonReader.read()"); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException for JsonReader.readArray() if i/o error try { LOGGER.info("Trip JsonException for JsonReader.readArray() if i/o error."); LOGGER.info("Reading array " + jsonArrayText); MyBufferedReader mbr = new MyBufferedReader( new StringReader(jsonArrayText)); JsonReader reader = Json.createReader(mbr); mbr.setThrowIOException(true); LOGGER.info("Calling JsonReader.readArray()"); JsonArray jsonArray = reader.readArray(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException for JsonReader.readObject() if i/o error try { LOGGER.info("Trip JsonException for JsonReader.read() if i/o error."); LOGGER.info("Reading object " + jsonObjectText); MyBufferedReader mbr = new MyBufferedReader( new StringReader(jsonObjectText)); JsonReader reader = Json.createReader(mbr); mbr.setThrowIOException(true); LOGGER.info("Calling JsonReader.readObject()"); JsonObject jsonObject = reader.readObject(); LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonReaderIOErrorTests Failed"); } /* * @testName: invalidLiteralNamesTest * * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:411; * * @test_Strategy: This test trips various JsonParsingException conditions * when reading an uppercase literal name that must be lowercase per JSON RFC * for the literal values (true, false or null). * */ @Test public void invalidLiteralNamesTest() { boolean pass = true; JsonReader reader; // Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE // instead of true try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE instead of true."); LOGGER.info("Reading " + "[TRUE]"); reader = Json.createReader(new StringReader("[TRUE]")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE // instead of false try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE instead of false."); LOGGER.info("Reading " + "[FALSE]"); reader = Json.createReader(new StringReader("[FALSE]")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonReader.read() if invalid liternal NULL // instead of null try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if invalid liternal NULL instead of null."); LOGGER.info("Reading " + "[NULL]"); reader = Json.createReader(new StringReader("[NULL]")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE // instead of true try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE instead of true."); LOGGER.info("Reading " + "{\"true\":TRUE}"); reader = Json.createReader(new StringReader("{\"true\":TRUE}")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE // instead of false try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE instead of false."); LOGGER.info("Reading " + "{\"false\":FALSE}"); reader = Json.createReader(new StringReader("{\"false\":FALSE}")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonParsingException for JsonReader.read() if invalid liternal NULL // instead of null try { LOGGER.info( "Trip JsonParsingException for JsonReader.read() if invalid liternal NULL instead of null."); LOGGER.info("Reading " + "{\"null\":NULL}"); reader = Json.createReader(new StringReader("{\"null\":NULL}")); JsonStructure jsonStructure = reader.read(); LOGGER.warning("Did not get expected JsonParsingException"); pass = false; } catch (JsonParsingException e) { LOGGER.info("Caught expected JsonParsingException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "invalidLiteralNamesTest Failed"); } /* * @testName: jsonReader11Test * * @assertion_ids: JSONP:JAVADOC:646; JSONP:JAVADOC:583; JSONP:JAVADOC:584; * JSONP:JAVADOC:585; JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; * JSONP:JAVADOC:662; JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; * JSONP:JAVADOC:666; JSONP:JAVADOC:667; * * @test_Strategy: Tests JsonReader API methods added in JSON-P 1.1. */ @Test public void jsonReader11Test() { Reader readerTest = new Reader(); final TestResult result = readerTest.test(); result.eval(); } /* * @testName: testDuplicateKeysDefault * * @assertion_ids: JSONP:JAVADOC:681; * * @test_Strategy: Tests key strategy added in JSON-P 2.1. */ @Test public void testDuplicateKeysDefault() { Map config = new HashMap<>(); JsonReaderFactory factory = Json.createReaderFactory(config); String json = "{\"val1\":\"A\",\"val1\":\"B\"}"; JsonReader reader = factory.createReader(new StringReader(json)); JsonObject object = reader.readObject(); reader.close(); assertEquals("B", object.getString("val1")); } /* * @testName: testDuplicateKeysNone * * @assertion_ids: JSONP:JAVADOC:681; * * @test_Strategy: Tests key strategy added in JSON-P 2.1. */ @Test public void testDuplicateKeysNone() { Map config = new HashMap<>(); config.put(JsonConfig.KEY_STRATEGY, JsonConfig.KeyStrategy.NONE); JsonReaderFactory factory = Json.createReaderFactory(config); String json = "{\"val1\":\"A\",\"val1\":\"B\"}"; JsonReader reader = factory.createReader(new StringReader(json)); try { reader.readObject(); fail("It is expected a JsonException"); } catch (JsonException e) {} } /* * @testName: testDuplicateKeysFirst * * @assertion_ids: JSONP:JAVADOC:681; * * @test_Strategy: Tests key strategy added in JSON-P 2.1. */ @Test public void testDuplicateKeysFirst() { Map config = new HashMap<>(); config.put(JsonConfig.KEY_STRATEGY, JsonConfig.KeyStrategy.FIRST); JsonReaderFactory factory = Json.createReaderFactory(config); String json = "{\"val1\":\"A\",\"val1\":\"B\"}"; JsonReader reader = factory.createReader(new StringReader(json)); JsonObject object = reader.readObject(); reader.close(); assertEquals("A", object.getString("val1")); } /* * @testName: testDuplicateKeysLast * * @assertion_ids: JSONP:JAVADOC:681; * * @test_Strategy: Tests key strategy added in JSON-P 2.1. */ @Test public void testDuplicateKeysLast() { Map config = new HashMap<>(); config.put(JsonConfig.KEY_STRATEGY, JsonConfig.KeyStrategy.LAST); JsonReaderFactory factory = Json.createReaderFactory(config); String json = "{\"val1\":\"A\",\"val1\":\"B\"}"; JsonReader reader = factory.createReader(new StringReader(json)); JsonObject object = reader.readObject(); reader.close(); assertEquals("B", object.getString("val1")); } } Reader.java000066400000000000000000000213361451447132700335440ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonreadertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonreadertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.util.logging.Logger; import jakarta.json.Json; import jakarta.json.JsonException; import jakarta.json.JsonReader; import jakarta.json.JsonValue; import jakarta.json.stream.JsonParsingException; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for {@link JsonReader}. */ public class Reader { private static final Logger LOGGER = Logger.getLogger(Reader.class.getName()); /** Tests input data. */ private static final Object[] VALUES = new Object[] { SimpleValues.OBJ_VALUE, // readValue() // for // JsonObject SimpleValues.createEmptyArrayWithStr(), // readValue() for simple JsonArray SimpleValues.STR_VALUE, // readValue() for String SimpleValues.INT_VALUE, // readValue() for int SimpleValues.LNG_VALUE, // readValue() for long SimpleValues.DBL_VALUE, // readValue() for double SimpleValues.BIN_VALUE, // readValue() for BigInteger SimpleValues.BDC_VALUE, // readValue() for BigDecimal SimpleValues.BOOL_VALUE, // readValue() for boolean null // readValue() for null }; /** * Creates an instance of JavaScript Object Notation (JSON) compatibility * tests for {@link JsonReader}. */ Reader() { super(); } /** * {@link JsonReader} API methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonReader API methods added in JSON-P 1.1."); LOGGER.info("JsonReader API methods added in JSON-P 1.1."); testReadValue(result); testDoubleReadValue(result); testIOExceptionOnReadValue(result); testReadInvalidValue(result); return result; } /** * Test {@code JsonValue readValue()} method on all child types stored in * source data. * * @param result * Test suite result. */ private void testReadValue(final TestResult result) { for (Object value : VALUES) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - readValue() for " + typeName + " in source data"); final JsonValue jsonValue = SimpleValues.toJsonValue(value); final String data = JsonValueType.toStringValue(value); LOGGER.info(" - Data: " + data); final StringReader strReader = new StringReader(data); JsonValue outValue = null; try (final JsonReader reader = Json.createReader(strReader)) { outValue = reader.readValue(); } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("readValue()", "Caught JsonException: " + ex.getLocalizedMessage()); } if (operationFailed(jsonValue, outValue)) { result.fail("readValue()", "Reader output " + JsonAssert.valueToString(outValue) + " value shall be " + JsonAssert.valueToString(jsonValue)); } } } /** * Test {@code JsonValue readValue()} method with duplicated {@code JsonValue} * read call. Second call is expected to throw {@code IllegalStateException} * exception. * * @param result * Test suite result. */ private void testDoubleReadValue(final TestResult result) { for (Object value : VALUES) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info( " - duplicate readValue() for " + typeName + " in source data"); final String data = JsonValueType.toStringValue(value); final StringReader strReader = new StringReader(data); try (final JsonReader reader = Json.createReader(strReader)) { // 1st attempt to read the data shall pass reader.readValue(); try { // 2nd attempt to read the data shall throw IllegalStateException reader.readValue(); result.fail("readValue()", "Duplicate call of readValue() shall throw IllegalStateException"); } catch (IllegalStateException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("readValue()", "Duplicate call of readValue() shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("readValue()", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code JsonValue readValue()} method with read call that causes * IOException. IOException shall be encapsulated in JsonException. * * @param result * Test suite result. */ @SuppressWarnings("ConvertToTryWithResources") private void testIOExceptionOnReadValue(final TestResult result) { LOGGER.info(" - readValue() from already closed file reader"); File temp = null; JsonReader reader; // Close writer before calling write method. try { temp = File.createTempFile("testIOExceptionOnReadValue", ".txt"); LOGGER.info(" - Temporary file: " + temp.getAbsolutePath()); try (final FileWriter fileWriter = new FileWriter(temp)) { fileWriter.write(JsonValueType.toStringValue(SimpleValues.DEF_VALUE)); } final FileReader fileReader = new FileReader(temp); reader = Json.createReader(fileReader); fileReader.close(); } catch (IOException ex) { LOGGER.info("Caught IOException: " + ex.getLocalizedMessage()); result.fail("write(JsonValue)", "Caught IOException: " + ex.getLocalizedMessage()); return; } finally { if (temp != null) { temp.delete(); } } try { reader.readValue(); result.fail("readValue()", "Call of readValue() on already closed file reader shall throw JsonException"); } catch (JsonException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("readValue()", "Call of readValue() on already closed file reader shall throw JsonException, not " + t.getClass().getSimpleName()); } } /** * Test {@code JsonValue readValue()} method with read call on invalid JSON * data. JsonParsingException shall be thrown when reading invalid data. * * @param result * Test suite result. */ private void testReadInvalidValue(final TestResult result) { LOGGER.info(" - readValue() on invalid JSON data"); // Invalid JSON: starting an array, closing an object. final String data = "[" + SimpleValues.toJsonValue(SimpleValues.DEF_VALUE) + "}"; final StringReader strReader = new StringReader(data); JsonValue outValue = null; try (final JsonReader reader = Json.createReader(strReader)) { reader.readValue(); result.fail("readValue()", "Call of readValue() on invalid data shall throw JsonParsingException"); } catch (JsonParsingException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("readValue()", "Call of readValue() on invalid data shall throw JsonParsingException, not " + t.getClass().getSimpleName()); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonstreamingtests/000077500000000000000000000000001451447132700323005ustar00rootroot00000000000000ClientTests.java000066400000000000000000000230571451447132700353340ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonstreamingtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonstreamingtests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import jakarta.json.stream.*; import java.io.*; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* * @testName: streamingTest1 * * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:106; JSONP:JAVADOC:107; * JSONP:JAVADOC:184; * * @test_Strategy: Test Scenario: Generate stream of Json Text containing a * JsonArray Compare actual Json Text generated with expected Json Text for * equality Test passes if both JsonArray comparisons of Json Text are equal. * */ @Test public void streamingTest1() { JsonReader reader = null; try { // Set expected result String expJsonText = "[1,2,3,4,5,6,7,8,9,10]"; LOGGER.info("expJsonText=" + expJsonText); LOGGER.info("Generate stream of Json Text containing a JsonArray"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write(1).write(2).write(3).write(4).write(5) .write(6).write(7).write(8).write(9).write(10).writeEnd(); generator.close(); // Get actual result String actJsonText = JSONP_Util.removeWhitespace(sWriter.toString()); LOGGER.info("actJsonText=" + actJsonText); LOGGER.info("Compare expJsonText and actJsonText for equality"); assertTrue(JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText), "streamingTest1 Failed"); } catch (Exception e) { fail("streamingTest1 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: streamingTest2 * * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:106; JSONP:JAVADOC:107; * JSONP:JAVADOC:131; * * @test_Strategy: Test Scenario: Generate data containing a JsonArray to a * Writer stream. Read data from Writer stream containing a JsonArray. Write * JsonArray out to a Writer stream. Re-read data from Writer stream * containing a JsonArray. Compare initial JsonArray with subsequent JsonArray * for equality. Test passes if both JsonArrays are equal. * */ @Test public void streamingTest2() { JsonReader reader = null; try { LOGGER.info("Generate data containing a JsonArray"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartArray().write(2).write(4).write(6).write(8).write(10) .writeEnd(); generator.close(); LOGGER.info("Read data from Writer stream containing a JsonArray"); reader = Json.createReader(new StringReader(sWriter.toString())); JsonArray expJsonArray = reader.readArray(); LOGGER.info("Dump of expJsonArray"); JSONP_Util.dumpJsonArray(expJsonArray); LOGGER.info("Write JsonArray out to a Writer stream"); sWriter = new StringWriter(); JsonWriter writer = Json.createWriter(sWriter); writer.writeArray(expJsonArray); LOGGER.info("Close JsonWriter"); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("writerContents=" + writerContents); LOGGER.info("Re-read data from Writer stream containing a JsonArray"); reader = Json.createReader(new StringReader(writerContents)); JsonArray actJsonArray = reader.readArray(); LOGGER.info("Dump of actJsonArray"); JSONP_Util.dumpJsonArray(actJsonArray); LOGGER.info("Compare expJsonArray and actJsonArray for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray), "streamingTest2 Failed"); } catch (Exception e) { fail("streamingTest2 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: streamingTest3 * * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:106; JSONP:JAVADOC:110; * JSONP:JAVADOC:131; JSONP:JAVADOC:172; * * @test_Strategy: Test Scenario: Generate data containing a JsonObject to a * Write stream. Read data from Writer stream containing a JsonObject. Write * JsonObject out to a Writer stream. Parse data from Writer stream containing * a JsonObject stream. Test passes if parsing JsonObject events are correct. * */ @Test public void streamingTest3() { JsonReader reader = null; JsonParser parser = null; try { LOGGER.info("Generate data containing a JsonObject"); StringWriter sWriter = new StringWriter(); JsonGenerator generator = Json.createGenerator(sWriter); generator.writeStartObject().write("two", 2).write("false", false) .writeEnd(); generator.close(); LOGGER.info("Read data from Writer stream containing a JsonObject"); reader = Json.createReader(new StringReader(sWriter.toString())); JsonObject expJsonObject = reader.readObject(); LOGGER.info("Dump of expJsonObject"); JSONP_Util.dumpJsonObject(expJsonObject); LOGGER.info("Write JsonObject out to a Writer stream"); sWriter = new StringWriter(); JsonWriter writer = Json.createWriter(sWriter); writer.writeObject(expJsonObject); LOGGER.info("Close JsonWriter"); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = sWriter.toString(); LOGGER.info("writerContents=" + writerContents); LOGGER.info("Parse data from Writer stream containing a JsonObject"); parser = Json .createParser(JSONP_Util.getInputStreamFromString((writerContents))); JSONP_Util.resetParseErrs(); JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); JSONP_Util.testKeyIntegerValue(parser, "two", 2); JSONP_Util.testKeyFalseValue(parser, "false"); JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); int parseErrs = JSONP_Util.getParseErrs(); assertTrue( parseErrs == 0, "StreamingTest3 Failed. There were " + parseErrs + " parser errors that occurred." ); } catch (Exception e) { fail("streamingTest3 Failed: ", e); } finally { if (reader != null) reader.close(); } } /* * @testName: streamingTest4 * * @assertion_ids: JSONP:JAVADOC:178; JSONP:JAVADOC:187; JSONP:JAVADOC:110; * JSONP:JAVADOC:168; * * @test_Strategy: Test Scenario: Generate data containing a JsonObject to an * OutputStream. Compare expected JSON text from what was generated. Read data * from InputStream containing a JsonObject. Write JsonObject again out to an * OutputStream. Compare again expected JSON text from what was generated. * Test passes if JSON text comparisons are correct. * */ @Test public void streamingTest4() { boolean pass = true; JsonReader reader = null; JsonParser parser = null; String expJsonText = "{\"two\":2,\"false\":false}"; try { LOGGER.info("Generate data containing a JsonObject to an OutputStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = Json.createGenerator(baos); generator.writeStartObject().write("two", 2).write("false", false) .writeEnd(); baos.close(); generator.close(); LOGGER.info("Compare JSON text generated to what is expected."); if (!JSONP_Util.assertEqualsJsonText(expJsonText, JSONP_Util.removeWhitespace(baos.toString("UTF-8")))) pass = false; LOGGER.info("Read data from InputStream containing a JsonObject"); reader = Json.createReader( JSONP_Util.getInputStreamFromString(baos.toString("UTF-8"))); JsonObject expJsonObject = reader.readObject(); LOGGER.info("Close JsonReader"); reader.close(); LOGGER.info("Dump of expJsonObject"); JSONP_Util.dumpJsonObject(expJsonObject); LOGGER.info("Write JsonObject back out to an OutputStream"); baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriter(baos); writer.writeObject(expJsonObject); LOGGER.info("Close JsonWriter"); baos.close(); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String writerContents = baos.toString("UTF-8"); LOGGER.info("writerContents=" + writerContents); LOGGER.info("Compare again JSON text generated to what is expected."); if (!JSONP_Util.assertEqualsJsonText(expJsonText, JSONP_Util.removeWhitespace(writerContents))) pass = false; } catch (Exception e) { fail("streamingTest4 Failed: ", e); } assertTrue(pass, "streamingTest4 Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonstringtests/000077500000000000000000000000001451447132700316155ustar00rootroot00000000000000ClientTests.java000066400000000000000000000147231451447132700346510ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonstringtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonstringtests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonStringEqualsTest * * @assertion_ids: JSONP:JAVADOC:254; * * @test_Strategy: Tests JsonString equals method. Create 2 equal JsonStrings * and compare them for equality and expect true. Create 2 non-equal * JsonStrings and compare them for equality and expect false. */ @Test public void jsonStringEqualsTest() { boolean pass = true; try { LOGGER.info("Create sample JsonString 1 for testing"); JsonString string1 = (JsonString) JSONP_Util .createJsonString("Hello World"); LOGGER.info("string1=" + JSONP_Util.toStringJsonString(string1)); LOGGER.info("Create sample JsonString 2 for testing"); JsonString string2 = JSONP_Util.createJsonString("Hello World"); LOGGER.info("string2=" + JSONP_Util.toStringJsonString(string2)); LOGGER.info( "Call JsonString.equals() to compare 2 equal JsonStrings and expect true"); if (string1.equals(string2)) { LOGGER.info("JsonStrings are equal - expected."); } else { pass = false; LOGGER.warning("JsonStrings are not equal - unexpected."); } LOGGER.info("Create sample JsonString 1 for testing"); string1 = JSONP_Util.createJsonString("Hello World"); LOGGER.info("string1=" + JSONP_Util.toStringJsonString(string1)); LOGGER.info("Create sample JsonString 2 for testing"); string2 = JSONP_Util.createJsonString("Hello USA"); LOGGER.info("string2=" + JSONP_Util.toStringJsonString(string2)); LOGGER.info( "Call JsonString.equals() to compare 2 equal JsonStrings and expect false"); if (!string1.equals(string2)) { LOGGER.info("JsonStrings are not equal - expected."); } else { pass = false; LOGGER.warning("JsonStrings are equal - unexpected."); } } catch (Exception e) { fail("jsonStringEqualsTest Failed: ", e); } assertTrue(pass, "jsonStringEqualsTest Failed"); } /* * @testName: jsonStringHashCodeTest * * @assertion_ids: JSONP:JAVADOC:255; * * @test_Strategy: Tests JsonString equals method. Create 2 equal JsonStrings * and compare them for hashcode and expect true. Create 2 non-equal * JsonStrings and compare them for hashcode and expect false. */ @Test public void jsonStringHashCodeTest() { boolean pass = true; try { LOGGER.info("Create sample JsonString 1 for testing"); JsonString string1 = JSONP_Util.createJsonString("Hello World"); LOGGER.info("string1=" + JSONP_Util.toStringJsonString(string1)); LOGGER.info("string1.hashCode()=" + string1.hashCode()); LOGGER.info("Create sample JsonString 2 for testing"); JsonString string2 = JSONP_Util.createJsonString("Hello World"); LOGGER.info("string2=" + JSONP_Util.toStringJsonString(string2)); LOGGER.info("string2.hashCode()=" + string2.hashCode()); LOGGER.info( "Call JsonString.hashCode() to compare 2 equal JsonStrings and expect true"); if (string1.hashCode() == string2.hashCode()) { LOGGER.info("JsonStrings hashCode are equal - expected."); } else { pass = false; LOGGER.warning("JsonStrings hashCode are not equal - unexpected."); } LOGGER.info("Create sample JsonString 1 for testing"); string1 = JSONP_Util.createJsonString("Hello World"); LOGGER.info("string1=" + JSONP_Util.toStringJsonString(string1)); LOGGER.info("string1.hashCode()=" + string1.hashCode()); LOGGER.info("Create sample JsonString 2 for testing"); string2 = JSONP_Util.createJsonString("Hello USA"); LOGGER.info("string2=" + JSONP_Util.toStringJsonString(string2)); LOGGER.info("string2.hashCode()=" + string2.hashCode()); LOGGER.info( "Call JsonString.hashCode() to compare 2 equal JsonStrings and expect false"); if (string1.hashCode() != string2.hashCode()) { LOGGER.info("JsonStrings hashCode are not equal - expected."); } else { pass = false; LOGGER.warning("JsonStrings hashCode are equal - unexpected."); } } catch (Exception e) { fail("jsonStringHashCodeTest Failed: ", e); } assertTrue(pass, "jsonStringHashCodeTest Failed"); } /* * @testName: jsonStringGetCharsTest * * @assertion_ids: JSONP:JAVADOC:383; * * @test_Strategy: Tests JsonString getChars method. */ @Test public void jsonStringGetCharsTest() { boolean pass = true; String helloWorld = "Hello World"; try { LOGGER.info("Create sample JsonString for testing"); JsonString string = JSONP_Util.createJsonString(helloWorld); LOGGER.info("string=" + JSONP_Util.toStringJsonString(string)); LOGGER.info( "Call JsonString.getChars() to return the char sequence for the JSON string"); CharSequence cs = string.getChars(); LOGGER.info("charSequence=" + cs.toString()); LOGGER.info("Checking char sequence for equality to expected string contents"); if (!JSONP_Util.assertEquals(helloWorld, cs.toString())) pass = false; LOGGER.info("Checking char sequence for expected equality to string length"); if (!JSONP_Util.assertEquals(helloWorld.length(), cs.length())) pass = false; } catch (Exception e) { fail("jsonStringGetCharsTest Failed: ", e); } assertTrue(pass, "jsonStringGetCharsTest Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonvaluetests/000077500000000000000000000000001451447132700314235ustar00rootroot00000000000000ClientTests.java000066400000000000000000000317761451447132700344660ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonvaluetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonvaluetests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonValueTypesTest * * @assertion_ids: JSONP:JAVADOC:102; * * @test_Strategy: Test JsonValue.getValueType() API method call with all * JsonValue types. * */ @Test public void jsonValueTypesTest() { boolean pass = true; try { JsonValue.ValueType valueType; // Testing JsonValue.FALSE case LOGGER.info("Testing getValueType for JsonValue.FALSE value"); valueType = JsonValue.FALSE.getValueType(); if (valueType != JsonValue.ValueType.FALSE) { LOGGER.warning("Expected JSON FALSE value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON FALSE value"); // Testing JsonValue.TRUE case LOGGER.info("Testing getValueType for JsonValue.TRUE value"); valueType = JsonValue.TRUE.getValueType(); if (valueType != JsonValue.ValueType.TRUE) { LOGGER.warning("Expected JSON TRUE value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON TRUE value"); // Testing JsonValue.NULL case LOGGER.info("Testing getValueType for JsonValue.NULL value"); valueType = JsonValue.NULL.getValueType(); if (valueType != JsonValue.ValueType.NULL) { LOGGER.warning("Expected JSON NULL value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON NULL value"); // Testing JsonValue.String case LOGGER.info("Testing getValueType for JsonValue.String value"); valueType = JSONP_Util.createJsonString("string").getValueType(); if (valueType != JsonValue.ValueType.STRING) { LOGGER.warning("Expected JSON STRING value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON STRING value"); // Testing JsonValue.Number case LOGGER.info("Testing getValueType for JsonValue.Number value"); valueType = JSONP_Util.createJsonNumber(Integer.MAX_VALUE).getValueType(); if (valueType != JsonValue.ValueType.NUMBER) { LOGGER.warning("Expected JSON NUMBER value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON NUMBER value"); // Testing JsonValue.Array case LOGGER.info("Testing getValueType for JsonValue.Array value"); valueType = JSONP_Util.createJsonArrayFromString("[]").getValueType(); if (valueType != JsonValue.ValueType.ARRAY) { LOGGER.warning("Expected JSON ARRAY value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON ARRAY value"); // Testing JsonValue.Object case LOGGER.info("Testing getValueType for JsonValue.Object value"); valueType = JSONP_Util.createJsonObjectFromString("{}").getValueType(); if (valueType != JsonValue.ValueType.OBJECT) { LOGGER.warning("Expected JSON OBJECT value type but got instead " + valueType); pass = false; } else LOGGER.info("Got expected value type for JSON OBJECT value"); } catch (Exception e) { fail("jsonValueTypesTest Failed: ", e); } assertTrue(pass, "jsonValueTypesTest Failed"); } /* * @testName: jsonValueOfTest * * @assertion_ids: JSONP:JAVADOC:103; * * @test_Strategy: Test JsonValue.ValueType.valueOf() API method call with all * JsonValue types. * */ @Test public void jsonValueOfTest() { boolean pass = true; String valueTypeStrings[] = { "ARRAY", "FALSE", "NULL", "NUMBER", "OBJECT", "STRING", "TRUE" }; for (String valueTypeString : valueTypeStrings) { JsonValue.ValueType valueType; try { LOGGER.info( "Testing enum value for string constant name " + valueTypeString); valueType = JsonValue.ValueType.valueOf(valueTypeString); LOGGER.info("Got enum type " + valueType + " for enum string constant named " + valueTypeString); } catch (Exception e) { LOGGER.warning("Caught unexpected exception: " + e); pass = false; } } LOGGER.info("Testing negative test case for NullPointerException"); try { JsonValue.ValueType.valueOf(null); LOGGER.warning("did not get expected NullPointerException"); pass = false; } catch (NullPointerException e) { LOGGER.info("Got expected NullPointerException"); } catch (Exception e) { LOGGER.warning("Got unexpected exception " + e); pass = false; } LOGGER.info("Testing negative test case for IllegalArgumentException"); try { JsonValue.ValueType.valueOf("INVALID"); LOGGER.warning("did not get expected IllegalArgumentException"); pass = false; } catch (IllegalArgumentException e) { LOGGER.info("Got expected IllegalArgumentException"); } catch (Exception e) { LOGGER.warning("Got unexpected exception " + e); pass = false; } assertTrue(pass, "jsonValueOfTest Failed"); } /* * @testName: jsonValuesTest * * @assertion_ids: JSONP:JAVADOC:104; * * @test_Strategy: Test JsonValue.ValueType.values() API method call and * verify enums returned. * */ @Test public void jsonValuesTest() { LOGGER.info( "Testing API method JsonValue.ValueType.values() to return array of enums."); JsonValue.ValueType[] values = JsonValue.ValueType.values(); for (JsonValue.ValueType valueType : values) { String valueString = JSONP_Util.getValueTypeString(valueType); if (valueString == null) { fail("jsonValuesTest Failed. Got no value for enum " + valueType); } else LOGGER.info("Got " + valueString + " for enum " + valueType); } } /* * @testName: jsonValueToStringTest * * @assertion_ids: JSONP:JAVADOC:288; * * @test_Strategy: Test JsonValue.toString() API method call with various * JsonValue types. * */ @Test public void jsonValueToStringTest() { boolean pass = true; try { String stringValue; JsonValue jsonValue; // Testing JsonValue.FALSE case LOGGER.info("Testing JsonValue.toString() for JsonValue.FALSE value"); stringValue = JsonValue.FALSE.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("false")) { LOGGER.warning("Expected false"); pass = false; } else { LOGGER.info("Got " + stringValue); } // Testing JsonValue.TRUE case LOGGER.info("Testing JsonValue.toString() for JsonValue.TRUE value"); stringValue = JsonValue.TRUE.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("true")) { LOGGER.warning("Expected true"); pass = false; } else { LOGGER.info("Got " + stringValue); } // Testing JsonValue.NULL case LOGGER.info("Testing JsonValue.toString() for JsonValue.NULL value"); stringValue = JsonValue.NULL.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("null")) { LOGGER.warning("Expected null"); pass = false; } else { LOGGER.info("Got " + stringValue); } // Testing JsonString case LOGGER.info("Testing JsonValue.toString() for JsonString value"); jsonValue = JSONP_Util.createJsonString("string"); stringValue = jsonValue.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("\"string\"")) { LOGGER.warning("Expected \"string\""); pass = false; } else { LOGGER.info("Got " + stringValue); } // Testing JsonNumber case LOGGER.info("Testing JsonValue.toString() for JsonNumber value"); jsonValue = JSONP_Util.createJsonNumber(10); stringValue = jsonValue.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("10")) { LOGGER.warning("Expected 10"); pass = false; } else { LOGGER.info("Got " + stringValue); } // Testing JsonArray case LOGGER.info("Testing JsonValue.toString() for JsonArray value"); jsonValue = JSONP_Util.createJsonArrayFromString("[]"); stringValue = jsonValue.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("[]")) { LOGGER.warning("Expected []"); pass = false; } else { LOGGER.info("Got " + stringValue); } // Testing JsonObject case LOGGER.info("Testing JsonValue.toString() for JsonObject value"); jsonValue = JSONP_Util.createJsonObjectFromString("{}"); stringValue = jsonValue.toString(); LOGGER.info("stringValue=" + stringValue); if (!stringValue.equals("{}")) { LOGGER.warning("Expected {}"); pass = false; } else { LOGGER.info("Got " + stringValue); } } catch (Exception e) { fail("jsonValueToStringTest Failed: ", e); } assertTrue(pass, "jsonValueToStringTest Failed"); } /* * @testName: jsonValue11Test * * @assertion_ids: JSONP:JAVADOC:648; JSONP:JAVADOC:649; * * @test_Strategy: Tests JsonValue API methods added in JSON-P 1.1. */ @Test public void jsonValue11Test() { Value valueTest = new Value(); final TestResult result = valueTest.test(); result.eval(); } /* * @testName: jsonStructure11Test * * @assertion_ids: JSONP:JAVADOC:647; * * @test_Strategy: Tests JsonStructure API methods added in JSON-P 1.1. */ @Test public void jsonStructure11Test() { Structure structTest = new Structure(); final TestResult result = structTest.test(); result.eval(); } /* * @testName: jsonNumber21Test * * @assertion_ids: JSONP:JAVADOC:682; * * @test_Strategy: Tests Json.createValue(Number) API method added in JSON-P 2.1. */ @Test public void jsonNumber21Test() { assertEquals(Json.createValue(1), Json.createValue(Byte.valueOf((byte) 1))); assertEquals(Json.createValue(1).toString(), Json.createValue(Byte.valueOf((byte) 1)).toString()); assertEquals(Json.createValue(1), Json.createValue(Short.valueOf((short) 1))); assertEquals(Json.createValue(1).toString(), Json.createValue(Short.valueOf((short) 1)).toString()); assertEquals(Json.createValue(1), Json.createValue(Integer.valueOf(1))); assertEquals(Json.createValue(1).toString(), Json.createValue(Integer.valueOf(1)).toString()); assertEquals(Json.createValue(1L), Json.createValue(Long.valueOf(1))); assertEquals(Json.createValue(1L).toString(), Json.createValue(Long.valueOf(1)).toString()); assertEquals(Json.createValue(1D), Json.createValue(Float.valueOf(1))); assertEquals(Json.createValue(1D).toString(), Json.createValue(Float.valueOf(1)).toString()); assertEquals(Json.createValue(1D), Json.createValue(Double.valueOf(1))); assertEquals(Json.createValue(1D).toString(), Json.createValue(Double.valueOf(1)).toString()); assertEquals(Json.createValue(1), Json.createValue(new CustomNumber(1))); assertEquals(Json.createValue(1).toString(), Json.createValue(new CustomNumber(1)).toString()); } private static class CustomNumber extends Number { private static final long serialVersionUID = 1L; private final int num; private CustomNumber(int num) { this.num = num; } @Override public int intValue() { return num; } @Override public long longValue() { return num; } @Override public float floatValue() { return num; } @Override public double doubleValue() { return num; } @Override public String toString() { return Integer.toString(num); } } } Structure.java000066400000000000000000000466671451447132700342320ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonvaluetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonvaluetests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.PointerRFCObject; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonStructure; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for * {@link JsonStructure}. RFC 6901 JSON Pointer is being passed to * {@code JsonValue getValue(String)} method so whole JSON Pointer resolving * sample is being used to test this method. */ public class Structure { private static final Logger LOGGER = Logger.getLogger(Structure.class.getName()); /** * Creates an instance of JavaScript Object Notation (JSON) compatibility * tests for {@link JsonStructure}. */ Structure() { super(); } /** * {@link JsonStructure} API methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonStructure API methods added in JSON-P 1.1."); LOGGER.info("JsonStructure API methods added in JSON-P 1.1."); testResolveWholeDocument(result); testResolveEmptyName(result); testResolveSimpleArray(result); testResolveSimpleArrayItems(result); testResolvePathWithEncodedSlash(result); testResolvePathWithSlash(result); testResolvePathWithPercent(result); testResolvePathWithCaret(result); testResolvePathWithVerticalBar(result); testResolvePathWithBackSlash(result); testResolvePathWithDoubleQuotes(result); testResolvePathWithSpace(result); testResolvePathWithTilde(result); testResolvePathWithEncodedTilde(result); testResolvePathWithEncodedTildeOne(result); testResolveValidNumericIndexInArray(result); testResolveMemberAfterLastInArray(result); testResolveNonNumericIndexInArray(result); return result; } /** * Test RFC 6901 JSON Pointer resolving for the whole document path using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolveWholeDocument(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = value; verifyGetValue(result, check, value, PointerRFCObject.RFC_KEY_WHOLE); } /** * Test RFC 6901 JSON Pointer resolver for {@code "": 0} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolveEmptyName(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL2); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR2); } /** * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolveSimpleArray(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = PointerRFCObject.RFC_VAL1; verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR1); } /** * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]} array * elements using {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolveSimpleArrayItems(final TestResult result) { final String[] itemPtrs = new String[] { PointerRFCObject.RFC_PTR1_ITEM1, PointerRFCObject.RFC_PTR1_ITEM2 }; final String[] itemVals = new String[] { PointerRFCObject.RFC_VAL1_ITEM1, PointerRFCObject.RFC_VAL1_ITEM2 }; final JsonObject value = PointerRFCObject.createRFC6901Object(); for (int i = 0; i < itemPtrs.length; i++) { final JsonValue check = Json.createValue(itemVals[i]); verifyGetValue(result, check, value, itemPtrs[i]); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1} using * {@code JsonValue getValue(String)}. Character {@code '/'} is encoded as * {@code "~1"} string. * * @param result * Tests result record. */ private void testResolvePathWithEncodedSlash(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL3); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR3_ENC); } /** * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1} using * {@code JsonValue getValue(String)}. Character {@code '/'} is not encoded as * {@code "~1"} string. This results in invalid {@code "/a/b"} path and * resolving such path must throw an exception. * * @param result * Tests result record. */ private void testResolvePathWithSlash(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); verifyGetValueFail(result, value, PointerRFCObject.RFC_PTR3); } /** * Test RFC 6901 JSON Pointer resolver for {@code "c%d": 2} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolvePathWithPercent(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL4); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR4); } /** * Test RFC 6901 JSON Pointer resolver for {@code "e^f": 3} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolvePathWithCaret(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL5); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR5); } /** * Test RFC 6901 JSON Pointer resolver for {@code "g|h": 4} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolvePathWithVerticalBar(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL6); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR6); } /** * Test RFC 6901 JSON Pointer resolver for {@code "i\\j": 5} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolvePathWithBackSlash(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL7); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR7); } /** * Test RFC 6901 JSON Pointer resolver for {@code "k\"l": 6} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolvePathWithDoubleQuotes(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL8); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR8); } /** * Test RFC 6901 JSON Pointer resolver for {@code " ": 7} using * {@code JsonValue getValue(String)}. * * @param result * Tests result record. */ private void testResolvePathWithSpace(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL9); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR9); } /** * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8} without encoding * using {@code JsonValue getValue(String)}. Passing this test is not * mandatory. * {@see RFC 6901: 3. * Syntax} defines JSON pointer grammar as:
* {@code json-pointer = *( "/" reference-token )}
* {@code reference-token = *( unescaped / escaped )}
* {@code unescaped = %x00-2E / %x30-7D / %x7F-10FFFF}
* {@code escaped = "~" ( "0" / "1" )}
* Characters {@code '/'} and {@code '~'} are excluded from {@code unescaped}. * But having {@code '~'} outside escape sequence may be acceptable. * * @param result * Tests result record. */ private void testResolvePathWithTilde(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR10 + "\" pointer (optional)"); final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL10); boolean noError = true; try { final JsonValue out = value.getValue(PointerRFCObject.RFC_PTR10); if (operationFailed(check, out)) { noError = false; LOGGER.info(" - Pointer \"" + PointerRFCObject.RFC_KEY10 + "\" did not return expected value"); } } catch (JsonException e) { noError = false; LOGGER.info(" - Expected exception: " + e.getMessage()); } if (noError) { LOGGER.info( " - Pointer resolving accepts '~' outside escape sequence"); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8} using * {@code JsonValue getValue(String)}. Character {@code '~'} is encoded as * {@code "~0"} string. * * @param result * Tests result record. */ private void testResolvePathWithEncodedTilde(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL10); verifyGetValue(result, check, value, PointerRFCObject.RFC_KEY10_ENC); } /** * Test RFC 6901 JSON Pointer resolver for {@code "o~1p": 9} using * {@code JsonValue getValue(String)}. String {@code "~1"} is encoded as * {@code "~01"} String. Proper encoded sequences transformation is described * in chapter: * {@code "the string '~01' correctly becomes '~1' after transformation"}. * * @param result * Tests result record. */ private void testResolvePathWithEncodedTildeOne(final TestResult result) { final JsonStructure value = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL11); verifyGetValue(result, check, value, PointerRFCObject.RFC_PTR11_ENC); } /** * Test RFC 6901 JSON Pointer resolver for existing numeric indexes of an * array. {@see RFC * 6901: 4. Evaluation} chapter:
* If the currently referenced value is a JSON array, the reference token MUST * contain either: *
    *
  • characters comprised of digits (see ABNF below; note that leading zeros * are not allowed) that represent an unsigned base-10 integer value, making * the new referenced value the array element with the zero-based index * identified by the token
  • *
*/ private void testResolveValidNumericIndexInArray(final TestResult result) { LOGGER.info( " - getValue(String) resolving of pointer containing existing numeric array index"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createSimpleStringArray5(), SimpleValues.createSimpleIntArray5(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createSimpleObjectArray5() }; final JsonValue[] strings = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.STR_VALUE_1), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_2), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_3), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_4), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_5) }; final JsonValue[] ints = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.INT_VALUE_1), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_2), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_3), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_4), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_5) }; final JsonValue[] bools = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE), SimpleValues.toJsonValue(SimpleValues.BOOL_TRUE), SimpleValues.toJsonValue(SimpleValues.BOOL_TRUE), SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE), SimpleValues.toJsonValue(SimpleValues.BOOL_TRUE) }; final JsonValue[] objs = new JsonValue[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_5 }; final JsonValue[][] checks = new JsonValue[][] { strings, ints, bools, objs }; // Go trough all array types for (int i = 0; i < arraysIn.length; i++) { // Go trough all valid indexes in arrays for (int j = 0; j < 5; j++) { final String path = "/" + Integer.toString(j); try { final JsonValue out = arraysIn[i].getValue(path); if (operationFailed(checks[i][j], out)) { result.fail("getValue(String)", "Failed for \"" + path + "\" path"); } } catch (JsonException e) { result.fail("getValue(String)", "Exception: " + e.getMessage()); } } } } /** * Test RFC 6901 JSON Pointer resolver for character {@code '-'} marking the * end of an array. * {@see RFC 6901: 4. * Evaluation} chapter:
* If the currently referenced value is a JSON array, the reference token MUST * contain either: *
    *
  • exactly the single character "-", making the new referenced value the * (nonexistent) member after the last array element
  • *
* Note that the use of the "-" character to index an array will always result * in such an error condition because by definition it refers to a nonexistent * array element. Thus, applications of JSON Pointer need to specify how that * character is to be handled, if it is to be useful. */ private void testResolveMemberAfterLastInArray(final TestResult result) { LOGGER.info(" - getValue(String) resolving of array \"/-\" pointer"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray(), SimpleValues.createSimpleIntArray5(), SimpleValues.createBoolArray2(), SimpleValues.createSimpleObjectArray5() }; for (int i = 0; i < arraysIn.length; i++) { try { arraysIn[i].getValue("/-"); result.fail("getValue(String)", "Call of getValue(String) on \"" + "/-" + "\" shall throw JsonException"); } catch (JsonException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } } } /** * Test RFC 6901 JSON Pointer resolver for invalid index containing non * numeric characters on array. * {@see RFC 6901: 4. * Evaluation} chapter:
* {@code array-index = %x30 / ( %x31-39 *(%x30-39) )} grammar rule prohibits * indexes with anything else than sequence of digits. Index {@code '-'} is * being checked in another tests. The only exception is path for whole * document ({@code ""}) which must return the whole array. */ private void testResolveNonNumericIndexInArray(final TestResult result) { LOGGER.info( " - getValue(String) resolving of pointer containing non numeric array index"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray(), SimpleValues.createSimpleIntArray5(), SimpleValues.createBoolArray2(), SimpleValues.createSimpleObjectArray5() }; final String[] typeNames = new String[] { "empty", "String", "int", "boolean", "JsonObject" }; final String wholeDocument = ""; final String[] paths = new String[] { "/", "/1a", "/b4", "/name" }; // Go trough all array types for (int i = 0; i < arraysIn.length; i++) { try { final JsonValue wholeOut = arraysIn[i].getValue(wholeDocument); if (operationFailed(wholeOut, arraysIn[i])) { result.fail("getValue(String)", "Failed for \"" + wholeDocument + "\" path on " + typeNames[i] + " array"); } } catch (JsonException e) { result.fail("getValue(String)", "Failed for \"" + wholeDocument + "\" path on " + typeNames[i] + " array: " + e.getMessage()); } for (int j = 0; j < paths.length; j++) { try { final JsonValue out = arraysIn[i].getValue(paths[j]); result.fail("getValue(String)", "Succeeded for \"" + paths[j] + "\" path on " + typeNames[i] + " array"); } catch (JsonException e) { // There are too many combinations to log them. } } } } /** * Test helper: Verify {@code JsonValue getValue(String)} for given JSON path. * * @param result * Tests result record. */ private void verifyGetValue(final TestResult result, final JsonValue check, final JsonStructure value, final String path) { LOGGER.info(" - getValue(String) resolving of \"" + path + "\" pointer"); try { final JsonValue out = value.getValue(path); if (operationFailed(check, out)) { result.fail("getValue(String)", "Failed for \"" + path + "\" path"); } } catch (JsonException e) { result.fail("getValue(String)", "Exception: " + e.getMessage()); } } /** * Test helper: Verify {@code JsonValue getValue(String)} for given JSON path. * * @param result * Tests result record. */ private void verifyGetValueFail(final TestResult result, final JsonStructure value, final String path) { LOGGER.info( " - getValue(String) resolving of invalid \"" + path + "\" pointer"); try { value.getValue(path); result.fail("getValue(String)", "Call of getValue(String) on \"" + path + "\" shall throw JsonException"); } catch (JsonException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } Value.java000066400000000000000000000160761451447132700332750ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonvaluetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonvaluetests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for {@link JsonValue}. */ public class Value { private static final Logger LOGGER = Logger.getLogger(Value.class.getName()); /** * Creates an instance of JavaScript Object Notation (JSON) compatibility * tests for {@link JsonValue}. */ Value() { super(); } /** * {@link JsonValue} API methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonValue API methods added in JSON-P 1.1."); LOGGER.info("JsonValue API methods added in JSON-P 1.1."); testAsJsonObject(result); testAsJsonObjectOnNonObject(result); testAsJsonArray(result); testAsJsonArrayOnNonArray(result); return result; } /** * Test {@code JsonObject asJsonObject()} method on {@code JsonObject} * instances. * * @param result * Test suite result. */ private void testAsJsonObject(final TestResult result) { LOGGER.info(" - asJsonObject() on JsonObject instances"); final JsonObject[] values = { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObjectStr(), SimpleValues.createSimpleObjectInt(), SimpleValues.createSimpleObjectBool(), SimpleValues.createSimpleObjectObject(), SimpleValues.createCompoundObject() }; for (final JsonObject objValue : values) { final JsonValue value = objValue; final JsonObject out = objValue.asJsonObject(); if (operationFailed(objValue, out)) { result.fail("asJsonObject()", "Output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(objValue)); } } } /** * Test {@code JsonObject asJsonObject()} method on non {@code JsonObject} * instances. * * @param result * Test suite result. */ private void testAsJsonObjectOnNonObject(final TestResult result) { LOGGER.info(" - asJsonObject() on non JsonObject instances"); final JsonValue[] values = { SimpleValues.createEmptyArrayWithStr(), SimpleValues.createEmptyArrayWithInt(), SimpleValues.createEmptyArrayWithBool(), SimpleValues.createEmptyArrayWithObject(), SimpleValues.toJsonValue(SimpleValues.STR_VALUE), SimpleValues.toJsonValue(SimpleValues.INT_VALUE), SimpleValues.toJsonValue(SimpleValues.LNG_VALUE), SimpleValues.toJsonValue(SimpleValues.DBL_VALUE), SimpleValues.toJsonValue(SimpleValues.BIN_VALUE), SimpleValues.toJsonValue(SimpleValues.BDC_VALUE), SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), SimpleValues.toJsonValue(null) }; for (final JsonValue value : values) { try { value.asJsonObject(); result.fail("asJsonObject()", "Call of asJsonObject() on non JsonObject instance shall throw ClassCastException"); } catch (ClassCastException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("asJsonObject()", "Call of asJsonObject() on non JsonObject instance shall throw ClassCastException, not " + t.getClass().getSimpleName()); } } } /** * Test {@code JsonObject asJsonArray()} method on {@code JsonArray} * instances. * * @param result * Test suite result. */ private void testAsJsonArray(final TestResult result) { LOGGER.info(" - asJsonArray() on JsonArray instances"); final JsonArray[] values = { SimpleValues.createEmptyArray(), SimpleValues.createEmptyArrayWithStr(), SimpleValues.createEmptyArrayWithInt(), SimpleValues.createEmptyArrayWithBool(), SimpleValues.createEmptyArrayWithObject(), SimpleValues.createSimpleStringArray5(), SimpleValues.createSimpleIntArray5(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createSimpleObjectArray5() }; for (final JsonArray objValue : values) { final JsonValue value = objValue; final JsonArray out = objValue.asJsonArray(); if (operationFailed(objValue, out)) { result.fail("asJsonArray()", "Output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(objValue)); } } } /** * Test {@code JsonObject asJsonArray()} method on non {@code JsonArray} * instances. * * @param result * Test suite result. */ private void testAsJsonArrayOnNonArray(final TestResult result) { LOGGER.info(" - asJsonArray() on non JsonArray instances"); final JsonValue[] values = { SimpleValues.createSimpleObjectStr(), SimpleValues.createSimpleObjectInt(), SimpleValues.createSimpleObjectBool(), SimpleValues.createSimpleObjectObject(), SimpleValues.createCompoundObject(), SimpleValues.toJsonValue(SimpleValues.STR_VALUE), SimpleValues.toJsonValue(SimpleValues.INT_VALUE), SimpleValues.toJsonValue(SimpleValues.LNG_VALUE), SimpleValues.toJsonValue(SimpleValues.DBL_VALUE), SimpleValues.toJsonValue(SimpleValues.BIN_VALUE), SimpleValues.toJsonValue(SimpleValues.BDC_VALUE), SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), SimpleValues.toJsonValue(null) }; for (final JsonValue value : values) { try { value.asJsonArray(); result.fail("asJsonArray()", "Call of asJsonArray() on non JsonArray instance shall throw ClassCastException"); } catch (ClassCastException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("asJsonArray()", "Call of asJsonArray() on non JsonArray instance shall throw ClassCastException, not " + t.getClass().getSimpleName()); } } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonwriterfactorytests/000077500000000000000000000000001451447132700332135ustar00rootroot00000000000000ClientTests.java000066400000000000000000000272521451447132700362500ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonwriterfactorytests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.api.jsonwriterfactorytests; import ee.jakarta.tck.jsonp.common.JSONP_Util; import jakarta.json.*; import jakarta.json.stream.*; import java.io.*; import java.util.Map; import java.util.logging.Logger; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonWriterFactoryTest1 * * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:414; JSONP:JAVADOC:422; * JSONP:JAVADOC:452; JSONP:JAVADOC:463; * * @test_Strategy: Tests the JsonWriterFactory API. * * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); * JsonWriter writer1 = writerFactory.createWriter(Writer) JsonWriter writer2 * = writerFactory.createWriter(Writer) */ @Test public void jsonWriterFactoryTest1() { boolean pass = true; JsonWriter writer1 = null; JsonWriter writer2 = null; String expString = "{}"; String actString; JsonObject jsonObject = Json.createReader(new StringReader(expString)) .readObject(); try { LOGGER.info("Create JsonWriterFactory with Map with EMPTY config"); JsonWriterFactory writerFactory = Json .createWriterFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = writerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("--------------------------------------------------"); LOGGER.info("TEST CASE [JsonWriterFactory.createWriter(Writer)]"); LOGGER.info("--------------------------------------------------"); LOGGER.info("Create 1st JsonWriter using JsonWriterFactory"); Writer sWriter1 = new StringWriter(); writer1 = writerFactory.createWriter(sWriter1); if (writer1 == null) { LOGGER.warning("WriterFactory failed to create writer1"); pass = false; } else { writer1.writeObject(jsonObject); writer1.close(); } LOGGER.info("sWriter1=" + sWriter1.toString()); actString = JSONP_Util.removeWhitespace(sWriter1.toString()); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; LOGGER.info("Create 2nd JsonWriter using JsonWriterFactory"); Writer sWriter2 = new StringWriter(); writer2 = writerFactory.createWriter(sWriter2); if (writer2 == null) { LOGGER.warning("WriterFactory failed to create writer2"); pass = false; } else { writer2.writeObject(jsonObject); writer2.close(); } LOGGER.info("sWriter2=" + sWriter2.toString()); actString = JSONP_Util.removeWhitespace(sWriter2.toString()); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; } catch (Exception e) { fail("jsonWriterFactoryTest1 Failed: ", e); } assertTrue(pass, "jsonWriterFactoryTest1 Failed"); } /* * @testName: jsonWriterFactoryTest2 * * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:414; JSONP:JAVADOC:424; * JSONP:JAVADOC:452; JSONP:JAVADOC:463; * * @test_Strategy: Tests the JsonWriterFactory API. * * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); * JsonWriter writer1 = writerFactory.createWriter(OutputStream, Charset) * JsonWriter writer2 = writerFactory.createWriter(OutputStream, Charset) * * Create writer with both UTF-8 and UTF-16BE. */ @Test public void jsonWriterFactoryTest2() { boolean pass = true; JsonWriter writer1 = null; JsonWriter writer2 = null; String expString = "{}"; String actString; JsonObject jsonObject = Json.createReader(new StringReader(expString)) .readObject(); try { LOGGER.info("Create JsonWriterFactory with Map with EMPTY config"); JsonWriterFactory writerFactory = Json .createWriterFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = writerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info( "-----------------------------------------------------------------"); LOGGER.info( "TEST CASE [JsonWriterFactory.createWriter(OutputStream, Charset)]"); LOGGER.info( "-----------------------------------------------------------------"); LOGGER.info( "Create 1st JsonWriter using JsonWriterFactory with UTF-8 encoding"); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); writer1 = writerFactory.createWriter(baos1, JSONP_Util.UTF_8); if (writer1 == null) { LOGGER.warning("WriterFactory failed to create writer1"); pass = false; } else { writer1.writeObject(jsonObject); writer1.close(); } LOGGER.info("baos1=" + baos1.toString("UTF-8")); actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; LOGGER.info( "Create 2nd JsonWriter using JsonWriterFactory with UTF-8 encoding"); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); writer2 = writerFactory.createWriter(baos2, JSONP_Util.UTF_8); if (writer2 == null) { LOGGER.warning("WriterFactory failed to create writer2"); pass = false; } else { writer2.writeObject(jsonObject); writer2.close(); } LOGGER.info("baos2=" + baos2.toString("UTF-8")); actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; } catch (Exception e) { fail("jsonWriterFactoryTest2 Failed: ", e); } assertTrue(pass, "jsonWriterFactoryTest2 Failed"); } /* * @testName: jsonWriterFactoryTest3 * * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:414; JSONP:JAVADOC:423; * JSONP:JAVADOC:452; JSONP:JAVADOC:463; * * @test_Strategy: Tests the JsonWriterFactory API. * * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); * JsonWriter writer1 = writerFactory.createWriter(OutputStream) JsonWriter * writer2 = writerFactory.createWriter(OutputStream) */ @Test public void jsonWriterFactoryTest3() { boolean pass = true; JsonWriter writer1 = null; JsonWriter writer2 = null; String expString = "{}"; String actString; JsonObject jsonObject = Json.createReader(new StringReader(expString)) .readObject(); try { LOGGER.info("Create JsonWriterFactory with Map with EMPTY config"); JsonWriterFactory writerFactory = Json .createWriterFactory(JSONP_Util.getEmptyConfig()); LOGGER.info("Checking factory configuration properties"); Map config = writerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("--------------------------------------------------------"); LOGGER.info("TEST CASE [JsonWriterFactory.createWriter(OutputStream)]"); LOGGER.info("--------------------------------------------------------"); LOGGER.info("Create 1st JsonWriter using JsonWriterFactory"); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); writer1 = writerFactory.createWriter(baos1); if (writer1 == null) { LOGGER.warning("WriterFactory failed to create writer1"); pass = false; } else { writer1.writeObject(jsonObject); writer1.close(); } LOGGER.info("baos1=" + baos1.toString("UTF-8")); actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; LOGGER.info("Create 2nd JsonWriter using JsonWriterFactory"); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); writer2 = writerFactory.createWriter(baos2); if (writer2 == null) { LOGGER.warning("WriterFactory failed to create writer2"); pass = false; } else { writer2.writeObject(jsonObject); writer2.close(); } LOGGER.info("baos2=" + baos2.toString("UTF-8")); actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expString, actString)) pass = false; } catch (Exception e) { fail("jsonWriterFactoryTest3 Failed: ", e); } assertTrue(pass, "jsonWriterFactoryTest3 Failed"); } /* * @testName: jsonWriterFactoryTest4 * * @assertion_ids: JSONP:JAVADOC:452; JSONP:JAVADOC:463; * * @test_Strategy: Tests the JsonWriterFactory API. * * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); * Map config = JsonWriterFactory.getConfigInUse(); * * Test for the following 3 scenarios: 1) no supported provider property * (empty config) 2) supported provider property 3) supported and non * supported provider property */ @Test public void jsonWriterFactoryTest4() { boolean pass = true; JsonWriterFactory writerFactory; Map config; try { LOGGER.info("----------------------------------------------"); LOGGER.info("Test scenario1: no supported provider property"); LOGGER.info("----------------------------------------------"); LOGGER.info("Create JsonWriterFactory with Map with EMPTY config"); writerFactory = Json.createWriterFactory(JSONP_Util.getEmptyConfig()); config = writerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-------------------------------------------"); LOGGER.info("Test scenario2: supported provider property"); LOGGER.info("-------------------------------------------"); LOGGER.info("Create JsonWriterFactory with Map with FOO config"); writerFactory = Json.createWriterFactory(JSONP_Util.getFooConfig()); config = writerFactory.getConfigInUse(); String[] props = { JsonGenerator.PRETTY_PRINTING, }; if (!JSONP_Util.doConfigCheck(config, 0)) pass = false; LOGGER.info("-------------------------------------------------------------"); LOGGER.info("Test scenario3: supported and non supported provider property"); LOGGER.info("-------------------------------------------------------------"); LOGGER.info("Create JsonGeneratorFactory with Map with all config"); writerFactory = Json.createWriterFactory(JSONP_Util.getAllConfig()); config = writerFactory.getConfigInUse(); if (!JSONP_Util.doConfigCheck(config, 1, props)) pass = false; } catch (Exception e) { fail("jsonWriterFactoryTest4 Failed: ", e); } assertTrue(pass, "jsonWriterFactoryTest4 Failed"); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonwritertests/000077500000000000000000000000001451447132700316235ustar00rootroot00000000000000ClientTests.java000066400000000000000000001177311451447132700346620ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonwritertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonwritertests; import ee.jakarta.tck.jsonp.api.common.TestResult; import ee.jakarta.tck.jsonp.common.JSONP_Util; import ee.jakarta.tck.jsonp.common.MyBufferedWriter; import java.io.*; import java.util.*; import java.util.logging.Logger; import jakarta.json.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; // $Id$ public class ClientTests { private static final Logger LOGGER = Logger.getLogger(ClientTests.class.getName()); /* Tests */ /* * @testName: jsonWriterTest1 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:110; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. * Comparison is done by reading the JsonWriter output using JsonReader and * recreating the JsonObject and than performing a JsonObject comparison for * equality. * * Tests using API methods: Json.createWriter(Writer) and * writer.writeObject(JsonObject) * */ @Test public void jsonWriterTest1() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeObject(myJsonObject1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sWriter.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info( "Read the JsonObject back into 'myJsonObject2' using a JsonReader"); JsonReader reader = Json.createReader(new StringReader(contents)); JsonObject myJsonObject2 = (JsonObject) reader.read(); LOGGER.info("Compare myJsonObject1 and myJsonObject2 for equality"); assertTrue(JSONP_Util.assertEqualsJsonObjects(myJsonObject1, myJsonObject2), "jsonWriterTest1 Failed"); } catch (Exception e) { fail("jsonWriterTest1 Failed: ", e); } } /* * @testName: jsonWriterTest2 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:187; JSONP:JAVADOC:110; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. * Comparison is done by comparing the expected JsonObject text output with * the actual JsonObject text output from the JsonWriter for equality. * * Tests using API methods: Json.createWriter(OutputStream) and * writer.writeObject(JsonObject) * */ @Test public void jsonWriterTest2() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriter(baos); writer.writeObject(myJsonObject1); LOGGER.info("Close JsonWriter"); baos.close(); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonObjectText = baos.toString("UTF-8"); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + actJsonObjectText); LOGGER.info( "Compare expected JsonObject text with actual JsonObject text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonObjectText), "jsonWriterTest2 Failed" ); } catch (Exception e) { fail("jsonWriterTest2 Failed: ", e); } } /* * @testName: jsonWriterTest3 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:107; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. * Comparison is done by reading the JsonWriter output using JsonReader and * recreating the JsonArray and than performing a JsonArray comparison for * equality. * * Tests using API methods: Json.createWriter(Writer) and * writer.writeArray(JsonArray) * */ @Test public void jsonWriterTest3() { try { LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.writeArray(myJsonArray1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sWriter.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info("Read the JsonArray back into 'myJsonArray2' using a JsonReader"); JsonArray myJsonArray2; try (JsonReader reader = Json.createReader(new StringReader(contents))) { myJsonArray2 = (JsonArray) reader.read(); LOGGER.info("Close JsonReader"); } LOGGER.info("Compare myJsonArray1 and myJsonArray2 for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(myJsonArray1, myJsonArray2), "jsonWriterTest3 Failed"); } catch (Exception e) { fail("jsonWriterTest3 Failed: ", e); } } /* * @testName: jsonWriterTest4 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:187; JSONP:JAVADOC:107; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. * Comparison is done by comparing the expected JsonArray text output with the * actual JsonArray text output from the JsonWriter for equality. * * Tests using API methods: Json.createWriter(OutputStream) and * writer.writeArray(JsonArray) * */ @Test public void jsonWriterTest4() { try { LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriter(baos); writer.writeArray(myJsonArray1); LOGGER.info("Close JsonWriter"); baos.close(); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonArrayText = baos.toString("UTF-8"); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + actJsonArrayText); LOGGER.info( "Compare expected JsonArray text with actual JsonArray text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonArrayText), "jsonWriterTest4 Failed" ); } catch (Exception e) { fail("jsonWriterTest4 Failed: ", e); } } /* * @testName: jsonWriterTest5 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:424; JSONP:JAVADOC:110; * JSONP:JAVADOC:452; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. * Comparison is done by comparing the expected JsonObject text output with * the actual JsonObject text output from the JsonWriter for equality. * * Tests using API methods: * Json.createWriterFactory(Map).createWriter(OutputStream, Charset) * writer.writeObject(JsonObject) * * For encoding use UTF-16BE. */ @Test public void jsonWriterTest5() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_16BE); writer.writeObject(myJsonObject1); LOGGER.info("Close JsonWriter"); baos.close(); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonObjectText = JSONP_Util .removeWhitespace(baos.toString("UTF-16BE")); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + actJsonObjectText); LOGGER.info( "Compare expected JsonObject text with actual JsonObject text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonObjectText), "jsonWriterTest5 Failed" ); } catch (Exception e) { fail("jsonWriterTest5 Failed: ", e); } } /* * @testName: jsonWriterTest6 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:424; JSONP:JAVADOC:107; * JSONP:JAVADOC:452; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. * Comparison is done by comparing the expected JsonArray text output with the * actual JsonArray text output from the JsonWriter for equality. * * Tests using API methods: * Json.createWriterFactory.createWriter(OutputStream, Charset) * writer.writeArray(JsonArray) * * For encoding use UTF-8. */ @Test public void jsonWriterTest6() { try { LOGGER.info("Create a configuration with PRETT_PRINTING enabled."); Map config = JSONP_Util.getPrettyPrintingConfig(); LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(config).createWriter(baos, JSONP_Util.UTF_8); writer.writeArray(myJsonArray1); LOGGER.info("Close JsonWriter"); baos.close(); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonArrayText = JSONP_Util .removeWhitespace(baos.toString("UTF-8")); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + actJsonArrayText); LOGGER.info( "Compare expected JsonArray text with actual JsonArray text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonArrayText), "jsonWriterTest6 Failed" ); } catch (Exception e) { fail("jsonWriterTest6 Failed: ", e); } } /* * @testName: jsonWriterTest7 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:191; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. * Comparison is done by reading the JsonWriter output using JsonReader and * recreating the JsonObject and than performing a JsonObject comparison for * equality. * * Tests using API methods: Json.createWriter(Writer) and * writer.write(JsonStructure) * */ @Test public void jsonWriterTest7() { try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.write(myJsonObject1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sWriter.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info( "Read the JsonObject back into 'myJsonObject2' using a JsonReader"); JsonReader reader = Json.createReader(new StringReader(contents)); JsonObject myJsonObject2 = (JsonObject) reader.read(); LOGGER.info("Compare myJsonObject1 and myJsonObject2 for equality"); assertTrue(JSONP_Util.assertEqualsJsonObjects(myJsonObject1, myJsonObject2), "jsonWriterTest7 Failed"); } catch (Exception e) { fail("jsonWriterTest7 Failed: ", e); } } /* * @testName: jsonWriterTest8 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:191; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. * Comparison is done by reading the JsonWriter output using JsonReader and * recreating the JsonArray and than performing a JsonArray comparison for * equality. * * Tests using API methods: Json.createWriter(Writer) and * writer.write(JsonStructure) * */ @Test public void jsonWriterTest8() { try { LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); StringWriter sWriter = new StringWriter(); try (JsonWriter writer = Json.createWriter(sWriter)) { writer.write(myJsonArray1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String contents = sWriter.toString(); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + contents); LOGGER.info("Read the JsonArray back into 'myJsonArray2' using a JsonReader"); JsonReader reader = Json.createReader(new StringReader(contents)); JsonArray myJsonArray2 = (JsonArray) reader.read(); LOGGER.info("Compare myJsonArray1 and myJsonArray2 for equality"); assertTrue(JSONP_Util.assertEqualsJsonArrays(myJsonArray1, myJsonArray2), "jsonWriterTest8 Failed"); } catch (Exception e) { fail("jsonWriterTest8 Failed: ", e); } } /* * @testName: jsonWriterUTFEncodedTests * * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:423; JSONP:JAVADOC:452; * * @test_Strategy: Tests various JsonWriter API's to create a JsonObject. * * The output is written to an OutputStream using all supported UTF encodings * and read back as a string and filtered to remove whitespace and is compared * against an expected string. The following UTF encodings are tested: * * UTF8 UTF16 UTF16LE UTF16BE UTF32LE UTF32BE * * { "object":{"string":"string","number":1,"true":true,"false":false,"null": * null}, "array":["string", 1, true, false, null] } */ @Test public void jsonWriterUTFEncodedTests() { boolean pass = true; LOGGER.info( "Create expected JSON text with no whitespace for use in comparsion"); String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; try { LOGGER.info( "-----------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-8]"); LOGGER.info( "-----------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonWriter using UTF-8 encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_8); JSONP_Util.writeJsonObjectFromString(writer, expJson); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-8")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-8 encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing generation to UTF-8 encoding: " + e); } try { LOGGER.info( "------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-16]"); LOGGER.info( "------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonWriter using UTF-16 encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_16); JSONP_Util.writeJsonObjectFromString(writer, expJson); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-16")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-16 encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning("Exception occurred testing generation to UTF-16 encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-16LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonWriter using UTF-16LE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_16LE); JSONP_Util.writeJsonObjectFromString(writer, expJson); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-16LE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-16LE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16LE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-16LE encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-16BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonWriter using UTF-16BE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_16BE); JSONP_Util.writeJsonObjectFromString(writer, expJson); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-16BE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-16BE encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-32LE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonWriter using UTF-32LE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_32LE); JSONP_Util.writeJsonObjectFromString(writer, expJson); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-32LE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-32LE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32LE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-32LE encoding: " + e); } try { LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info( "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-32BE]"); LOGGER.info( "--------------------------------------------------------------------------------------------------"); LOGGER.info("Create JsonWriter using UTF-32BE encoding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) .createWriter(baos, JSONP_Util.UTF_32BE); JSONP_Util.writeJsonObjectFromString(writer, expJson); // Dump JsonText output LOGGER.info("Generated Output=" + baos.toString("UTF-32BE")); // Do comparison LOGGER.info( "Read the JSON text back from OutputStream using UTF-32BE encoding removing whitespace"); String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32BE")); if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) pass = false; } catch (Exception e) { pass = false; LOGGER.warning( "Exception occurred testing generation to UTF-32BE encoding: " + e); } assertTrue(pass, "jsonWriterUTFEncodedTests Failed"); } /* * @testName: jsonWriterWithConfigTest1 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:422; JSONP:JAVADOC:110; * JSONP:JAVADOC:452; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. * Comparison is done by comparing the expected JsonObject text output with * the actual JsonObject text output from the JsonWriter for equality. * * Tests using API methods: * Json.createWriterFactory(Map).createWriter(Writer) * writer.writeObject(JsonObject) * */ @Test public void jsonWriterWithConfigTest1() { try { LOGGER.info("Create a configuration with PRETT_PRINTING enabled."); Map config = JSONP_Util.getPrettyPrintingConfig(); LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); LOGGER.info("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); StringWriter swriter = new StringWriter(); try (JsonWriter writer = Json.createWriterFactory(config) .createWriter(swriter)) { writer.writeObject(myJsonObject1); LOGGER.info("Close JsonWriter"); } LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonObjectText = JSONP_Util .removeWhitespace(swriter.toString()); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + actJsonObjectText); LOGGER.info( "Compare expected JsonObject text with actual JsonObject text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonObjectText), "jsonWriterWithConfigTest1 Failed" ); } catch (Exception e) { fail("jsonWriterWithConfigTest1 Failed: ", e); } } /* * @testName: jsonWriterWithConfigTest2 * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:423; JSONP:JAVADOC:107; * * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. * Comparison is done by comparing the expected JsonArray text output with the * actual JsonArray text output from the JsonWriter for equality. * * Tests using API methods: * Json.createWriterFactory(Map).creatWriter(OutputStream) * writer.writeArray(JsonArray) * */ @Test public void jsonWriterWithConfigTest2() { try { LOGGER.info("Create a configuration with PRETT_PRINTING enabled."); Map config = JSONP_Util.getPrettyPrintingConfig(); LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); LOGGER.info("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter writer = Json.createWriterFactory(config).createWriter(baos); writer.writeArray(myJsonArray1); LOGGER.info("Close JsonWriter"); baos.close(); writer.close(); LOGGER.info("Save contents of the JsonWriter as a String"); String actJsonArrayText = JSONP_Util .removeWhitespace(baos.toString("UTF-8")); LOGGER.info("Dump contents of JsonWriter as a String"); LOGGER.info("JsonWriterContents=" + actJsonArrayText); LOGGER.info( "Compare expected JsonArray text with actual JsonArray text for equality"); assertTrue( JSONP_Util.assertEqualsJsonText(JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonArrayText), "jsonWriterWithConfigTest2 Failed" ); } catch (Exception e) { fail("jsonWriterWithConfigTest2 Failed: ", e); } } /* * @testName: jsonWriterExceptionTests * * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:109; * JSONP:JAVADOC:112; JSONP:JAVADOC:222; * * @test_Strategy: Test for JsonWriter exception test conditions. o * IllegalStateException * */ @Test public void jsonWriterExceptionTests() { boolean pass = true; JsonWriter writer = null; // IllegalStateException if writer.close() already called before // writer.writeArray(JsonArray) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create JsonWriter, write something and close it"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeArray(jsonArray); writer.close(); LOGGER.info( "IllegalStateException if writer.close() already called before writer.writeArray(JsonArray)"); writer.writeArray(jsonArray); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // IllegalStateException if writer.writeArray() called after // writer.writeArray(JsonArray) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create JsonWriter and write out array"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeArray(jsonArray); LOGGER.info( "IllegalStateException if writer.writeArray(JsonArray) called after writer.writeArray(JsonArray)"); writer.writeArray(jsonArray); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (writer != null) writer.close(); } // IllegalStateException if writer.writeObject() called after // writer.writeArray(JsonArray) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create sample JsonObject for testing"); JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create JsonWriter and write out array"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeArray(jsonArray); LOGGER.info( "IllegalStateException if writer.writeObject(JsonObject) called after writer.writeArray(JsonArray)"); writer.writeObject(jsonObject); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (writer != null) writer.close(); } // IllegalStateException if writer.close() already called before // writer.writeObject(JsonArray) try { LOGGER.info("Create sample JsonObject for testing"); JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create JsonWriter, write something and close it"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeObject(jsonObject); writer.close(); LOGGER.info( "IllegalStateException if writer.close() already called before writer.writeObject(JsonObject)"); writer.writeObject(jsonObject); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // IllegalStateException if writer.writeObject() called after // writer.writeObject(JsonObject) try { LOGGER.info("Create sample JsonObject for testing"); JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create JsonWriter and write out object"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeObject(jsonObject); LOGGER.info( "IllegalStateException if writer.writeObject(JsonObject) called after writer.writeObject(JsonObject)"); writer.writeObject(jsonObject); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (writer != null) writer.close(); } // IllegalStateException if writer.writeArray() called after // writer.writeObject(JsonObject) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create sample JsonObject for testing"); JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create JsonWriter and write out object"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeObject(jsonObject); LOGGER.info( "IllegalStateException if writer.writeArray(JsonArray) called after writer.writeObject(JsonObject)"); writer.writeArray(jsonArray); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (writer != null) writer.close(); } // IllegalStateException if writer.close() already called before // writer.write(JsonArray) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create JsonWriter, write something and close it"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.write(jsonArray); writer.close(); LOGGER.info( "IllegalStateException if writer.close() already called before writer.write(JsonArray)"); writer.write(jsonArray); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // IllegalStateException if writer.write(JsonArray) called after // writer.writeArray(JsonArray) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info("Create JsonWriter and write out array"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeArray(jsonArray); LOGGER.info( "IllegalStateException if writer.write(JsonArray) called after writer.writeArray(JsonArray)"); writer.write(jsonArray); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (writer != null) writer.close(); } // IllegalStateException if writer.write(JsonObject) called after // writer.writeJsonObject(JsonObject) try { LOGGER.info("Create sample JsonObject for testing"); JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info("Create JsonWriter and write out object"); StringWriter sWriter = new StringWriter(); writer = Json.createWriter(sWriter); writer.writeObject(jsonObject); LOGGER.info( "IllegalStateException if writer.write(JsonObject) called after writer.writeObject(JsonObject)"); writer.write(jsonObject); pass = false; LOGGER.warning("Failed to throw IllegalStateException"); } catch (IllegalStateException e) { LOGGER.info("Got expected IllegalStateException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } finally { if (writer != null) writer.close(); } assertTrue(pass, "jsonWriterExceptionTests Failed"); } /* * @testName: jsonWriterIOErrorTests * * @assertion_ids: JSONP:JAVADOC:108; JSONP:JAVADOC:111; JSONP:JAVADOC:221; * JSONP:JAVADOC:414; * * @test_Strategy: Tests for JsonException for testable i/o errors. * */ @Test public void jsonWriterIOErrorTests() { boolean pass = true; // Trip JsonException if there is an i/o error on JsonWriter.close() try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info( "Trip JsonException if there is an i/o error on JsonWriter.close()."); MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); try (JsonWriter writer = Json.createWriter(mbw)) { writer.writeObject(myJsonObject); mbw.setThrowIOException(true); LOGGER.info("Calling JsonWriter.close()"); } LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException if there is an i/o error on // JsonWriter.writeObject(JsonObject) try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info( "Trip JsonException if there is an i/o error on JsonWriter.writeObject(JsonObject)."); MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); try (JsonWriter writer = Json.createWriter(mbw)) { mbw.setThrowIOException(true); LOGGER.info("Calling JsonWriter.writeObject(JsonObject)"); writer.writeObject(myJsonObject); } LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException if there is an i/o error on // JsonWriter.writeArray(JsonArray) try { LOGGER.info("Create sample JsonArray for testing"); JsonArray myJsonArray = JSONP_Util.createSampleJsonArray(); LOGGER.info( "Trip JsonException if there is an i/o error on JsonWriter.writeArray(JsonArray)."); MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); try (JsonWriter writer = Json.createWriter(mbw)) { mbw.setThrowIOException(true); LOGGER.info("Calling JsonWriter.writeArray(JsonArray)"); writer.writeArray(myJsonArray); } LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } // Trip JsonException if there is an i/o error on // JsonWriter.write(JsonStructure) try { LOGGER.info("Create sample JsonObject for testing"); JsonObject myJsonObject = JSONP_Util.createSampleJsonObject(); LOGGER.info( "Trip JsonException if there is an i/o error on JsonWriter.write(JsonStructure)."); MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); try (JsonWriter writer = Json.createWriter(mbw)) { mbw.setThrowIOException(true); LOGGER.info("Calling JsonWriter.write(JsonStructure)"); writer.write(myJsonObject); } LOGGER.warning("Did not get expected JsonException"); pass = false; } catch (JsonException e) { LOGGER.info("Caught expected JsonException"); } catch (Exception e) { pass = false; LOGGER.warning("Caught unexpected exception: " + e); } assertTrue(pass, "jsonWriterIOErrorTests Failed"); } /* * @testName: jsonWriter11Test * * @assertion_ids: JSONP:JAVADOC:650; JSONP:JAVADOC:583; JSONP:JAVADOC:584; * JSONP:JAVADOC:585; JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; * JSONP:JAVADOC:662; JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; * JSONP:JAVADOC:666; JSONP:JAVADOC:667; * * @test_Strategy: Tests JsonWriter API methods added in JSON-P 1.1. */ @Test public void jsonWriter11Test() { ee.jakarta.tck.jsonp.api.jsonwritertests.Writer writerTest = new Writer(); final TestResult result = writerTest.test(); result.eval(); } } Writer.java000066400000000000000000000174361451447132700336760ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/jsonwritertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.jsonwritertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.logging.Logger; import jakarta.json.Json; import jakarta.json.JsonException; import jakarta.json.JsonValue; import jakarta.json.JsonWriter; import jakarta.json.stream.JsonParser; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests for {@link JsonWriter}. */ public class Writer { private static final Logger LOGGER = Logger.getLogger(Writer.class.getName()); /** Tests input data. */ private static final Object[] VALUES = new Object[] { SimpleValues.OBJ_VALUE, // write(JsonValue) // for // JsonObject SimpleValues.createEmptyArrayWithStr(), // write(JsonValue) for simple JsonArray SimpleValues.STR_VALUE, // write(JsonValue) for String SimpleValues.INT_VALUE, // write(JsonValue) for int SimpleValues.LNG_VALUE, // write(JsonValue) for long SimpleValues.DBL_VALUE, // write(JsonValue) for double SimpleValues.BIN_VALUE, // write(JsonValue) for BigInteger SimpleValues.BDC_VALUE, // write(JsonValue) for BigDecimal SimpleValues.BOOL_VALUE, // write(JsonValue) for boolean null // write(JsonValue) for null }; /** * Creates an instance of JavaScript Object Notation (JSON) compatibility * tests for {@link JsonWriter}. */ Writer() { super(); } /** * {@link JsonWriter} API methods added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonWriter API methods added in JSON-P 1.1."); LOGGER.info("JsonWriter API methods added in JSON-P 1.1."); testWriteValue(result); testDoubleWriteValue(result); testIOExceptionOnWriteValue(result); return result; } /** * Test {@code void write(JsonValue)} method on all child types of * {@code JsonValue}. * * @param result * Test suite result. */ private void testWriteValue(final TestResult result) { for (Object value : VALUES) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info(" - write(JsonValue) for " + typeName + " as an argument"); final JsonValue jsonValue = SimpleValues.toJsonValue(value); final StringWriter strWriter = new StringWriter(); try (final JsonWriter writer = Json.createWriter(strWriter)) { writer.write(jsonValue); } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("write(JsonValue)", "Caught JsonException: " + ex.getLocalizedMessage()); } final String data = strWriter.toString(); LOGGER.info(" - Data: " + data); final JsonParser parser = Json.createParser(new StringReader(data)); parser.next(); final JsonValue outValue = parser.getValue(); if (operationFailed(jsonValue, outValue)) { result.fail("write(JsonValue)", "Writer output " + JsonAssert.valueToString(outValue) + " value shall be " + JsonAssert.valueToString(jsonValue)); } } } /** * Test {@code void write(JsonValue)} method with duplicated {@code JsonValue} * write call. Second call is expected to throw {@code IllegalStateException} * exception. * * @param result * Test suite result. */ private void testDoubleWriteValue(final TestResult result) { for (Object value : VALUES) { final String typeName = JsonValueType.getType(value).name(); LOGGER.info( " - duplicate write(JsonValue) for " + typeName + " as an argument"); final JsonValue jsonValue = SimpleValues.toJsonValue(value); final StringWriter strWriter = new StringWriter(); try (final JsonWriter writer = Json.createWriter(strWriter)) { // 1st attempt to write the data shall pass writer.write(jsonValue); try { // 2nd attempt to write the data shall throw IllegalStateException writer.write(jsonValue); result.fail("write(JsonValue)", "Duplicate call of write(JsonValue) shall throw IllegalStateException"); } catch (IllegalStateException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("write(JsonValue)", "Duplicate call of write(JsonValue) shall throw IllegalStateException, not " + t.getClass().getSimpleName()); } } catch (JsonException ex) { LOGGER.info("Caught JsonException: " + ex.getLocalizedMessage()); result.fail("write(JsonValue)", "Caught JsonException: " + ex.getLocalizedMessage()); } } } /** * Test {@code void write(JsonValue)} method with write call that causes * IOException. IOException shall be encapsulated in JsonException. * * @param result * Test suite result. */ @SuppressWarnings("ConvertToTryWithResources") private void testIOExceptionOnWriteValue(final TestResult result) { LOGGER.info(" - write(JsonValue) into already closed file writer"); final JsonValue jsonValue = SimpleValues.toJsonValue(SimpleValues.DEF_VALUE); File temp = null; JsonWriter writer; // Close writer before calling write method. try { temp = File.createTempFile("testIOExceptionOnWriteValue", ".txt"); LOGGER.info(" - Temporary file: " + temp.getAbsolutePath()); final FileWriter fileWriter = new FileWriter(temp); writer = Json.createWriter(fileWriter); fileWriter.close(); } catch (IOException ex) { LOGGER.info("Caught IOException: " + ex.getLocalizedMessage()); result.fail("write(JsonValue)", "Caught IOException: " + ex.getLocalizedMessage()); return; } finally { if (temp != null) { temp.delete(); } } try { writer.write(jsonValue); result.fail("write(JsonValue)", "Call of write(JsonValue) on already closed file writer shall throw JsonException"); } catch (JsonException ex) { LOGGER.info(" - Expected exception: " + ex.getMessage()); } catch (Throwable t) { result.fail("write(JsonValue)", "Call of write(JsonValue) on already closed file writer shall throw JsonException, not " + t.getClass().getSimpleName()); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/000077500000000000000000000000001451447132700305145ustar00rootroot00000000000000MergeAddValue.java000066400000000000000000000147311451447132700337530ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonObject; import java.util.logging.Logger; // $Id$ /** * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility * tests.
* Checks scenario described in * {@see RFC 7396: 1. * Introduction}: If the provided merge patch contains members that do not * appear within the target, those members are added. */ public class MergeAddValue extends MergeCommon { private static final Logger LOGGER = Logger.getLogger(MergeAddValue.class.getName()); /** * Creates an instance of RFC 7396 value adding test. */ MergeAddValue() { super(); } /** * Test RFC 7396: Adding non existing values. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "RFC 7396: Add non existing values"); LOGGER.info("Testing RFC 7396: Add non existing values"); testStringOnEmptyObject(result); testStringOnsimpleObject(result); testIntOnEmptyObject(result); testIntOnsimpleObject(result); testBoolOnEmptyObject(result); testBoolOnsimpleObject(result); testObjectOnEmptyObject(result); testObjectOnsimpleObject(result); return result; } /** * Test RFC 7396 patch and diff for {@code String} on empty JSON object. * * @param result * Tests result record. */ private void testStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject patch = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectStr(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testStringOnsimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectWithStr(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on empty JSON object. * * @param result * Tests result record. */ private void testIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject patch = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectInt(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testIntOnsimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectWithInt(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. * * @param result * Tests result record. */ private void testBoolOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject patch = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectBool(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testBoolOnsimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectWithBool(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonObject} on empty JSON object. * * @param result * Tests result record. */ private void testObjectOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonObject on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject patch = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createSimpleObjectObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonObject} on compound JSON * object. * * @param result * Tests result record. */ private void testObjectOnsimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on compound JSON object"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject patch = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createCompoundObjectWithObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } } MergeCommon.java000066400000000000000000000156101451447132700335130ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonValue; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests.
*/ public abstract class MergeCommon { /** Message content: "MERGE" operation. */ private static final String MERGE_STR = "MERGE"; /** Message content: "DIFF" operation. */ private static final String DIFF_STR = "DIFF"; /** Message content template for test failure log message: patch. */ private static final String TEST_FAIL_PATCH = "Patch "; /** Message content template for test failure log message: failed on. */ private static final String TEST_FAIL_ON = " failed on "; /** Message content template for test failure log message: value. */ private static final String TEST_FAIL_VAL = " value"; /** Message content template for test failure log message: patch. */ private static final String TEST_FAIL_FROM = "Diff from "; /** Message content template for test failure log message: failed on. */ private static final String TEST_FAIL_TO = " to "; /** Message content template for test failure log message: value. */ private static final String TEST_FAIL_FAIL = " failed"; /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @param message * Assert message. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out, final String message) { return out == null || !JsonAssert.assertEquals(check, out, message); } /** * Test helper: Verify merge of JSON patch on provided JSON value and verify * result using provided expected JSON value. * * @param result * Test suite result. * @param in * Source JSON value to be modified. * @param patch * JSON patch to be done on source value. * @param check * Expected modified JSON object (used for operation check). */ protected void simpleMerge(final TestResult result, final JsonValue in, final JsonValue patch, final JsonValue check) { final JsonValue out = Json.createMergePatch(patch).apply(in); if (operationFailed(check, out, MERGE_STR + " mismatch")) { final String targetClassName = in.getValueType().name().toLowerCase(); result.fail(testName(MERGE_STR, targetClassName), testMergeMessage(JsonAssert.valueToString(in), JsonAssert.valueToString(patch))); } } /** * Test helper: Verify diff on provided JSON values and verify result using * provided expected JSON value. * * @param result * Test suite result. * @param src * Source JSON value for diff. * @param target * Target JSON value for diff. * @param diff * Expected diff JSON object (used for operation check). */ protected void simpleDiff(final TestResult result, final JsonValue src, final JsonValue target, final JsonValue diff) { final JsonValue out = Json.createMergeDiff(src, target).toJsonValue(); if (operationFailed(diff, out, DIFF_STR + " mismatch")) { final String srcClassName = src.getValueType().name().toLowerCase(); final String targetClassName = target.getValueType().name().toLowerCase(); result.fail(testName(DIFF_STR, srcClassName, targetClassName), testDiffMessage(JsonAssert.valueToString(src), JsonAssert.valueToString(target))); } } /** * Build test name for test failure log message. * * @param operation * Name of operation. * @param targetType * Name of the target (JSON value being modified) value type. * @return Test name for test failure log message. */ protected String testName(final String operation, final String targetType) { final StringBuilder sb = new StringBuilder( operation.length() + targetType.length() + 1); sb.append(operation); sb.append(' '); sb.append(targetType); return sb.toString(); } /** * Build test name for test failure log message. * * @param operation * Name of operation. * @param srcType * Name of the source (JSON value being used for modification) value * type. * @param targetType * Name of the target (JSON value being modified) value type. * @return Test name for test failure log message. */ protected String testName(final String operation, final String srcType, final String targetType) { final StringBuilder sb = new StringBuilder( operation.length() + srcType.length() + targetType.length() + 2); sb.append(operation); sb.append(' '); sb.append(srcType); sb.append(','); sb.append(targetType); return sb.toString(); } /** * Build message content for test failure log message. * * @param in * Source JSON value to be modified. * @param patch * JSON patch to be done on source value. * @return Log message content. */ protected String testMergeMessage(final String in, final String patch) { final StringBuilder sb = new StringBuilder( TEST_FAIL_PATCH.length() + TEST_FAIL_ON.length() + TEST_FAIL_VAL.length() + patch.length() + in.length()); sb.append(TEST_FAIL_PATCH); sb.append(patch); sb.append(TEST_FAIL_ON); sb.append(in); sb.append(TEST_FAIL_VAL); return sb.toString(); } /** * Build message content for test failure log message. * * @param src * Source JSON value for diff. * @param target * Target JSON value for diff. * @return Log message content. */ protected String testDiffMessage(final String src, final String target) { final StringBuilder sb = new StringBuilder( TEST_FAIL_FROM.length() + TEST_FAIL_TO.length() + TEST_FAIL_FAIL.length() + src.length() + target.length()); sb.append(TEST_FAIL_FROM); sb.append(src); sb.append(TEST_FAIL_TO); sb.append(target); sb.append(TEST_FAIL_FAIL); return sb.toString(); } } MergeNonObject.java000066400000000000000000000215711451447132700341470ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility * tests.
* Checks scenario described in * {@see RFC 7396: 1. * Introduction}: If the patch is anything other than an object, the result * will always be to replace the entire target with the entire patch. */ public class MergeNonObject extends MergeCommon { private static final Logger LOGGER = Logger.getLogger(MergeNonObject.class.getName()); /** * Creates an instance of RFC 7396 non object patch test. */ MergeNonObject() { super(); } /** * Test RFC 7396: Non object patch. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 7396: Non object patch"); LOGGER.info("Testing RFC 7396: Non object patch"); testStringOnEmptyObject(result); testStringOnSimpleObject(result); testStringOnSimpleArray(result); testIntOnEmptyObject(result); testIntOnSimpleObject(result); testIntOnSimpleArray(result); testBoolOnEmptyObject(result); testBoolOnSimpleObject(result); testBoolOnSimpleArray(result); testArrayOnEmptyObject(result); testArrayOnCompoundObject(result); testArrayOnSimpleArray(result); return result; } /** * Test RFC 7396 patch and diff for {@code String} on empty JSON object. * * @param result * Tests result record. */ private void testStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonValue patch = Json.createValue(SimpleValues.STR_VALUE); final JsonValue check = Json.createValue(SimpleValues.STR_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code String} on empty JSON object. * * @param result * Tests result record. */ private void testStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithStr(); final JsonValue patch = Json.createValue(SimpleValues.STR_VALUE); final JsonValue check = Json.createValue(SimpleValues.STR_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code String} on empty JSON array. * * @param result * Tests result record. */ private void testStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array"); final JsonArray in = SimpleValues.createStringArray2(); final JsonValue patch = Json.createValue(SimpleValues.STR_VALUE); final JsonValue check = Json.createValue(SimpleValues.STR_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on empty JSON object. * * @param result * Tests result record. */ private void testIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonValue patch = Json.createValue(SimpleValues.INT_VALUE); final JsonValue check = Json.createValue(SimpleValues.INT_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on empty JSON object. * * @param result * Tests result record. */ private void testIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithInt(); final JsonValue patch = Json.createValue(SimpleValues.INT_VALUE); final JsonValue check = Json.createValue(SimpleValues.INT_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on empty JSON array. * * @param result * Tests result record. */ private void testIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array"); final JsonArray in = SimpleValues.createIntArray2(); final JsonValue patch = Json.createValue(SimpleValues.INT_VALUE); final JsonValue check = Json.createValue(SimpleValues.INT_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. * * @param result * Tests result record. */ private void testBoolOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonValue patch = SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE); final JsonValue check = SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. * * @param result * Tests result record. */ private void testBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithBool(); final JsonValue patch = SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE); final JsonValue check = SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on empty JSON array. * * @param result * Tests result record. */ private void testBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array"); final JsonArray in = SimpleValues.createBoolArray2(); final JsonValue patch = SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE); final JsonValue check = SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonArray} on empty JSON object. * * @param result * Tests result record. */ private void testArrayOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonArray on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonArray patch = SimpleValues.createStringArray1(); final JsonArray check = SimpleValues.createStringArray1(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonArray} on empty JSON object. * * @param result * Tests result record. */ private void testArrayOnCompoundObject(final TestResult result) { LOGGER.info(" - for JsonArray on compound JSON object"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonValue patch = SimpleValues.createStringArray2(); final JsonValue check = SimpleValues.createStringArray2(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonArray} on empty JSON array. * * @param result * Tests result record. */ private void testArrayOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonArray on simple JSON array"); final JsonArray in = SimpleValues.createBoolArray2(); final JsonValue patch = SimpleValues.createIntArray2(); final JsonValue check = SimpleValues.createIntArray2(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } } MergeRFCSample.java000066400000000000000000000052111451447132700340330ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.MergeRFCObject; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonObject; import java.util.logging.Logger; // $Id$ /** * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility * tests.
* Test based on * {@see RFC 7396: 3. * Example} objects. */ public class MergeRFCSample extends MergeCommon { private static final Logger LOGGER = Logger.getLogger(MergeRFCSample.class.getName()); /** * Creates an instance of RFC 7396 value replacing test. */ MergeRFCSample() { super(); } /** * Test RFC 7396: Adding non existing values. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 7396: Example JSON object"); LOGGER.info("Testing RFC 7396: Example JSON object"); testMerge(result); testDiff(result); return result; } /** * Test RFC 7396 patch for example objects. * * @param result * Tests result record. */ private void testMerge(final TestResult result) { LOGGER.info(" - merge"); final JsonObject in = MergeRFCObject.createRFCSourceObject(); final JsonObject patch = MergeRFCObject.createRFCPatchObject(); final JsonObject check = MergeRFCObject.createRFCTargetObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 diff for example objects. * * @param result * Tests result record. */ private void testDiff(final TestResult result) { LOGGER.info(" - diff"); final JsonObject in = MergeRFCObject.createRFCSourceObject(); final JsonObject diff = MergeRFCObject.createRFCPatchObject(); final JsonObject out = MergeRFCObject.createRFCTargetObject(); simpleDiff(result, in, out, diff); } } MergeRemoveValue.java000066400000000000000000000150001451447132700345060ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonObject; import java.util.logging.Logger; // $Id$ /** * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility * tests.
* Checks scenario described in * {@see RFC 7396: 1. * Introduction}: {@code null} values in the merge patch are given special * meaning to indicate the removal of existing values in the target. */ public class MergeRemoveValue extends MergeCommon { private static final Logger LOGGER = Logger.getLogger(MergeRemoveValue.class.getName()); /** * Creates an instance of RFC 7396 value removal test. */ MergeRemoveValue() { super(); } /** * Test RFC 7396: Removing existing values. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "RFC 7396: Remove existing values"); LOGGER.info("Testing RFC 7396: Remove existing values"); testStringOnEmptyObject(result); testStringOnsimpleObject(result); testIntOnEmptyObject(result); testIntOnsimpleObject(result); testBoolOnEmptyObject(result); testBoolOnsimpleObject(result); testObjectOnEmptyObject(result); testObjectOnsimpleObject(result); return result; } /** * Test RFC 7396 patch and diff for {@code String} on empty JSON object. * * @param result * Tests result record. */ private void testStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject patch = SimpleValues.createPatchRemoveStr(); final JsonObject check = SimpleValues.createEmptyObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testStringOnsimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithStr(); final JsonObject patch = SimpleValues.createPatchRemoveStr(); final JsonObject check = SimpleValues.createSimpleObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on empty JSON object. * * @param result * Tests result record. */ private void testIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject patch = SimpleValues.createPatchRemoveInt(); final JsonObject check = SimpleValues.createEmptyObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testIntOnsimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithInt(); final JsonObject patch = SimpleValues.createPatchRemoveInt(); final JsonObject check = SimpleValues.createSimpleObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. * * @param result * Tests result record. */ private void testBoolOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject patch = SimpleValues.createPatchRemoveBool(); final JsonObject check = SimpleValues.createEmptyObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testBoolOnsimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithBool(); final JsonObject patch = SimpleValues.createPatchRemoveBool(); final JsonObject check = SimpleValues.createSimpleObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonObject} on empty JSON object. * * @param result * Tests result record. */ private void testObjectOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonObject to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectObject(); final JsonObject patch = SimpleValues.createPatchRemoveObject(); final JsonObject check = SimpleValues.createEmptyObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testObjectOnsimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on compoubnd JSON object"); final JsonObject in = SimpleValues.createCompoundObjectWithObject(); final JsonObject patch = SimpleValues.createPatchRemoveObject(); final JsonObject check = SimpleValues.createCompoundObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } } MergeReplaceValue.java000066400000000000000000000102141451447132700346260ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonObject; import java.util.logging.Logger; // $Id$ /** * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility * tests.
* Checks scenario described in * {@see RFC 7396: 1. * Introduction}: If the target does contain the member, the value is * replaced. */ public class MergeReplaceValue extends MergeCommon { private static final Logger LOGGER = Logger.getLogger(MergeReplaceValue.class.getName()); /** * Creates an instance of RFC 7396 value replacing test. */ MergeReplaceValue() { super(); } /** * Test RFC 7396: Adding non existing values. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "RFC 7396: Replace existing values"); LOGGER.info("Testing RFC 7396: Replace existing values"); testStringOnsimpleObject(result); testIntOnsimpleObject(result); testBoolOnsimpleObject(result); testObjectOnsimpleObject(result); return result; } /** * Test RFC 7396 patch and diff for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testStringOnsimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectMoveStr(); final JsonObject check = SimpleValues.createSimpleObjectMoveStr(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testIntOnsimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectMoveInt(); final JsonObject check = SimpleValues.createSimpleObjectMoveInt(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testBoolOnsimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectMoveBool(); final JsonObject check = SimpleValues.createSimpleObjectMoveBool(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } /** * Test RFC 7396 patch and diff for {@code JsonObject} on compound JSON * object. * * @param result * Tests result record. */ private void testObjectOnsimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject patch = SimpleValues.createSimpleObjectMoveObject(); final JsonObject check = SimpleValues.createSimpleObjectMoveObject(); simpleMerge(result, in, patch, check); simpleDiff(result, in, check, patch); } } MergeTests.java000066400000000000000000000115741451447132700333720ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/mergetests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.mergetests; import ee.jakarta.tck.jsonp.api.common.TestResult; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; // $Id$ /** * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility * tests.
* {@see RFC 7396}. */ public class MergeTests { /** * Test JSON-P API response on * {@see RFC 7396: 1. * Introduction}: If the provided merge patch contains members that do not * appear within the target, those members are added. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonMergeAddValueTest * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; * JSONP:JAVADOC:617; JSONP:JAVADOC:620; JSONP:JAVADOC:654; * JSONP:JAVADOC:655; * @test_Strategy: Test API response on various JSON values. */ @Test public void jsonMergeAddValueTest() { MergeAddValue addTest = new MergeAddValue(); final TestResult result = addTest.test(); result.eval(); } /** * Test JSON-P API response on * {@see RFC 7396: 1. * Introduction}: If the target does contain the member, the value is * replaced. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonMergeReplaceValueTest * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; * @test_Strategy: Test API response on various JSON values. */ @Test public void jsonMergeReplaceValueTest() { MergeReplaceValue replaceTest = new MergeReplaceValue(); final TestResult result = replaceTest.test(); result.eval(); } /** * Test JSON-P API response on * {@see RFC 7396: 1. * Introduction}: {@code null} values in the merge patch are given special * meaning to indicate the removal of existing values in the target. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonMergeRemoveValueTest * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; * @test_Strategy: Test API response on various JSON values. */ @Test public void jsonMergeRemoveValueTest() { MergeRemoveValue removeTest = new MergeRemoveValue(); final TestResult result = removeTest.test(); result.eval(); } /** * Test JSON-P API response on * {@see RFC 7396: 1. * Introduction}: If the patch is anything other than an object, the * result will always be to replace the entire target with the entire patch. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonMergeNonObjectTest * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; * JSONP:JAVADOC:583; JSONP:JAVADOC:584; * @test_Strategy: Test API response on various JSON values. */ @Test public void jsonMergeNonObjectTest() { MergeNonObject nonObjTest = new MergeNonObject(); final TestResult result = nonObjTest.test(); result.eval(); } /** * Test JSON-P API response on Test based on * {@see RFC 7396: 3. * Example} objects. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonMergeRFCSampleTest * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; * @test_Strategy: Test API response on RFC example objects. */ @Test public void jsonMergeRFCSampleTest() { MergeRFCSample rfcSampleTest = new MergeRFCSample(); final TestResult result = rfcSampleTest.test(); result.eval(); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/000077500000000000000000000000001451447132700305145ustar00rootroot00000000000000CommonOperation.java000066400000000000000000000410511451447132700344120ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonPatch; import jakarta.json.JsonPatchBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests. */ public abstract class CommonOperation { private static final Logger LOGGER = Logger.getLogger(CommonOperation.class.getName()); /** Message content template for test failure log message: operation name. */ private static final String TEST_FAIL_OP = " operation"; /** Message content template for test failure log message: path. */ private static final String TEST_FAIL_FOR = " for "; /** Message content template for test failure log message: failed. */ private static final String TEST_FAIL_FAI = " failed"; /** * Message content template for test failure log message: on target type * prefix. */ private static final String TEST_FAIL_ON1 = " on JSON "; /** * Message content template for test failure log message: on target type * suffix. */ private static final String TEST_FAIL_ON2 = " value"; /** * Message content template for test failure log message: patching execution * method. */ private static final String TEST_FAIL_MET = " using "; /** * Creates an instance of JavaScript Object Notation (JSON) compatibility * tests. */ protected CommonOperation() { super(); } /** * Tested operation name, e.g. {@code "ADD"}, {@code "REPLACE"}, * {@code "MOVE"}. Child class callback. * * @return Operation name to be used in logs. */ protected abstract String operationName(); /** * Create and initialize patch builder to contain patch operation to be * applied. Child class callback. * * @param path * JSON path of operation. * @param value * JSON value used in patch operation. * @return Patch builder containing operation to be applied. */ protected abstract JsonPatchBuilder createOperationBuilder(final String path, final Object value); /** * Update patch builder to contain next patch operation to be applied. Child * class callback. * * @param builder * JSON patch builder to update. * @param path * JSON path of operation. * @param value * JSON value used in patch operation. * @return Patch builder containing operation to be applied. */ protected abstract JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value); /** * Test helper: Verify simple operation on provided JSON value and verify * result using provided expected JSON value. Operation execution is done * using all known methods to build and apply JSON patch. * * @param result * Test suite result. * @param in * JSON value to be modified. * @param check * Expected modified JSON object (used for operation check). * @param path * JSON path of operation. * @param value * JSON value used in patch operation. */ protected void simpleOperation(final TestResult result, final JsonValue in, final JsonValue check, final String path, final Object value) { final JsonPatchBuilder builder = createOperationBuilder(path, value); final JsonPatch patch = builder.build(); JsonValue out; try { out = SimpleValues.patchApply(patch, in); } catch (JsonException e) { out = null; LOGGER.info( " Exception for path \"" + path + "\" on " + JsonAssert.valueToString(in)); LOGGER.info(" " + e.getMessage()); } if (operationFailed(check, out)) { final String targetClassName = in.getValueType().name().toLowerCase(); final String operation = JsonAssert.valueToString(patch.toJsonArray()); LOGGER.info(" " + operation); result.fail(testName(path, targetClassName), testMessage(operation, path, JsonAssert.valueToString(in))); } } /** * Test helper: Verify set of operations on provided JSON value and verify * result using provided expected JSON value. Verification is done using all * known methods to build and apply JSON patch. This method allows custom * patching of JSON array. Used for operations without value operand, e.g. * REMOVE. Operation builder callback will receive {@code null} as value. * * @param result * Test suite result. * @param in * JSON array to be modified. * @param check * Expected modified JSON array (used for operation check). * @param paths * JSON paths array of operations. */ protected void complexOperation(final TestResult result, final JsonArray in, final JsonArray check, final String[] paths) { final Object[] values = new Object[paths.length]; for (int i = 0; i < paths.length; i++) { values[i] = null; } complexOperation(result, in, check, paths, values); } /** * Test helper: Verify set of operations on provided JSON value and verify * result using provided expected JSON value. Verification is done using all * known methods to build and apply JSON patch. This method allows custom * patching of JSON array. * * @param result * Test suite result. * @param in * JSON array to be modified. * @param check * Expected modified JSON array (used for operation check). * @param paths * JSON paths array of operations. Pairs of {@code paths[i]} and * {@code values[i]} are used for individual operations. * @param values * JSON values array used in patch operations. */ protected void complexOperation(final TestResult result, final JsonArray in, final JsonArray check, final String[] paths, final Object[] values) { if (paths.length != values.length) { throw new IllegalArgumentException( "Number of paths does not match number of indexes"); } final JsonPatchBuilder builder = prepareComplexBuilder(paths, values); final JsonPatch patch = builder.build(); final JsonValue out = SimpleValues.patchApply(patch, in); if (operationFailed(check, out)) { final String operations = JsonAssert.valueToString(patch.toJsonArray()); final String targetClassName = in.getValueType().name().toLowerCase(); LOGGER.info(" " + operations); result.fail(testName(paths, targetClassName), testMessage(operations, paths, JsonAssert.valueToString(in))); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } /** * Builds JSON patch builder with set of operations stored in {@code paths} * and {@code values}. * * @param paths * JSON paths array of operations. Pairs of {@code paths[i]} and * {@code values[i]} are used for individual operations. * @param values * JSON values array used in patch operations. */ private JsonPatchBuilder prepareComplexBuilder(final String[] paths, final Object[] values) { JsonPatchBuilder builder = Json.createPatchBuilder(); for (int i = 0; i < paths.length; i++) { builder = updateOperationBuilder(builder, paths[i], values[i]); } return builder; } /** * Test helper: Verify that operation on provided JSON value fails. Operation * execution is done using all known methods to build and apply JSON patch. * * @param result * Test suite result. * @param in * JSON value to be modified. * @param path * JSON path of operation. * @param value * JSON value used in patch operation. */ protected void simpleOperationFail(final TestResult result, final JsonValue in, final String path, final Object value) { try { final JsonPatch patch = createOperationBuilder(path, value).build(); SimpleValues.patchApply(patch, in); final String targetClassName = in.getValueType().name().toLowerCase(); final String operation = JsonAssert.valueToString(patch.toJsonArray()); LOGGER.info( " Failed for path \"" + path + "\" on " + JsonAssert.valueToString(in)); LOGGER.info(" " + operation); result.fail(testName(path, targetClassName), testMessage(operation, path, JsonAssert.valueToString(in))); } catch (JsonException e) { // There are too many combinations to log them. // LOGGER.info(" - Expected exception: "+e.getMessage()); } } /** * Get source class name. * * @param value * JSON value to search for class name. * @return Class name of provided JSON value or {@code null} when this value * has been {@code null}. */ protected String getSrcName(final Object value) { return value != null ? value.getClass().getSimpleName() : null; } /** * Get source classes names. * * @param values * JSON values to search for class name. * @return Class name of provided JSON value or {@code null} when this value * has been {@code null}. */ protected String[] getSrcNames(final Object[] values) { if (values == null) { return null; } final String[] names = new String[values.length]; for (int i = 0; i < values.length; i++) { names[i] = values[i] != null ? values[i].getClass().getSimpleName() : null; } return names; } /** * Build test name for test failure log message. * * @param path * JSON patch operation source path. * @param targetType * Name of target (JSON value being modified) value type. * @return Test name for test failure log message. */ protected String testName(final String path, final String targetType) { final String operationName = operationName(); final int pathLen = path != null ? path.length() + 1 : 0; final StringBuilder sb = new StringBuilder( operationName.length() + pathLen + targetType.length() + 1); sb.append(operationName); if (pathLen > 0) { sb.append(' '); sb.append(path); } sb.append(' '); sb.append(targetType); return sb.toString(); } /** * Build test name for test failure log message. * * @param paths * JSON patch operation source paths. * @param targetType * Name of target (JSON value being modified) value type. * @return Test name for test failure log message. */ protected String testName(final String[] paths, final String targetType) { final String operationName = operationName(); final int pathsLen = paths != null ? paths.length : 0; int pathsSize = 0; for (int i = 0; i < pathsLen; i++) { pathsSize += paths[i] != null ? paths[i].length() : SimpleValues.NULL.length(); if (i > 0) { pathsSize += 1; } } if (pathsLen > 1) { pathsSize += 2; } final StringBuilder sb = new StringBuilder( operationName.length() + pathsSize + targetType.length() + 2); sb.append(operationName); sb.append(' '); if (pathsLen > 1) { sb.append('['); } for (int i = 0; i < pathsLen; i++) { if (i > 0) { sb.append(','); } sb.append(paths[i] != null ? paths[i] : SimpleValues.NULL); } if (pathsLen > 1) { sb.append(']'); } sb.append(' '); sb.append(targetType); return sb.toString(); } /** * Build message content for test failure log message. * * @param operation * JSON patch operation being executed. * @param path * JSON patch operation source path. * @param value * Target value being modified. * @return Log message content. */ protected String testMessage(final String operation, final String path, final String value) { final int tarLen = value != null ? TEST_FAIL_ON1.length() + TEST_FAIL_ON2.length() + value.length() : 0; final StringBuilder sb = new StringBuilder( operation.length() + TEST_FAIL_OP.length() + TEST_FAIL_FOR.length() + path.length() + TEST_FAIL_FAI.length() + tarLen); sb.append(operation); sb.append(TEST_FAIL_OP); sb.append(TEST_FAIL_FOR); sb.append(path); sb.append(TEST_FAIL_FAI); if (tarLen > 0) { sb.append(TEST_FAIL_ON1); sb.append(value); sb.append(TEST_FAIL_ON2); } return sb.toString(); } /** * Build message content for test failure log message. * * @param operation * JSON patch operation being executed. * @param paths * JSON patch operation source paths. * @param value * Target value being modified. * @return Log message content. */ protected String testMessage(final String operation, final String[] paths, final String value) { final int tarLen = value != null ? TEST_FAIL_ON1.length() + TEST_FAIL_ON2.length() + value.length() : 0; final int pathsLen = paths != null ? paths.length : 0; int pathsSize = 0; for (int i = 0; i < pathsLen; i++) { pathsSize += paths[i] != null ? paths[i].length() : SimpleValues.NULL.length(); if (i > 0) { pathsSize += 1; } } if (pathsLen > 1) { pathsSize += 2; } final StringBuilder sb = new StringBuilder( operation.length() + TEST_FAIL_OP.length() + TEST_FAIL_FOR.length() + pathsSize + TEST_FAIL_FAI.length() + tarLen); sb.append(operation); sb.append(TEST_FAIL_OP); sb.append(TEST_FAIL_FOR); if (pathsLen > 1) { sb.append('['); } for (int i = 0; i < pathsLen; i++) { if (i > 0) { sb.append(','); } sb.append(paths[i] != null ? paths[i] : SimpleValues.NULL); } if (pathsLen > 1) { sb.append(']'); } sb.append(TEST_FAIL_FAI); if (tarLen > 0) { sb.append(TEST_FAIL_ON1); sb.append(value); sb.append(TEST_FAIL_ON2); } return sb.toString(); } /** * Build message content for test failure log message. * * @param paths * JSON patch operation source path. * @param targetType * Name of target (JSON value being modified) value type. * @return Log message content. */ protected String testMessage(final String[] paths, final String targetType) { final String operationName = operationName(); final int tarLen = targetType != null ? TEST_FAIL_ON1.length() + TEST_FAIL_ON2.length() + targetType.length() : 0; int pathsLen = 0; for (int i = 0; i < paths.length; i++) { pathsLen += paths[i] != null ? paths[i].length() : SimpleValues.NULL.length(); if (i > 0) { pathsLen += 1; } } if (paths.length > 1) { pathsLen += 2; } final StringBuilder sb = new StringBuilder( operationName.length() + TEST_FAIL_OP.length() + TEST_FAIL_FOR.length() + pathsLen + TEST_FAIL_FAI.length() + tarLen); sb.append(operationName); sb.append(TEST_FAIL_OP); sb.append(TEST_FAIL_FOR); if (paths.length > 1) { sb.append('['); } for (int i = 0; i < paths.length; i++) { if (i > 0) { sb.append(','); } sb.append(paths[i] != null ? paths[i] : SimpleValues.NULL); } if (paths.length > 1) { sb.append(']'); } sb.append(TEST_FAIL_FAI); if (tarLen > 0) { sb.append(TEST_FAIL_ON1); sb.append(targetType); sb.append(TEST_FAIL_ON2); } return sb.toString(); } } PatchCreate.java000066400000000000000000000106341451447132700334670ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.*; import java.util.logging.Logger; // $Id$ /** * JavaScript Object Notation (JSON) compatibility tests: {@link JsonPatch} API * factory methods added in JSON-P 1.1.
*/ public class PatchCreate { private static final Logger LOGGER = Logger.getLogger(PatchCreate.class.getName()); /** * Creates an instance of {@link JsonPatch} API factory methods added in * JSON-P 1.1 test. */ PatchCreate() { super(); } /** * Test {@link JsonPatch} factory method added in JSON-P 1.1. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonPatch API factory methods added in JSON-P 1.1."); LOGGER.info("JsonPatch API factory methods added in JSON-P 1.1."); testCreateDiff(result); testCreatePatch(result); testCreatePatchBuilder(result); return result; } /** * Test {@link Json#createDiff(JsonStructure,JsonStructure)} method. * * @param result * Test suite result. */ private void testCreateDiff(final TestResult result) { LOGGER.info(" - Json#createDiff(JsonStructure,JsonStructure)"); final JsonObject src = SimpleValues.createSimpleObject(); final JsonObject trg = SimpleValues.createSimpleObjectWithStr(); final JsonPatch patch = Json.createDiff(src, trg); final JsonObject out = patch.apply(src); if (operationFailed(trg, out)) { result.fail("createDiff(JsonStructure,JsonStructure)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(trg)); } } /** * Test {@link Json#createPatch(JsonArray)} method. * * @param result * Test suite result. */ private void testCreatePatch(final TestResult result) { LOGGER.info(" - Json#createPatch(JsonArray)"); final JsonObject src = SimpleValues.createSimpleObject(); final JsonObject trg = SimpleValues.createSimpleObjectWithStr(); final JsonArray patchArray = Json.createDiff(src, trg).toJsonArray(); final JsonPatch patch = Json.createPatch(patchArray); final JsonObject out = patch.apply(src); if (operationFailed(trg, out)) { result.fail("createPatch(JsonArray)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(trg)); } } /** * Test {@link Json#createPatchBuilder(JsonArray)} method. * * @param result * Test suite result. */ private void testCreatePatchBuilder(final TestResult result) { LOGGER.info(" - Json#createPatchBuilder(JsonArray)"); final JsonObject src = SimpleValues.createSimpleObject(); final JsonObject trg = SimpleValues.createSimpleObjectWithStr(); final JsonArray patchArray = Json.createDiff(src, trg).toJsonArray(); final JsonPatchBuilder patchBuilder = Json.createPatchBuilder(patchArray); final JsonObject out = patchBuilder.build().apply(src); if (operationFailed(trg, out)) { result.fail("createPatchBuilder(JsonArray)", "Builder output " + JsonAssert.valueToString(out) + " value shall be " + JsonAssert.valueToString(trg)); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null || !JsonAssert.assertEquals(check, out); } } PatchOperationAdd.java000066400000000000000000000561621451447132700346430ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonPatch; import jakarta.json.JsonPatchBuilder; import jakarta.json.JsonValue; import jakarta.json.JsonStructure; import jakarta.json.Json; import jakarta.json.JsonPointer; import java.util.logging.Logger; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Implements * {@see RFC 6902: * 4.1. add} tests. */ class PatchOperationAdd extends CommonOperation { private static final Logger LOGGER = Logger.getLogger(PatchOperationAdd.class.getName()); /** Tested operation name. */ private final String OPERATION = "ADD"; /** * Creates an instance of RFC 6902 add operation test. */ PatchOperationAdd() { super(); } /** * Test RFC 6902 add operation. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6902 add operation"); LOGGER.info("Testing RFC 6902 add operation:"); testAddStringOnEmptyObject(result); testAddStringOnSimpleObject(result); testAddStringOnEmptyArray(result); testAddStringOnSimpleArray(result); testAddStringOnSimpleArray2(result); testAddIntOnEmptyObject(result); testAddIntOnSimpleObject(result); testAddIntOnEmptyArray(result); testAddIntOnSimpleArray(result); testAddIntOnSimpleArray2(result); testAddBooleanOnEmptyObject(result); testAddBooleanOnSimpleObject(result); testAddBooleanOnEmptyArray(result); testAddBooleanOnSimpleArray(result); testAddBooleanOnSimpleArray2(result); testAddObjectOnEmptyObject(result); testAddObjectOnSimpleObject(result); testAddObjectOnEmptyArray(result); testAddObjectOnSimpleArray(result); testAddObjectOnSimpleArray2(result); testAddArrayToReplaceObject(result); testAddArrayToReplaceDocument(result); testAddStringArrayToStringArray(result); testAddStringToNonExistingObject(result); return result; } /** * Test RFC 6902 add operation for {@code String} on empty JSON object. * * @param result * Tests result record. */ private void testAddStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectStr(); simpleOperation(result, in, check, SimpleValues.STR_PATH, SimpleValues.STR_VALUE); } /** * Test RFC 6902 add operation for {@code String} on empty JSON array. Only * allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testAddStringOnEmptyArray(final TestResult result) { LOGGER.info(" - for String on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithStr(); simpleOperation(result, in, check, "/0", SimpleValues.STR_VALUE); } /** * Test RFC 6902 add operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testAddStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject check = SimpleValues.createSimpleObjectWithStr(); simpleOperation(result, in, check, SimpleValues.STR_PATH, SimpleValues.STR_VALUE); } /** * Test RFC 6902 add operation for {@code String} on simple JSON array. Using * index {@code 0} to add {@code String} before already existing element and * index {@code 1} to add {@code String} after already existing element. * * @param result * Tests result record. */ private void testAddStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 1"); final JsonArray in = SimpleValues.createStringArray1(); final JsonArray checkBefore = SimpleValues.createSimpleStringArrayWithStrBefore(); final JsonArray checkAfter = SimpleValues.createSimpleStringArrayWithStrAfter(); // Add before. simpleOperation(result, in, checkBefore, "/0", SimpleValues.STR_VALUE); // Add after. simpleOperation(result, in, checkAfter, "/1", SimpleValues.STR_VALUE); } /** * Test RFC 6902 add operation for {@code String}s on simple JSON array. * Starting with an array of size 2. *

    *
  • Adding {@code String} at the end, in the middle and at the beginning of * this array. *
  • Adding {@code String} at the beginning, in the middle and at the end of * this array. *
* * @param result * Tests result record. */ private void testAddStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 2"); final JsonArray in = SimpleValues.createStringArray2(); final JsonArray check = SimpleValues.createSimpleStringArray5(); complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, new String[] { SimpleValues.STR_VALUE_5, SimpleValues.STR_VALUE_3, SimpleValues.STR_VALUE_1 }); complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, new String[] { SimpleValues.STR_VALUE_1, SimpleValues.STR_VALUE_3, SimpleValues.STR_VALUE_5 }); } /** * Test RFC 6902 add operation for {@code int} on empty JSON object. * * @param result * Tests result record. */ private void testAddIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectInt(); simpleOperation(result, in, check, SimpleValues.INT_PATH, SimpleValues.INT_VALUE); } /** * Test RFC 6902 add operation for {@code int} on empty JSON array. Only * allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testAddIntOnEmptyArray(final TestResult result) { LOGGER.info(" - for int on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithInt(); simpleOperation(result, in, check, "/0", SimpleValues.INT_VALUE); } /** * Test RFC 6902 add operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testAddIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject check = SimpleValues.createSimpleObjectWithInt(); simpleOperation(result, in, check, SimpleValues.INT_PATH, SimpleValues.INT_VALUE); } /** * Test RFC 6902 add operation for {@code int} on simple JSON array. Using * index {@code 0} to add {@code int} before already existing element and * index {@code 1} to add {@code int} after already existing element. * * @param result * Tests result record. */ private void testAddIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 1"); final JsonArray in = SimpleValues.createIntArray1(); final JsonArray checkBefore = SimpleValues.createSimpleIntArrayWithIntBefore(); final JsonArray checkAfter = SimpleValues.createSimpleIntArrayWithIntAfter(); // Add before. simpleOperation(result, in, checkBefore, "/0", SimpleValues.INT_VALUE); // Add after. simpleOperation(result, in, checkAfter, "/1", SimpleValues.INT_VALUE); } /** * Test RFC 6902 add operation for {@code int}s on simple JSON array. Starting * with an array of size 2. *
    *
  • Adding {@code int} at the end, in the middle and at the beginning of * this array. *
  • Adding {@code int} at the beginning, in the middle and at the end of * this array. *
* * @param result * Tests result record. */ private void testAddIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 2"); final JsonArray in = SimpleValues.createIntArray2(); final JsonArray check = SimpleValues.createSimpleIntArray5(); complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, new Integer[] { SimpleValues.INT_VALUE_5, SimpleValues.INT_VALUE_3, SimpleValues.INT_VALUE_1 }); complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, new Integer[] { SimpleValues.INT_VALUE_1, SimpleValues.INT_VALUE_3, SimpleValues.INT_VALUE_5 }); } /** * Test RFC 6902 add operation for {@code boolean} on empty JSON object. * * @param result * Tests result record. */ private void testAddBooleanOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectBool(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, SimpleValues.BOOL_VALUE); } /** * Test RFC 6902 add operation for {@code boolean} on empty JSON array. Only * allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testAddBooleanOnEmptyArray(final TestResult result) { LOGGER.info(" - for boolean on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithBool(); simpleOperation(result, in, check, "/0", SimpleValues.BOOL_VALUE); } /** * Test RFC 6902 add operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testAddBooleanOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject check = SimpleValues.createSimpleObjectWithBool(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, SimpleValues.BOOL_VALUE); } /** * Test RFC 6902 add operation for {@code boolean} on simple JSON array. Using * index {@code 0} to add {@code boolean} before already existing element and * index {@code 1} to add {@code boolean} after already existing element. * * @param result * Tests result record. */ private void testAddBooleanOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 1"); final JsonArray in = SimpleValues.createBoolArray1(); final JsonArray checkBefore = SimpleValues.createSimpleBoolArrayWithBoolBefore(); final JsonArray checkAfter = SimpleValues.createSimpleBoolArrayWithBoolAfter(); // Add before. simpleOperation(result, in, checkBefore, "/0", SimpleValues.BOOL_FALSE); // Add after. simpleOperation(result, in, checkAfter, "/1", SimpleValues.BOOL_FALSE); } /** * Test RFC 6902 add operation for {@code boolean}s on simple JSON array. * Starting with an array of size 2. *
    *
  • Adding {@code boolean} at the end, in the middle and at the beginning * of this array. *
  • Adding {@code boolean} at the beginning, in the middle and at the end * of this array. *
* * @param result * Tests result record. */ private void testAddBooleanOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 2"); final JsonArray in = SimpleValues.createBoolArray2(); final JsonArray check = SimpleValues.createSimpleBoolArray5(); complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, new Boolean[] { SimpleValues.BOOL_TRUE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE }); complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, new Boolean[] { SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_TRUE }); } /** * Test RFC 6902 add operation for {@code JsonObject} on empty JSON object. * * @param result * Tests result record. */ private void testAddObjectOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonObject on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, SimpleValues.OBJ_VALUE); } /** * Test RFC 6902 add operation for {@code JsonObject} on empty JSON array. * Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testAddObjectOnEmptyArray(final TestResult result) { LOGGER.info(" - for JsonObject on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithObject(); simpleOperation(result, in, check, "/0", SimpleValues.OBJ_VALUE); } /** * Test RFC 6902 add operation for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testAddObjectOnSimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject check = SimpleValues.createCompoundObjectWithObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, SimpleValues.OBJ_VALUE); } /** * Test RFC 6902 add operation for {@code JsonObject} on simple JSON array. * Using index {@code 0} to add {@code JsonObject} before already existing * element and index {@code 1} to add {@code JsonObject} after already * existing element. * * @param result * Tests result record. */ private void testAddObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 1"); final JsonArray in = SimpleValues.createObjectArray1(); final JsonArray checkBefore = SimpleValues.createSimpleObjectArrayWithObjectBefore(); final JsonArray checkAfter = SimpleValues.createSimpleObjectArrayWithObjectAfter(); // Add before. simpleOperation(result, in, checkBefore, "/0", SimpleValues.OBJ_VALUE); // Add after. simpleOperation(result, in, checkAfter, "/1", SimpleValues.OBJ_VALUE); } /** * Test RFC 6902 add operation for {@code JsonObject}s on simple JSON array. * Starting with an array of size 2. *
    *
  • Adding {@code JsonObject} at the end, in the middle and at the * beginning of this array. *
  • Adding {@code JsonObject} at the beginning, in the middle and at the * end of this array. *
* * @param result * Tests result record. */ private void testAddObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 2"); final JsonArray in = SimpleValues.createObjectArray2(); final JsonArray check = SimpleValues.createSimpleObjectArray5(); complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, new JsonObject[] { SimpleValues.OBJ_VALUE_5, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_1 }); complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, new JsonObject[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_5 }); } // Tests based on RFC 6902 definitions and examples. /** * Test that existing target object is replaced by specified array when ADD * operation is applied. * {@see RFC 6902: * 4.1. add}:
* When the operation is applied, the target location MUST reference one of: *
    *
  • A member to add to an existing object - whereupon the supplied value is * added to that object at the indicated location. If the member already * exists, it is replaced by the specified value.
  • *
  • ...
  • *
*/ private void testAddArrayToReplaceObject(final TestResult result) { LOGGER.info(" - for JsonArray to replace JsonObject"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject check = SimpleValues.createCompoundObjectWithObjectReplaced(); final JsonArray value = SimpleValues.createSimpleStringArray5(); simpleOperation(result, in, check, SimpleValues.DEF_OBJ_PATH, value); } /** * Test that whole document is replaced by specified array when ADD operation * is applied with root pointer. * {@see RFC 6902: * 4.1. add}:
* When the operation is applied, the target location MUST reference one of: *
    *
  • The root of the target document - whereupon the specified value becomes * the entire content of the target document.
  • *
  • ...
  • *
*/ private void testAddArrayToReplaceDocument(final TestResult result) { LOGGER.info(" - for JsonArray to replace whole document"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonArray check = SimpleValues.createSimpleStringArray5(); final JsonArray value = SimpleValues.createSimpleStringArray5(); // Instance being replaced is JsonObject, instance being added is JsonArray. // The only API method allowing // this is the one working with JsonStructure. New builder instance is used // for each of the cases. final JsonPatch patch1 = builderAdd(Json.createPatchBuilder(), "", value) .build(); final JsonValue out1 = patch1.apply((JsonStructure) in); if (!JsonAssert.assertEquals(check, out1)) { final String className = value.getClass().getSimpleName(); result.fail("ADD " + className + " to compound object", "ADD operation for " + className + " failed on compound value"); } } /** * Test ADD operation of an array of {@code String}s into existing array of * {@code String}s. This scenario is inspired by * {@see RFC 6902: * 4.1. add} operation example {@code { "op": "add", "path": "/a/b/c", * "value": [ "foo", "bar" ] }} and following explanation of this operation on * an array: *
    *
  • An element to add to an existing array - whereupon the supplied value * is added to the array at the indicated location. Any elements at or above * the specified index are shifted one position to the right. The specified * index MUST NOT be greater than the number of elements in the array. If the * "-" character is used to index the end of the array (see [RFC6901]), this * has the effect of appending the value to the array.
  • *
*/ private void testAddStringArrayToStringArray(final TestResult result) { LOGGER.info(" - for String array to be added to existing String array"); final JsonArray in = SimpleValues.createStringArray2(); final JsonArray check = SimpleValues.createStringArray2WithStringArrayInTheMiddle(); final JsonArray value = SimpleValues.createStringInnerArray2(); simpleOperation(result, in, check, "/1", value); } /** * Test ADD operation on non existing JsonObject. This scenario is described * in {@see RFC * 6902: 4.1. add} error handling samples. Test is trying to ADD value { * "address" : "In a galaxy far far away"} into object { "name" : "John Smith" * } using path "/child/address". Even "/child" path does not exist so this * operation must fail. * */ private void testAddStringToNonExistingObject(final TestResult result) { LOGGER.info(" - for String to be added to non existing JsonObject"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonValue value = Json.createValue(SimpleValues.STR_VALUE); final String path = SimpleValues.DEF_OBJ_PATH + SimpleValues.STR_PATH; final JsonPointer ptr = Json.createPointer(path); simpleOperationFail(result, in, path, value); } /** * Tested operation name {@code "MOVE"}. * * @return Operation name to be used in logs. */ @Override protected String operationName() { return OPERATION; } /** * Create and initialize patch builder to contain ADD operation to be applied. * * @param path * JSON path of value to be added. * @param value * JSON Value to be added. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder createOperationBuilder(final String path, final Object value) { return builderAdd(Json.createPatchBuilder(), path, value); } /** * Update patch builder to contain next ADD operation to be applied. * * @param builder * JSON patch builder to update. * @param path * JSON path of value to be added. * @param value * JSON Value to be added. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value) { return builderAdd(builder, path, value); } /** * Add {@code value} at {@code path} to provided JSON patch builder. * * @param builder * Target JSON patch builder. * @param path * JSON path of value to be added. * @param value * Value to be added at given JSON path. * @return JSON patch builder containing new {@code value} at {@code path} * added. */ @SuppressWarnings("UnnecessaryUnboxing") private static JsonPatchBuilder builderAdd(final JsonPatchBuilder builder, final String path, final Object value) { switch (JsonValueType.getType(value.getClass())) { case String: return builder.add(path, (String) value); case Integer: return builder.add(path, ((Integer) value).intValue()); case Boolean: return builder.add(path, ((Boolean) value).booleanValue()); case JsonValue: return builder.add(path, (JsonValue) value); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } } PatchOperationCopy.java000066400000000000000000000262551451447132700350650ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonPatchBuilder; import java.util.logging.Logger; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Implements * {@see RFC 6902: * 4.5. copy} tests. */ public class PatchOperationCopy extends CommonOperation { private static final Logger LOGGER = Logger.getLogger(PatchOperationCopy.class.getName()); /** Tested operation name. */ private final String OPERATION = "COPY"; /** * Creates an instance of RFC 6902 replace operation test. */ PatchOperationCopy() { super(); } /** * Test RFC 6902 COPY operation. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6902 copy operation"); LOGGER.info("Testing RFC 6902 copy operation:"); testCopyStringOnSimpleObject(result); testCopyStringOnSimpleArray(result); testCopyIntOnSimpleObject(result); testCopyIntOnSimpleArray(result); testCopyBoolOnSimpleObject(result); testCopyBoolOnSimpleArray(result); testCopyObjectOnSimpleObject(result); testCopyObjectOnSimpleArray(result); testCopyStringOnCompoundObject(result); testCopyOfNonExistingLocationInObject(result); testCopyOfNonExistingLocationInArray(result); return result; } /** * Test RFC 6902 COPY operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testCopyStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectCopyStr(); simpleOperation(result, in, check, SimpleValues.STR_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 COPY operation for {@code String} on simple JSON array. * * @param result * Tests result record. */ private void testCopyStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 2"); final JsonArray in = SimpleValues.createStringArray2(); simpleOperation(result, in, SimpleValues.createStringArray2Copy1to0(), "/1", "/0"); simpleOperation(result, in, SimpleValues.createStringArray2Copy0to2(), "/0", "/2"); simpleOperation(result, in, SimpleValues.createStringArray2Copy0to1(), "/0", "/1"); } /** * Test RFC 6902 COPY operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testCopyIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectCopyInt(); simpleOperation(result, in, check, SimpleValues.INT_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 COPY operation for {@code int} on simple JSON array. * * @param result * Tests result record. */ private void testCopyIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 2"); final JsonArray in = SimpleValues.createIntArray2(); simpleOperation(result, in, SimpleValues.createIntArray2Copy1to0(), "/1", "/0"); simpleOperation(result, in, SimpleValues.createIntArray2Copy0to2(), "/0", "/2"); simpleOperation(result, in, SimpleValues.createIntArray2Copy0to1(), "/0", "/1"); } /** * Test RFC 6902 COPY operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testCopyBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectCopyBool(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 COPY operation for {@code boolean} on simple JSON array. * * @param result * Tests result record. */ private void testCopyBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 2"); final JsonArray in = SimpleValues.createBoolArray2(); simpleOperation(result, in, SimpleValues.createBoolArray2Copy1to0(), "/1", "/0"); simpleOperation(result, in, SimpleValues.createBoolArray2Copy0to2(), "/0", "/2"); simpleOperation(result, in, SimpleValues.createBoolArray2Copy0to1(), "/0", "/1"); } /** * Test RFC 6902 COPY operation for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testCopyObjectOnSimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createSimpleObjectCopyObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 COPY operation for {@code JsonObject} on simple JSON array. * * @param result * Tests result record. */ private void testCopyObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 2"); final JsonArray in = SimpleValues.createObjectArray2(); simpleOperation(result, in, SimpleValues.createObjectArray2Copy1to0(), "/1", "/0"); simpleOperation(result, in, SimpleValues.createObjectArray2Copy0to2(), "/0", "/2"); simpleOperation(result, in, SimpleValues.createObjectArray2Copy0to1(), "/0", "/1"); } /** * Test RFC 6902 COPY operation for {@code String} on compound JSON object. * Copied value overwrites an existing value. * * @param result * Tests result record. */ private void testCopyStringOnCompoundObject(final TestResult result) { LOGGER.info(" - for String on compound JSON object"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject check = SimpleValues.createCompoundObjectCopyValue(); simpleOperation(result, in, check, SimpleValues.DEF_PATH, SimpleValues.DEF_OBJ_PATH + SimpleValues.DEF_PATH); } // Tests based on RFC 6902 definitions and examples. /** * Test RFC 6902 COPY operation for non existing location in object. * {@see RFC 6902: * 4.5. copy} defines:
* The "from" location MUST exist for the operation to be successful. */ private void testCopyOfNonExistingLocationInObject(final TestResult result) { LOGGER.info(" - for non existing location in JsonObject"); final JsonObject[] objsIn = new JsonObject[] { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObject(), SimpleValues.createCompoundObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; final Object[] values = new Object[] { SimpleValues.OBJ_PATH, SimpleValues.BOOL_PATH, SimpleValues.INT_PATH, SimpleValues.STR_PATH }; // Go trough all objects for (int i = 0; i < objsIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, objsIn[i], paths[j], values[i]); } } } /** * Test RFC 6902 COPY operation for non existing location in array. * {@see RFC 6902: * 4.5. copy} defines:
* The "from" location MUST exist for the operation to be successful. */ private void testCopyOfNonExistingLocationInArray(final TestResult result) { LOGGER.info(" - for non existing location in JsonArray"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray1(), SimpleValues.createIntArray2(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createObjectArray2() }; final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", SimpleValues.STR_PATH + "/0" }; final Object[] values = new Object[] { "/0", "/1", "/2", "/5", "/1" }; // Go trough all arrays for (int i = 0; i < arraysIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, arraysIn[i], paths[j], values[i]); } } } /** * Tested operation name {@code "COPY"}. * * @return Operation name to be used in logs. */ @Override protected String operationName() { return OPERATION; } /** * Create and initialize patch builder to contain COPY operation to be * applied. * * @param path * Source JSON path of COPY operation. * @param value * Target JSON path of COPY operation. Must be instance of * {@link String}. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder createOperationBuilder(final String path, final Object value) { if (value instanceof String) { // LOGGER.info(" COPY "+path+" -> "+(String)value); return Json.createPatchBuilder().copy((String) value, path); } else { throw new IllegalArgumentException( "Argument \"value\" is not an instance of String"); } } /** * Update patch builder to contain next COPY operation to be applied. * * @param builder * JSON patch builder to update. * @param path * Source JSON path of COPY operation. * @param value * Target JSON path of COPY operation. Must be instance of * {@link String}. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value) { if (value instanceof String) { // LOGGER.info(" COPY "+path+" -> "+(String)value); return builder.copy((String) value, path); } else { throw new IllegalArgumentException( "Argument \"value\" is not an instance of String"); } } } PatchOperationEnum.java000066400000000000000000000065451451447132700350570ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonPatch; import java.util.logging.Logger; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Test {@link JsonPatch.Operation} enumeration. */ public class PatchOperationEnum { private static final Logger LOGGER = Logger.getLogger(PatchOperationEnum.class.getName()); /** * Creates an instance of {@link JsonPatch.Operation} enumeration test. */ PatchOperationEnum() { super(); } /** * Test {@link JsonPatch.Operation} enumeration. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "JsonPatch.Operation enumeration test"); LOGGER.info("JsonPatch.Operation enumeration test"); testOperationName(result); testOperationValueOf(result); return result; } /** * Test {@link JsonPatch.Operation#fromOperationName(String)} and * {@link JsonPatch.Operation#operationName()} methods. * * @param result * Tests result record. */ private void testOperationName(final TestResult result) { LOGGER.info(" - fromOperationName(String) and operationName(String)"); for (final JsonPatch.Operation op : JsonPatch.Operation.values()) { final String opName = op.operationName(); final JsonPatch.Operation opOut = JsonPatch.Operation .fromOperationName(opName); final int opNameLen = opName.length(); boolean opNameLc = true; for (int i = 0; opNameLc && i < opNameLen; i++) { opNameLc = Character.isLowerCase(opName.charAt(i)); } if (!opNameLc) { result.fail("operationName(String)", "Returned value " + opName + " is not lower case String"); } if (op != opOut) { result.fail("fromOperationName(String) and operationName(String)", "Returned operation " + opOut.name() + " shall be " + op.name()); } } } /** * Test {@code JsonPatch.Operation#valueOf(String)} method. * * @param result * Tests result record. */ private void testOperationValueOf(final TestResult result) { LOGGER.info(" - valueOf(String)"); for (final JsonPatch.Operation op : JsonPatch.Operation.values()) { final String opName = op.name(); final JsonPatch.Operation opOut = JsonPatch.Operation.valueOf(opName); if (op != opOut) { result.fail("valueOf(String)", "Returned operation " + opOut.name() + " shall be " + op.name()); } } } } PatchOperationMove.java000066400000000000000000000430251451447132700350530ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonPatch; import jakarta.json.JsonPatchBuilder; import jakarta.json.JsonPointer; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Implements * {@see RFC 6902: * 4.4. move} tests. */ public class PatchOperationMove extends CommonOperation { private static final Logger LOGGER = Logger.getLogger(PatchOperationMove.class.getName()); /** Tested operation name. */ private final String OPERATION = "MOVE"; /** * Creates an instance of RFC 6902 replace operation test. */ PatchOperationMove() { super(); } /** * Test RFC 6902 MOVE operation. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6902 move operation"); LOGGER.info("Testing RFC 6902 move operation:"); testMoveStringOnSimpleObject(result); testMoveStringOnSimpleArray(result); testMoveStringOnSimpleArray2(result); testMoveIntOnSimpleObject(result); testMoveIntOnSimpleArray(result); testMoveIntOnSimpleArray2(result); testMoveBoolOnSimpleObject(result); testMoveBoolOnSimpleArray(result); testMoveBoolOnSimpleArray2(result); testMoveObjectOnSimpleObject(result); testMoveObjectOnSimpleArray(result); testMoveObjectOnSimpleArray2(result); testMoveStringOnCompoundObject(result); testMoveOfNonExistingLocationInObject(result); testMoveOfNonExistingLocationInArray(result); testMoveVsRemoveAddOnSelfContainedPath(result); return result; } /** * Test RFC 6902 MOVE operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testMoveStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectMoveStr(); simpleOperation(result, in, check, SimpleValues.STR_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 MOVE operation for {@code String} on simple JSON array. * * @param result * Tests result record. */ private void testMoveStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 2"); final JsonArray in = SimpleValues.createStringArray2(); final JsonArray check = SimpleValues.createStringArray2R(); simpleOperation(result, in, in, "/0", "/0"); simpleOperation(result, in, check, "/1", "/0"); simpleOperation(result, in, check, "/0", "/1"); simpleOperation(result, in, check, "/0", "/-"); } /** * Test RFC 6902 MOVE operation for {@code String} on simple JSON array. * * @param result * Tests result record. */ private void testMoveStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleStringArray5(); final JsonArray check = SimpleValues.createSimpleStringArray5R(); complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, new String[] { "/1", "/2", "/1", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, new String[] { "/-", "/2", "/3", "/0" }); } /** * Test RFC 6902 MOVE operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testMoveIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectMoveInt(); simpleOperation(result, in, check, SimpleValues.INT_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 MOVE operation for {@code int} on simple JSON array. * * @param result * Tests result record. */ private void testMoveIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 2"); final JsonArray in = SimpleValues.createIntArray2(); final JsonArray check = SimpleValues.createIntArray2R(); simpleOperation(result, in, in, "/0", "/0"); simpleOperation(result, in, check, "/1", "/0"); simpleOperation(result, in, check, "/0", "/1"); simpleOperation(result, in, check, "/0", "/-"); } /** * Test RFC 6902 MOVE operation for {@code int} on simple JSON array. * * @param result * Tests result record. */ private void testMoveIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleIntArray5(); final JsonArray check = SimpleValues.createSimpleIntArray5R(); complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, new String[] { "/1", "/2", "/1", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, new String[] { "/-", "/2", "/3", "/0" }); } /** * Test RFC 6902 MOVE operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testMoveBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectMoveBool(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 MOVE operation for {@code boolean} on simple JSON array. * * @param result * Tests result record. */ private void testMoveBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 2"); final JsonArray in = SimpleValues.createBoolArray2(); final JsonArray check = SimpleValues.createBoolArray2R(); simpleOperation(result, in, in, "/0", "/0"); simpleOperation(result, in, check, "/1", "/0"); simpleOperation(result, in, check, "/0", "/1"); simpleOperation(result, in, check, "/0", "/-"); } /** * Test RFC 6902 MOVE operation for {@code boolean} on simple JSON array. * * @param result * Tests result record. */ private void testMoveBoolOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleBoolArray5(); final JsonArray check = SimpleValues.createSimpleBoolArray5R(); complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, new String[] { "/1", "/2", "/1", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, new String[] { "/-", "/2", "/3", "/0" }); } /** * Test RFC 6902 MOVE operation for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testMoveObjectOnSimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createSimpleObjectMoveObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, SimpleValues.DEF_PATH); } /** * Test RFC 6902 MOVE operation for {@code JsonObject} on simple JSON array. * * @param result * Tests result record. */ private void testMoveObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 2"); final JsonArray in = SimpleValues.createObjectArray2(); final JsonArray check = SimpleValues.createObjectArray2R(); simpleOperation(result, in, in, "/0", "/0"); simpleOperation(result, in, check, "/1", "/0"); simpleOperation(result, in, check, "/0", "/1"); simpleOperation(result, in, check, "/0", "/-"); } /** * Test RFC 6902 MOVE operation for {@code JsonObject} on simple JSON array. * * @param result * Tests result record. */ private void testMoveObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleObjectArray5(); final JsonArray check = SimpleValues.createSimpleObjectArray5R(); complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, new String[] { "/1", "/2", "/1", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, new String[] { "/-", "/2", "/3", "/0" }); } /** * Test RFC 6902 MOVE operation for {@code String} on compound JSON object. * Moved value overwrites an existing value. * * @param result * Tests result record. */ private void testMoveStringOnCompoundObject(final TestResult result) { LOGGER.info(" - for String on compound JSON object"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject check = SimpleValues.createCompoundObjectMoveValue(); simpleOperation(result, in, check, SimpleValues.DEF_PATH, SimpleValues.DEF_OBJ_PATH + SimpleValues.DEF_PATH); } // Tests based on RFC 6902 definitions and examples. /** * Test RFC 6902 MOVE operation for non existing location in object. * {@see RFC 6902: * 4.4. move} defines:
* The "from" location MUST exist for the operation to be successful. */ private void testMoveOfNonExistingLocationInObject(final TestResult result) { LOGGER.info(" - for non existing location in JsonObject"); final JsonObject[] objsIn = new JsonObject[] { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObject(), SimpleValues.createCompoundObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; final Object[] values = new Object[] { SimpleValues.OBJ_PATH, SimpleValues.BOOL_PATH, SimpleValues.INT_PATH, SimpleValues.STR_PATH }; // Go trough all objects for (int i = 0; i < objsIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, objsIn[i], paths[j], values[i]); } } } /** * Test RFC 6902 MOVE operation for non existing location in array. * {@see RFC 6902: * 4.4. move} defines:
* The "from" location MUST exist for the operation to be successful. */ private void testMoveOfNonExistingLocationInArray(final TestResult result) { LOGGER.info(" - for non existing location in JsonArray"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray1(), SimpleValues.createIntArray2(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createObjectArray2() }; final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", SimpleValues.STR_PATH + "/0" }; final Object[] values = new Object[] { "/0", "/1", "/2", "/5", "/1" }; // Go trough all arrays for (int i = 0; i < arraysIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, arraysIn[i], paths[j], values[i]); } } } /** * Test RFC 6902 MOVE operation for moving existing path into path containing * source path as a prefix. * {@see RFC 6902: * 4.4. move} defines:
* This operation is functionally identical to a "remove" operation on the * "from" location, followed immediately by an "add" operation at the target * location with the value that was just removed. * {@see RFC 6901: 7. * Error Handling} defines:
* This specification does not define how errors are handled. An application * of JSON Pointer SHOULD specify the impact and handling of each type of * error.
* For example, some applications might stop pointer processing upon an error, * while others may attempt to recover from missing values by inserting * default ones.
* This means, that such an operation may fail on non existing target "path" * after ADD operation, but also missing pointer error recovery may take care * of creating missing "path" elements. In both cases MOVE and sequence of * REMOVE and ADD operations MUST produce the same result. */ private void testMoveVsRemoveAddOnSelfContainedPath(final TestResult result) { LOGGER.info(" - for moving JsonObject under itself"); final JsonObject in = SimpleValues.createCompoundObject(); final String targetPath = SimpleValues.DEF_OBJ_PATH + SimpleValues.DEF_PATH; final JsonPointer ptr = Json.createPointer(SimpleValues.DEF_OBJ_PATH); final JsonValue value = ptr.getValue(in); final JsonPatchBuilder moveBuilder = Json.createPatchBuilder() .move(targetPath, SimpleValues.DEF_OBJ_PATH); final JsonPatchBuilder remAddBuilder = Json.createPatchBuilder() .remove(SimpleValues.DEF_OBJ_PATH).add(targetPath, value); final JsonPatch movePatch = moveBuilder.build(); final JsonPatch remAddPatch = remAddBuilder.build(); // Check REMOVE and ADD sequence first. JsonObject remAddOut; try { remAddOut = remAddPatch.apply(in); LOGGER.info(" REMOVE and ADD passed"); } catch (JsonException e) { remAddOut = null; LOGGER.info(" REMOVE and ADD failed: " + e.getMessage()); } // Check MOVE second JsonObject moveOut; try { moveOut = movePatch.apply(in); LOGGER.info(" MOVE passed"); } catch (JsonException e) { moveOut = null; LOGGER.info(" MOVE failed: " + e.getMessage()); } // Results evaluation if (remAddOut != null) { // Both output values are not null: Compare them if (moveOut != null) { if (!JsonAssert.assertEquals(remAddOut, moveOut)) { result.fail("MOVE vs REMOVE and ADD", "Returned values are not equal"); } // REMOVE and ADD output is not null but MOVE output is null } else { result.fail("MOVE vs REMOVE and ADD", "REMOVE and ADD failed but MOVE dit not"); } } else { // REMOVE and ADD output is null but MOVE output is not null if (moveOut != null) { result.fail("MOVE vs REMOVE and ADD", "MOVE failed but REMOVE and ADD dit not"); } // else: Both output values are null: both patch operations failed -> test // passed } } /** * Tested operation name {@code "MOVE"}. * * @return Operation name to be used in logs. */ @Override protected String operationName() { return OPERATION; } /** * Create and initialize patch builder to contain MOVE operation to be * applied. * * @param path * Source JSON path of MOVE operation. * @param value * Target JSON path of MOVE operation. Must be instance of * {@link String}. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder createOperationBuilder(final String path, final Object value) { if (value instanceof String) { // LOGGER.info(" MOVE "+path+" -> "+(String)value); return Json.createPatchBuilder().move((String) value, path); } else { throw new IllegalArgumentException( "Argument \"value\" is not an instance of String"); } } /** * Update patch builder to contain next MOVE operation to be applied. * * @param builder * JSON patch builder to update. * @param path * Source JSON path of MOVE operation. * @param value * Target JSON path of MOVE operation. Must be instance of * {@link String}. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value) { if (value instanceof String) { // LOGGER.info(" MOVE "+path+" -> "+(String)value); return builder.move((String) value, path); } else { throw new IllegalArgumentException( "Argument \"value\" is not an instance of String"); } } } PatchOperationRemove.java000066400000000000000000000444441451447132700354100ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonPatchBuilder; import java.util.logging.Logger; // $Id$ /* * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Implements {@see RFC 6902: 4.2. remove} * tests. */ public class PatchOperationRemove extends CommonOperation { private static final Logger LOGGER = Logger.getLogger(PatchOperationRemove.class.getName()); /** Tested operation name. */ private final String OPERATION = "REMOVE"; /** * Creates an instance of RFC 6902 remove operation test. */ PatchOperationRemove() { super(); } /** * Test RFC 6902 remove operation. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6902 remove operation"); LOGGER.info("Testing RFC 6902 remove operation:"); testRemoveStringOnEmptyObject(result); testRemoveStringOnEmptyArray(result); testRemoveStringOnSimpleObject(result); testRemoveStringOnSimpleArray(result); testRemoveStringOnSimpleArray2(result); testRemoveIntOnEmptyObject(result); testRemoveIntOnEmptyArray(result); testRemoveIntOnSimpleObject(result); testRemoveIntOnSimpleArray(result); testRemoveIntOnSimpleArray2(result); testRemoveBoolOnEmptyObject(result); testRemoveBoolOnEmptyArray(result); testRemoveBoolOnSimpleObject(result); testRemoveBoolOnSimpleArray(result); testRemoveBoolOnSimpleArray2(result); testRemoveObjectOnEmptyObject(result); testRemoveObjectOnEmptyArray(result); testRemoveObjectOnSimpleObject(result); testRemoveObjectOnSimpleArray(result); testRemoveObjectOnSimpleArray2(result); testRemoveFromNonExistingLocationInObject(result); testRemoveFromNonExistingLocationInArray(result); return result; } /** * Test pointer remove operation for {@code String} to produce empty JSON * object. * * @param result * Tests result record. */ private void testRemoveStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createEmptyObject(); simpleOperation(result, in, check, SimpleValues.STR_PATH, null); } /** * Test pointer remove operation for {@code String} to produce empty JSON * array. Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveStringOnEmptyArray(final TestResult result) { LOGGER.info(" - for String to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithStr(); final JsonArray check = SimpleValues.createEmptyArray(); simpleOperation(result, in, check, "/0", null); } /** * Test pointer remove operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithStr(); final JsonObject check = SimpleValues.createSimpleObject(); simpleOperation(result, in, check, SimpleValues.STR_PATH, null); } /** * Test pointer remove operation for {@code String} on simple JSON array of * size 2. Using index {@code 0} to remove {@code String} before another * existing element and index {@code 1} to remove {@code String} after another * existing element. * * @param result * Tests result record. */ private void testRemoveStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleStringArrayWithStrBefore(); final JsonArray inAfter = SimpleValues.createSimpleStringArrayWithStrAfter(); final JsonArray check = SimpleValues.createStringArray1(); simpleOperation(result, inBefore, check, "/0", null); simpleOperation(result, inAfter, check, "/1", null); } /** * Test pointer REMOVE for {@code String} on simple JSON array of size 5. * Starting with an array of size 2. *

    *
  • Removing {@code String} at the end, at the middle and at the beginning * of this array. *
  • Removing {@code String} at the beginning, in the middle and at the end * of this array. *
* * @param result * Tests result record. */ private void testRemoveStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleStringArray5(); final JsonArray check = SimpleValues.createStringArray2(); complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); } /** * Test pointer REMOVE operation for {@code int} to produce empty JSON object. * * @param result * Tests result record. */ private void testRemoveIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createEmptyObject(); simpleOperation(result, in, check, SimpleValues.INT_PATH, null); } /** * Test pointer REMOVE operation for {@code int} to produce empty JSON array. * Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveIntOnEmptyArray(final TestResult result) { LOGGER.info(" - for int to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithInt(); final JsonArray check = SimpleValues.createEmptyArray(); simpleOperation(result, in, check, "/0", null); } /** * Test pointer REMOVE operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithInt(); final JsonObject check = SimpleValues.createSimpleObject(); simpleOperation(result, in, check, SimpleValues.INT_PATH, null); } /** * Test pointer REMOVE operation for {@code int} on simple JSON array of size * 2. Using index {@code 0} to remove {@code int} before another existing * element and index {@code 1} to remove {@code int} after another existing * element. * * @param result * Tests result record. */ private void testRemoveIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleIntArrayWithIntBefore(); final JsonArray inAfter = SimpleValues.createSimpleIntArrayWithIntAfter(); final JsonArray check = SimpleValues.createIntArray1(); simpleOperation(result, inBefore, check, "/0", null); simpleOperation(result, inAfter, check, "/1", null); } /** * Test pointer REMOVE for {@code int} on simple JSON array of size 5. * Starting with an array of size 5. *
    *
  • Removing {@code int} at the end, at the middle and at the beginning of * this array. *
  • Removing {@code int} at the beginning, in the middle and at the end of * this array. *
* * @param result * Tests result record. */ private void testRemoveIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleIntArray5(); final JsonArray check = SimpleValues.createIntArray2(); complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); } /** * Test pointer REMOVE operation for {@code boolean} to produce empty JSON * object. * * @param result * Tests result record. */ private void testRemoveBoolOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createEmptyObject(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, null); } /** * Test pointer REMOVE operation for {@code boolean} to produce empty JSON * array. Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveBoolOnEmptyArray(final TestResult result) { LOGGER.info(" - for boolean to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithBool(); final JsonArray check = SimpleValues.createEmptyArray(); simpleOperation(result, in, check, "/0", null); } /** * Test pointer REMOVE operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithBool(); final JsonObject check = SimpleValues.createSimpleObject(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, null); } /** * Test pointer REMOVE operation for {@code boolean} on simple JSON array of * size 2. Using index {@code 0} to remove {@code boolean} before another * existing element and index {@code 1} to remove {@code boolean} after * another existing element. * * @param result * Tests result record. */ private void testRemoveBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleBoolArrayWithBoolBefore(); final JsonArray inAfter = SimpleValues.createSimpleBoolArrayWithBoolAfter(); final JsonArray check = SimpleValues.createBoolArray1(); simpleOperation(result, inBefore, check, "/0", null); simpleOperation(result, inAfter, check, "/1", null); } /** * Test pointer REMOVE for {@code boolean} on simple JSON array of size 5. * Starting with an array of size 5. *
    *
  • Removing {@code boolean} at the end, at the middle and at the beginning * of this array. *
  • Removing {@code boolean} at the beginning, in the middle and at the end * of this array. *
* * @param result * Tests result record. */ private void testRemoveBoolOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleBoolArray5(); final JsonArray check = SimpleValues.createBoolArray2(); complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); } /** * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON * object. * * @param result * Tests result record. */ private void testRemoveObjectOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonObject to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createEmptyObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, null); } /** * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON * array. Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveObjectOnEmptyArray(final TestResult result) { LOGGER.info(" - for JsonObject to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithObject(); final JsonArray check = SimpleValues.createEmptyArray(); simpleOperation(result, in, check, "/0", null); } /** * Test pointer REMOVE operation for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveObjectOnSimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createCompoundObjectWithObject(); final JsonObject check = SimpleValues.createCompoundObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, null); } /** * Test pointer REMOVE operation for {@code JsonObject} on simple JSON array * of size 2. Using index {@code 0} to remove {@code JsonObject} before * another existing element and index {@code 1} to remove {@code JsonObject} * after another existing element. * * @param result * Tests result record. */ private void testRemoveObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleObjectArrayWithObjectBefore(); final JsonArray inAfter = SimpleValues.createSimpleObjectArrayWithObjectAfter(); final JsonArray check = SimpleValues.createObjectArray1(); simpleOperation(result, inBefore, check, "/0", null); simpleOperation(result, inAfter, check, "/1", null); } /** * Test pointer REMOVE for {@code JsonObject} on simple JSON array of size 5. * Starting with an array of size 5. *
    *
  • Removing {@code JsonObject} at the end, at the middle and at the * beginning of this array. *
  • Removing {@code JsonObject} at the beginning, in the middle and at the * end of this array. *
* * @param result * Tests result record. */ private void testRemoveObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleObjectArray5(); final JsonArray check = SimpleValues.createObjectArray2(); complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); } // Tests based on RFC 6902 definitions and examples. /** * Test pointer REMOVE for non existing location in object. * {@see RFC 6902: * 4.2. remove} defines:
* The target location MUST exist for the operation to be successful. */ private void testRemoveFromNonExistingLocationInObject( final TestResult result) { LOGGER.info(" - for non existing location in JsonObject"); final JsonObject[] objsIn = new JsonObject[] { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObject(), SimpleValues.createCompoundObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; // Go trough all objects for (int i = 0; i < objsIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, objsIn[i], paths[j], null); } } } /** * Test pointer REMOVE for non existing location in array. * {@see RFC 6902: * 4.2. remove} defines:
* The target location MUST exist for the operation to be successful. */ private void testRemoveFromNonExistingLocationInArray( final TestResult result) { LOGGER.info(" - for non existing location in JsonArray"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray1(), SimpleValues.createIntArray2(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createObjectArray2() }; final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", SimpleValues.STR_PATH + "/0" }; // Go trough all arrays for (int i = 0; i < arraysIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, arraysIn[i], paths[j], null); } } } /** * Tested operation name {@code "REMOVE"}. * * @return Operation name to be used in logs. */ @Override protected String operationName() { return OPERATION; } /** * Create and initialize patch builder to contain REMOVE operation to be * applied. * * @param path * JSON path of value to removed. * @param value * Not used for REMOVE operation. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder createOperationBuilder(final String path, final Object value) { return Json.createPatchBuilder().remove(path); } /** * Update patch builder to contain next REMOVE operation to be applied. * * @param builder * JSON patch builder to update. * @param path * JSON path of value to removed. * @param value * Not used for REMOVE operation. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value) { return builder.remove(path); } } PatchOperationReplace.java000066400000000000000000000366511451447132700355270ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonPatchBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Implements * {@see RFC 6902: * 4.3. replace} tests. */ public class PatchOperationReplace extends CommonOperation { private static final Logger LOGGER = Logger.getLogger(PatchOperationReplace.class.getName()); /** Tested operation name. */ private final String OPERATION = "REPLACE"; /** * Creates an instance of RFC 6902 replace operation test. */ PatchOperationReplace() { super(); } /** * Test RFC 6902 replace operation. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6902 replace operation"); LOGGER.info("Testing RFC 6902 replace operation:"); testReplaceStringOnSimpleObject(result); testReplaceStringOnSimpleArray(result); testReplaceStringOnSimpleArray2(result); testReplaceIntOnSimpleObject(result); testReplaceIntOnSimpleArray(result); testReplaceIntOnSimpleArray2(result); testReplaceBoolOnSimpleObject(result); testReplaceBoolOnSimpleArray(result); testReplaceBoolOnSimpleArray2(result); testReplaceObjectOnCompoundObject(result); testReplaceObjectOnSimpleArray(result); testReplaceObjectOnSimpleArray2(result); testReplaceOfNonExistingLocationInObject(result); testReplaceOfNonExistingLocationInArray(result); return result; } /** * Test pointer replace operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testReplaceStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectReplaceStr(); simpleOperation(result, in, check, SimpleValues.STR_PATH, SimpleValues.STR_VALUE2); } /** * Test pointer replace operation for {@code String} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 1"); final JsonArray in = SimpleValues.createStringArray1(); final JsonArray check = SimpleValues.createSimpleStringArrayReplaceStr(); simpleOperation(result, in, check, "/0", SimpleValues.STR_VALUE); } /** * Test pointer replace operation for {@code String} on simple JSON array of * size 5. Starting with an array of size 5. *

    *
  • Replacing {@code String} items from the end to the beginning of this * array. *
  • Replacing {@code String} from the beginning to the end of this array. *
* * @param result * Tests result record. */ private void testReplaceStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleStringArray5(); final JsonArray check = SimpleValues.createSimpleStringArray5R(); complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new String[] { SimpleValues.STR_VALUE_1, SimpleValues.STR_VALUE_2, SimpleValues.STR_VALUE_4, SimpleValues.STR_VALUE_5 }); complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new String[] { SimpleValues.STR_VALUE_5, SimpleValues.STR_VALUE_4, SimpleValues.STR_VALUE_2, SimpleValues.STR_VALUE_1 }); } /** * Test pointer replace operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testReplaceIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectReplaceInt(); simpleOperation(result, in, check, SimpleValues.INT_PATH, SimpleValues.INT_VALUE2); } /** * Test pointer replace operation for {@code int} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 1"); final JsonArray in = SimpleValues.createIntArray1(); final JsonArray check = SimpleValues.createSimpleIntArrayReplaceInt(); simpleOperation(result, in, check, "/0", SimpleValues.INT_VALUE); } /** * Test pointer replace operation for {@code int} on simple JSON array of size * 5. Starting with an array of size 5. *
    *
  • Replacing {@code int} items from the end to the beginning of this * array. *
  • Replacing {@code int} from the beginning to the end of this array. *
* * @param result * Tests result record. */ private void testReplaceIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleIntArray5(); final JsonArray check = SimpleValues.createSimpleIntArray5R(); complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new Integer[] { SimpleValues.INT_VALUE_1, SimpleValues.INT_VALUE_2, SimpleValues.INT_VALUE_4, SimpleValues.INT_VALUE_5 }); complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new Integer[] { SimpleValues.INT_VALUE_5, SimpleValues.INT_VALUE_4, SimpleValues.INT_VALUE_2, SimpleValues.INT_VALUE_1 }); } /** * Test pointer replace operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testReplaceBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectReplaceBool(); simpleOperation(result, in, check, SimpleValues.BOOL_PATH, SimpleValues.BOOL_VALUE2); } /** * Test pointer replace operation for {@code boolean} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 1"); final JsonArray in = SimpleValues.createBoolArray1(); final JsonArray check = SimpleValues.createSimpleBoolArrayReplaceBool(); simpleOperation(result, in, check, "/0", SimpleValues.BOOL_FALSE); } /** * Test pointer replace operation for {@code boolean} on simple JSON array of * size 5. Starting with an array of size 5. *
    *
  • Replacing {@code boolean} items from the end to the beginning of this * array. *
  • Replacing {@code boolean} from the beginning to the end of this array. *
* * @param result * Tests result record. */ private void testReplaceBoolOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleBoolArray5(); final JsonArray check = SimpleValues.createSimpleBoolArray5R(); complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new Boolean[] { SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE }); complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new Boolean[] { SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE }); } /** * Test pointer replace operation for {@code JsonObject} on compound JSON * object. * * @param result * Tests result record. */ private void testReplaceObjectOnCompoundObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createCompoundObjectWithObject(); final JsonObject check = SimpleValues.createCompoundObjectReplaceObject(); simpleOperation(result, in, check, SimpleValues.OBJ_PATH, SimpleValues.OBJ_VALUE2); } /** * Test pointer replace operation for {@code JsonObject} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 1"); final JsonArray in = SimpleValues.createObjectArray1(); final JsonArray check = SimpleValues.createSimpleObjectArrayReplaceObject(); simpleOperation(result, in, check, "/0", SimpleValues.OBJ_VALUE); } /** * Test pointer replace operation for {@code JsonObject} on simple JSON array * of size 5. Starting with an array of size 5. *
    *
  • Replacing {@code JsonObject} items from the end to the beginning of * this array. *
  • Replacing {@code JsonObject} from the beginning to the end of this * array. *
* * @param result * Tests result record. */ private void testReplaceObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleObjectArray5(); final JsonArray check = SimpleValues.createSimpleObjectArray5R(); complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new JsonObject[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_5 }); complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new JsonObject[] { SimpleValues.OBJ_VALUE_5, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_1 }); } // Tests based on RFC 6902 definitions and examples. /** * Test pointer replace for non existing location in object. * {@see RFC 6902: * 4.3. replace} defines:
* The target location MUST exist for the operation to be successful. */ private void testReplaceOfNonExistingLocationInObject( final TestResult result) { LOGGER.info(" - for non existing location in JsonObject"); final JsonObject[] objsIn = new JsonObject[] { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObject(), SimpleValues.createCompoundObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; final Object[] values = new Object[] { SimpleValues.STR_VALUE, SimpleValues.INT_VALUE, SimpleValues.BOOL_VALUE, SimpleValues.OBJ_VALUE }; // Go trough all objects for (int i = 0; i < objsIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, objsIn[i], paths[j], values[i]); } } } /** * Test pointer replace for non existing location in array. * {@see RFC 6902: * 4.3. replace} defines:
* The target location MUST exist for the operation to be successful. */ private void testReplaceOfNonExistingLocationInArray( final TestResult result) { LOGGER.info(" - for non existing location in JsonArray"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray1(), SimpleValues.createIntArray2(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createObjectArray2() }; final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", SimpleValues.STR_PATH + "/0" }; final Object[] values = new Object[] { SimpleValues.STR_VALUE, SimpleValues.STR_VALUE, SimpleValues.INT_VALUE, SimpleValues.BOOL_VALUE, SimpleValues.OBJ_VALUE }; // Go trough all arrays for (int i = 0; i < arraysIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { simpleOperationFail(result, arraysIn[i], paths[j], values[i]); } } } /** * Tested operation name {@code "MOVE"}. * * @return Operation name to be used in logs. */ @Override protected String operationName() { return OPERATION; } /** * Create and initialize patch builder to contain REPLACE operation to be * applied. * * @param path * JSON path of value to be replaced. * @param value * Value to replace previous one. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder createOperationBuilder(final String path, final Object value) { return builderReplace(Json.createPatchBuilder(), path, value); } /** * Update patch builder to contain next REPLACE operation to be applied. * * @param builder * JSON patch builder to update. * @param path * JSON path of value to be replaced. * @param value * Value to replace previous one. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value) { return builderReplace(builder, path, value); } /** * Add REPLACE {@code value} at {@code path} operation to provided JSON patch * builder. * * @param builder * Target JSON patch builder. * @param path * JSON path of value to be replaced. * @param value * Value to be replaced at given JSON path. * @return JSON patch builder containing new {@code value} at {@code path} * replaced. */ @SuppressWarnings("UnnecessaryUnboxing") private static JsonPatchBuilder builderReplace(final JsonPatchBuilder builder, final String path, final Object value) { switch (JsonValueType.getType(value.getClass())) { case String: return builder.replace(path, (String) value); case Integer: return builder.replace(path, ((Integer) value).intValue()); case Boolean: return builder.replace(path, ((Boolean) value).booleanValue()); case JsonValue: return builder.replace(path, (JsonValue) value); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } } PatchOperationTest.java000066400000000000000000000346241451447132700350710ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.JsonValueType; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.JsonPatchBuilder; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. *

* Implements * {@see RFC 6902: * 4.6. test} tests. */ public class PatchOperationTest extends CommonOperation { private static final Logger LOGGER = Logger.getLogger(PatchOperationTest.class.getName()); /** Tested operation name. */ private final String OPERATION = "TEST"; /** * Creates an instance of RFC 6902 replace operation test. */ PatchOperationTest() { super(); } /** * Test RFC 6902 MOVE operation. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6902 test operation"); LOGGER.info("Testing RFC 6902 test operation:"); testOnEmptyObject(result); testOnEmptyArray(result); testOnSimpleObject(result); testOnSimpleStringArray(result); testOnSimpleIntArray(result); testOnSimpleBoolArray(result); testOnSimpleObjectArray(result); return result; } /** * Test RFC 6902 TEST operation on empty JSON object. * * @param result * Tests result record. */ private void testOnEmptyObject(final TestResult result) { LOGGER.info(" - on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; final Object[] values = new Object[] { SimpleValues.STR_VALUE, SimpleValues.INT_VALUE, SimpleValues.BOOL_VALUE, SimpleValues.OBJ_VALUE }; // Go trough all values. for (int i = 0; i < values.length; i++) { // Go trough all paths. for (int j = 0; j < paths.length; j++) { // Everything shall fail on empty object. simpleOperationFail(result, in, paths[j], values[i]); } } // Whole document should pass on itself. simpleOperation(result, in, null, "", in); } /** * Test RFC 6902 TEST operation on empty JSON array. * * @param result * Tests result record. */ private void testOnEmptyArray(final TestResult result) { LOGGER.info(" - on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final String[] paths = new String[] { "/-1", "/0", "/1", "/2", "/3", "/4", "/5", "/-" }; final Object[] values = new Object[] { SimpleValues.STR_VALUE, SimpleValues.INT_VALUE, SimpleValues.BOOL_VALUE, SimpleValues.OBJ_VALUE }; // Go trough all values. for (int i = 0; i < values.length; i++) { // Go trough all paths. for (int j = 0; j < paths.length; j++) { // Everything shall fail on empty object. simpleOperationFail(result, in, paths[j], values[i]); } } // Whole document should pass on itself. simpleOperation(result, in, null, "", in); } /** * Test RFC 6902 TEST on simple JSON object. * * @param result * Tests result record. */ private void testOnSimpleObject(final TestResult result) { LOGGER.info(" - on simple JSON object"); final JsonObject[] in = new JsonObject[] { SimpleValues.createSimpleObjectStr(), SimpleValues.createSimpleObjectInt(), SimpleValues.createSimpleObjectBool(), SimpleValues.createSimpleObjectObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; final Object[] values = new Object[] { SimpleValues.STR_VALUE, SimpleValues.INT_VALUE, SimpleValues.BOOL_VALUE, SimpleValues.OBJ_VALUE }; // go trough all source objects. for (int o = 0; o < in.length; o++) { // Go trough all values. for (int i = 0; i < values.length; i++) { // Go trough all paths. for (int j = 0; j < paths.length; j++) { if (o == i && o == j) { // TEST must pass for matching JsonObject, path and value simpleOperation(result, in[o], null, paths[j], values[i]); } else { // TEST must fail for non matching JsonObject, path and value simpleOperationFail(result, in[o], paths[j], values[i]); } } } // Whole document should pass on itself. simpleOperation(result, in[o], null, "", in[o]); } } /** * Test RFC 6902 TEST on simple JSON array of {@code String}. * * @param result * Tests result record. */ private void testOnSimpleStringArray(final TestResult result) { LOGGER.info(" - on simple JSON String array of size 5"); final JsonArray in = SimpleValues.createSimpleStringArray5(); final String[] indexes = new String[] { "/-1", "/-", SimpleValues.STR_PATH }; final String[] values = new String[] { SimpleValues.STR_VALUE_1, SimpleValues.STR_VALUE_2, SimpleValues.STR_VALUE_3, SimpleValues.STR_VALUE_4, SimpleValues.STR_VALUE_5 }; // Go trough all array indexes. for (int i = 0; i <= 5; i++) { final String path = arrayPtr("/", i); // Go trough all values. for (int v = 0; v < values.length; v++) { if (i == v) { // TEST must pass for matching index and value. simpleOperation(result, in, null, path, values[v]); } else { // TEST must fail for non matching index and value. simpleOperationFail(result, in, path, values[v]); } } } // Go trough all invalid indexes for (int i = 0; i < indexes.length; i++) { // Go trough all values. for (int v = 0; v < values.length; v++) { // TEST must fail for non matching index and value. simpleOperationFail(result, in, indexes[i], values[v]); } } // Whole document should pass on itself. simpleOperation(result, in, null, "", in); } /** * Test RFC 6902 TEST on simple JSON array of {@code int}. * * @param result * Tests result record. */ private void testOnSimpleIntArray(final TestResult result) { LOGGER.info(" - on simple JSON int array of size 5"); final JsonArray in = SimpleValues.createSimpleIntArray5(); final String[] indexes = new String[] { "/-1", "/-", SimpleValues.INT_PATH }; final int[] values = new int[] { SimpleValues.INT_VALUE_1, SimpleValues.INT_VALUE_2, SimpleValues.INT_VALUE_3, SimpleValues.INT_VALUE_4, SimpleValues.INT_VALUE_5 }; // Go trough all array indexes. for (int i = 0; i <= 5; i++) { final String path = arrayPtr("/", i); // Go trough all values. for (int v = 0; v < values.length; v++) { if (i == v) { // TEST must pass for matching index and value. simpleOperation(result, in, null, path, values[v]); } else { // TEST must fail for non matching index and value. simpleOperationFail(result, in, path, values[v]); } } } // Go trough all invalid indexes for (int i = 0; i < indexes.length; i++) { // Go trough all values. for (int v = 0; v < values.length; v++) { // TEST must fail for non matching index and value. simpleOperationFail(result, in, indexes[i], values[v]); } } // Whole document should pass on itself. simpleOperation(result, in, null, "", in); } /** * Test RFC 6902 TEST on simple JSON array of {@code boolean}. * * @param result * Tests result record. */ private void testOnSimpleBoolArray(final TestResult result) { LOGGER.info(" - on simple JSON boolean array of size 2"); final JsonArray in = SimpleValues.createBoolArray2(); final String[] indexes = new String[] { "/-1", "/-", SimpleValues.BOOL_PATH }; final boolean[] values = new boolean[] { SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE }; // Go trough all array indexes. for (int i = 0; i <= 2; i++) { final String path = arrayPtr("/", i); // Go trough all values. for (int v = 0; v < values.length; v++) { if (i == v) { // TEST must pass for matching index and value. simpleOperation(result, in, null, path, values[v]); } else { // TEST must fail for non matching index and value. simpleOperationFail(result, in, path, values[v]); } } } // Go trough all invalid indexes for (int i = 0; i < indexes.length; i++) { // Go trough all values. for (int v = 0; v < values.length; v++) { // TEST must fail for non matching index and value. simpleOperationFail(result, in, indexes[i], values[v]); } } // Whole document should pass on itself. simpleOperation(result, in, null, "", in); } /** * Test RFC 6902 TEST on simple JSON array of {@code JsonObject}. * * @param result * Tests result record. */ private void testOnSimpleObjectArray(final TestResult result) { LOGGER.info(" - on simple JSON JsonObject array of size 5"); final JsonArray in = SimpleValues.createSimpleObjectArray5(); final String[] indexes = new String[] { "/-1", "/-", SimpleValues.OBJ_PATH }; final JsonObject[] values = new JsonObject[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_5 }; // Go trough all array indexes. for (int i = 0; i <= 5; i++) { final String path = arrayPtr("/", i); // Go trough all values. for (int v = 0; v < values.length; v++) { if (i == v) { // TEST must pass for matching index and value. simpleOperation(result, in, null, path, values[v]); } else { // TEST must fail for non matching index and value. simpleOperationFail(result, in, path, values[v]); } } } // Go trough all invalid indexes for (int i = 0; i < indexes.length; i++) { // Go trough all values. for (int v = 0; v < values.length; v++) { // TEST must fail for non matching index and value. simpleOperationFail(result, in, indexes[i], values[v]); } } // Whole document should pass on itself. simpleOperation(result, in, null, "", in); } /** * Build JSON array pointer for given prefix and index. * * @param prefix * JSON array pointer prefix. * @param index * JSON array pointer index. * @return JSON array pointer. */ private static String arrayPtr(final String prefix, final int index) { final int prefixLen = prefix != null ? prefix.length() : 0; final String indexStr = Integer.toString(index); final StringBuilder sb = new StringBuilder(prefixLen + indexStr.length()); if (prefixLen > 0) { sb.append(prefix); } sb.append(indexStr); return sb.toString(); } /** * Tested operation name {@code "TEST"}. * * @return Operation name to be used in logs. */ @Override protected String operationName() { return OPERATION; } /** * Create and initialize patch builder to contain TEST operation to be * applied. * * @param path * JSON path of value to be tested. * @param value * Value to be compared against value on specified path. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder createOperationBuilder(final String path, final Object value) { return builderTest(Json.createPatchBuilder(), path, value); } /** * Update patch builder to contain next TEST operation to be applied. * * @param builder * JSON patch builder to update. * @param path * JSON path of value to be tested. * @param value * Value to be compared against value on specified path. * @return Patch builder containing operation to be applied. */ @Override protected JsonPatchBuilder updateOperationBuilder( final JsonPatchBuilder builder, final String path, final Object value) { return builderTest(builder, path, value); } /** * Add TEST {@code value} at {@code path} operation to provided JSON patch * builder. * * @param builder * Target JSON patch builder. * @param path * JSON path of value to be tested. * @param value * Value to be compared against value on specified path. * @return JSON patch builder containing new TEST operation. */ @SuppressWarnings("UnnecessaryUnboxing") private static JsonPatchBuilder builderTest(final JsonPatchBuilder builder, final String path, final Object value) { switch (JsonValueType.getType(value.getClass())) { case String: return builder.test(path, (String) value); case Integer: return builder.test(path, ((Integer) value).intValue()); case Boolean: return builder.test(path, ((Boolean) value).booleanValue()); case JsonValue: return builder.test(path, (JsonValue) value); default: throw new IllegalArgumentException( "Value does not match known JSON value type"); } } /** * Operation result check. * * @param check * Expected modified JSON value. * @param out * Operation output. * @return Value of {@code true} if operation passed or {@code false} * otherwise. */ @Override protected boolean operationFailed(final JsonValue check, final JsonValue out) { return out == null; } } PatchTests.java000066400000000000000000000150041451447132700333620ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/patchtests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.patchtests; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.JsonPatch; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; // $Id$ /* * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
* {@see RFC 6902}. */ public class PatchTests { /** * Test {@link JsonPatch} factory methods added in JSON-P 1.1. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonCreatePatch11Test * * @assertion_ids: JSONP:JAVADOC:574; JSONP:JAVADOC:579; JSONP:JAVADOC:581; * JSONP:JAVADOC:653; JSONP:JAVADOC:658; JSONP:JAVADOC:660; * JSONP:JAVADOC:620; JSONP:JAVADOC:621; * * @test_Strategy: Tests JsonPatch API factory methods added in JSON-P 1.1. */ @Test public void jsonCreatePatch11Test() { PatchCreate createTest = new PatchCreate(); final TestResult result = createTest.test(); result.eval(); } /** * Test {@code JsonPatch.Operation} enumeration added in JSON-P 1.1. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonJsonPatchOperation11Test * * @assertion_ids: JSONP:JAVADOC:622; JSONP:JAVADOC:623; JSONP:JAVADOC:624; * JSONP:JAVADOC:625; * * @test_Strategy: Tests JsonPatch.Operation enumeration added in JSON-P 1.1. */ @Test public void jsonJsonPatchOperation11Test() { PatchOperationEnum enumTest = new PatchOperationEnum(); final TestResult result = enumTest.test(); result.eval(); } /** * Test JSONP API response on add operation.
* {@see RFC 6902: * 4.1. add}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPatchAddTest * @assertion_ids: JSONP:JAVADOC:626; JSONP:JAVADOC:627; JSONP:JAVADOC:628; * JSONP:JAVADOC:629; JSONP:JAVADOC:580; JSONP:JAVADOC:659; * JSONP:JAVADOC:620; JSONP:JAVADOC:630; * @test_Strategy: Test API response on various usages of add operation. */ @Test public void jsonPatchAddTest() { PatchOperationAdd addTest = new PatchOperationAdd(); final TestResult result = addTest.test(); result.eval(); } /** * Test JSONP API response on remove operation.
* {@see RFC 6902: * 4.2. remove}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPatchRemoveTest * @assertion_ids: JSONP:JAVADOC:633; JSONP:JAVADOC:580; JSONP:JAVADOC:659; * JSONP:JAVADOC:620; JSONP:JAVADOC:630; * @test_Strategy: Test API response on various usages of remove operation. */ @Test public void jsonPatchRemoveTest() { PatchOperationRemove removeTest = new PatchOperationRemove(); final TestResult result = removeTest.test(); result.eval(); } /** * Test JSONP API response on replace operation.
* {@see RFC 6902: * 4.3. replace}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPatchReplaceTest * @assertion_ids: JSONP:JAVADOC:634; JSONP:JAVADOC:635; JSONP:JAVADOC:636; * JSONP:JAVADOC:637; JSONP:JAVADOC:580; JSONP:JAVADOC:659; * JSONP:JAVADOC:620; JSONP:JAVADOC:630; * @test_Strategy: Test API response on various usages of replace operation. */ @Test public void jsonPatchReplaceTest() { PatchOperationReplace replaceTest = new PatchOperationReplace(); final TestResult result = replaceTest.test(); result.eval(); } /** * Test JSONP API response on move operation.
* {@see RFC 6902: * 4.4. move}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPatchMoveTest * @assertion_ids: JSONP:JAVADOC:632; JSONP:JAVADOC:580; JSONP:JAVADOC:659; * JSONP:JAVADOC:620; JSONP:JAVADOC:630; * @test_Strategy: Test API response on various usages of move operation. */ @Test public void jsonPatchMoveTest() { PatchOperationMove moveTest = new PatchOperationMove(); final TestResult result = moveTest.test(); result.eval(); } /** * Test JSONP API response on copy operation.
* {@see RFC 6902: * 4.5. copy}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPatchCopyTest * @assertion_ids: JSONP:JAVADOC:631; JSONP:JAVADOC:580; JSONP:JAVADOC:659; * JSONP:JAVADOC:620; JSONP:JAVADOC:630; * @test_Strategy: Test API response on various usages of copy operation. */ @Test public void jsonPatchCopyTest() { PatchOperationCopy copyTest = new PatchOperationCopy(); final TestResult result = copyTest.test(); result.eval(); } /** * Test JSONP API response on test operation.
* {@see RFC 6902: * 4.6. test}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPatchTestTest * @assertion_ids: JSONP:JAVADOC:638; JSONP:JAVADOC:639; JSONP:JAVADOC:640; * JSONP:JAVADOC:641; JSONP:JAVADOC:580; JSONP:JAVADOC:659; * JSONP:JAVADOC:620; JSONP:JAVADOC:630; * @test_Strategy: Test API response on various usages of test operation. */ @Test public void jsonPatchTestTest() { PatchOperationTest testTest = new PatchOperationTest(); final TestResult result = testTest.test(); result.eval(); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/pointertests/000077500000000000000000000000001451447132700310755ustar00rootroot00000000000000PointerAdd.java000066400000000000000000000740311451447132700337170ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/pointertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.pointertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonPointer; import jakarta.json.JsonStructure; import java.util.logging.Logger; // $Id$ /** * {@see RFC 6901}: pointer * usage for {@see RFC 6902} * add operation tests.
*/ public class PointerAdd { private static final Logger LOGGER = Logger.getLogger(PointerAdd.class.getName()); /** * Creates an instance of RFC 6901 pointer instance usage for RFC 6902 add * operation tests. */ PointerAdd() { super(); } /** * Test RFC 6901 pointer instance usage for RFC 6902 add operation. Suite * entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "RFC 6901 pointer usage for RFC 6902 add operation"); LOGGER.info("Testing RFC 6901 pointer usage for RFC 6902 add operation"); testAddStringOnEmptyObject(result); testAddStringOnEmptyArray(result); testAddStringOnSimpleObject(result); testAddStringOnSimpleArray(result); testAddStringOnSimpleArray2(result); testAddIntOnEmptyObject(result); testAddIntOnEmptyArray(result); testAddIntOnSimpleObject(result); testAddIntOnSimpleArray(result); testAddIntOnSimpleArray2(result); testAddBoolOnEmptyObject(result); testAddBoolOnEmptyArray(result); testAddBoolOnSimpleObject(result); testAddBoolOnSimpleArray(result); testAddBoolOnSimpleArray2(result); testAddObjectOnEmptyObject(result); testAddObjectOnEmptyArray(result); testAddObjectOnSimpleObject(result); testAddObjectOnSimpleArray(result); testAddObjectOnSimpleArray2(result); testAddArrayToReplaceObject(result); testAddArrayToReplaceDocument(result); testAddStringArrayToStringArray(result); testAddStringToNonExistingObject(result); return result; } /** * Test pointer ADD operation for {@code String} on empty JSON object. * * @param result * Tests result record. */ private void testAddStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectStr(); final JsonPointer ptr = Json.createPointer(SimpleValues.STR_PATH); final JsonObject out = ptr.add(in, Json.createValue(SimpleValues.STR_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.STR_PATH + "\" ADD \"" + SimpleValues.STR_VALUE + "\" failed on empty JSON object"); } } /** * Test pointer ADD operation for {@code String} on empty JSON array. Only * allowed index for empty array is {@code 0} and {@code -}. * * @param result * Tests result record. */ private void testAddStringOnEmptyArray(final TestResult result) { LOGGER.info(" - for String on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithStr(); final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), Json.createPointer("/-") }; for (final JsonPointer ptr : ptrs) { final JsonArray out = ptr.add(in, Json.createValue(SimpleValues.STR_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + SimpleValues.STR_VALUE + "\" failed on empty JSON array"); } } } /** * Test pointer ADD operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testAddStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject check = SimpleValues.createSimpleObjectWithStr(); final JsonPointer ptr = Json.createPointer(SimpleValues.STR_PATH); final JsonObject out = ptr.add(in, Json.createValue(SimpleValues.STR_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.STR_PATH + "\" ADD \"" + SimpleValues.STR_VALUE + "\" failed on simple JSON object"); } } /** * Test pointer ADD operation for {@code String} on simple JSON array of size * 1. Using index {@code 0} to add {@code String} before already existing * element and indexes {@code 1} and {@code -} to add {@code String} after * already existing element. * * @param result * Tests result record. */ private void testAddStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 1"); final JsonArray in = SimpleValues.createStringArray1(); final JsonArray checkBefore = SimpleValues.createSimpleStringArrayWithStrBefore(); final JsonArray checkAfter = SimpleValues.createSimpleStringArrayWithStrAfter(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer[] ptrsAfter = new JsonPointer[] { Json.createPointer("/1"), Json.createPointer("/-") }; final JsonArray outBefore = ptrBefore.add(in, Json.createValue(SimpleValues.STR_VALUE)); if (!JsonAssert.assertEquals(checkBefore, outBefore)) { result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + SimpleValues.STR_VALUE + "\" failed on simple JSON array"); } for (final JsonPointer ptrAfter : ptrsAfter) { final JsonArray outAfter = ptrAfter.add(in, Json.createValue(SimpleValues.STR_VALUE)); if (!JsonAssert.assertEquals(checkAfter, outAfter)) { result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + SimpleValues.STR_VALUE + "\" failed on simple JSON array"); } } } /** * Test pointer ADD operation for {@code String} on simple JSON array of size * 2. Starting with an array of size 2. *

    *
  • Adding {@code String} at the end, in the middle and at the beginning of * this array. *
  • Adding {@code String} at the beginning, in the middle and at the end of * this array. *
* * @param result * Tests result record. */ private void testAddStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 2"); final JsonArray in = SimpleValues.createStringArray2(); final JsonArray check = SimpleValues.createSimpleStringArray5(); verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, new String[] { SimpleValues.STR_VALUE_5, SimpleValues.STR_VALUE_3, SimpleValues.STR_VALUE_1 }, "Pointer ADD operation", "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, new String[] { SimpleValues.STR_VALUE_1, SimpleValues.STR_VALUE_3, SimpleValues.STR_VALUE_5 }, "Pointer ADD operation", "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); } /** * Test pointer ADD operation for {@code int} on empty JSON object. * * @param result * Tests result record. */ private void testAddIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectInt(); final JsonPointer ptr = Json.createPointer(SimpleValues.INT_PATH); final JsonObject out = ptr.add(in, Json.createValue(SimpleValues.INT_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.INT_PATH + "\" ADD \"" + SimpleValues.INT_VALUE + "\" failed on empty JSON object"); } } /** * Test pointer ADD operation for {@code int} on empty JSON array. Only * allowed index for empty array is {@code 0} and {@code -}. * * @param result * Tests result record. */ private void testAddIntOnEmptyArray(final TestResult result) { LOGGER.info(" - for int on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithInt(); final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), Json.createPointer("/-") }; for (final JsonPointer ptr : ptrs) { final JsonArray out = ptr.add(in, Json.createValue(SimpleValues.INT_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + SimpleValues.INT_VALUE + "\" failed on empty JSON array"); } } } /** * Test pointer ADD operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testAddIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject check = SimpleValues.createSimpleObjectWithInt(); final JsonPointer ptr = Json.createPointer(SimpleValues.INT_PATH); final JsonObject out = ptr.add(in, Json.createValue(SimpleValues.INT_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.INT_PATH + "\" ADD \"" + SimpleValues.INT_VALUE + "\" failed on simple JSON object"); } } /** * Test pointer ADD operation for {@code int} on simple JSON array of size 1. * Using index {@code 0} to add {@code int} before already existing element * and index {@code 1} and {@code -} to add {@code int} after already existing * element. * * @param result * Tests result record. */ private void testAddIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 1"); final JsonArray in = SimpleValues.createIntArray1(); final JsonArray checkBefore = SimpleValues.createSimpleIntArrayWithIntBefore(); final JsonArray checkAfter = SimpleValues.createSimpleIntArrayWithIntAfter(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer[] ptrsAfter = new JsonPointer[] { Json.createPointer("/1"), Json.createPointer("/-") }; final JsonArray outBefore = ptrBefore.add(in, Json.createValue(SimpleValues.INT_VALUE)); if (!JsonAssert.assertEquals(checkBefore, outBefore)) { result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + SimpleValues.INT_VALUE + "\" failed on simple JSON array"); } for (final JsonPointer ptrAfter : ptrsAfter) { final JsonArray outAfter = ptrAfter.add(in, Json.createValue(SimpleValues.INT_VALUE)); if (!JsonAssert.assertEquals(checkAfter, outAfter)) { result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + SimpleValues.INT_VALUE + "\" failed on simple JSON array"); } } } /** * Test pointer ADD operation for {@code int} on simple JSON array of size 2. * Starting with an array of size 2. *
    *
  • Adding {@code int} at the end, in the middle and at the beginning of * this array. *
  • Adding {@code int} at the beginning, in the middle and at the end of * this array. *
* * @param result * Tests result record. */ private void testAddIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 2"); final JsonArray in = SimpleValues.createIntArray2(); final JsonArray check = SimpleValues.createSimpleIntArray5(); verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, new Integer[] { SimpleValues.INT_VALUE_5, SimpleValues.INT_VALUE_3, SimpleValues.INT_VALUE_1 }, "Pointer ADD operation", "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, new Integer[] { SimpleValues.INT_VALUE_1, SimpleValues.INT_VALUE_3, SimpleValues.INT_VALUE_5 }, "Pointer ADD operation", "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); } /** * Test pointer ADD operation for {@code boolean} on empty JSON object. * * @param result * Tests result record. */ private void testAddBoolOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectBool(); final JsonPointer ptr = Json.createPointer(SimpleValues.BOOL_PATH); final JsonObject out = ptr.add(in, SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.BOOL_PATH + "\" ADD \"" + SimpleValues.BOOL_VALUE + "\" failed on empty JSON object"); } } /** * Test pointer ADD operation for {@code boolean} on empty JSON array. Only * allowed index for empty array is {@code 0} and {@code -}. * * @param result * Tests result record. */ private void testAddBoolOnEmptyArray(final TestResult result) { LOGGER.info(" - for boolean on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithBool(); final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), Json.createPointer("/-") }; for (final JsonPointer ptr : ptrs) { final JsonArray out = ptr.add(in, SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + SimpleValues.BOOL_VALUE + "\" failed on empty JSON array"); } } } /** * Test pointer ADD operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testAddBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonObject check = SimpleValues.createSimpleObjectWithBool(); final JsonPointer ptr = Json.createPointer(SimpleValues.BOOL_PATH); final JsonObject out = ptr.add(in, SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.BOOL_PATH + "\" ADD \"" + SimpleValues.BOOL_VALUE + "\" failed on simple JSON object"); } } /** * Test pointer ADD operation for {@code boolean} on simple JSON array of size * 1. Using index {@code 0} to add {@code boolean} before already existing * element and index {@code 1} and {@code -} to add {@code boolean} after * already existing element. * * @param result * Tests result record. */ private void testAddBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 1"); final JsonArray in = SimpleValues.createBoolArray1(); final JsonArray checkBefore = SimpleValues.createSimpleBoolArrayWithBoolBefore(); final JsonArray checkAfter = SimpleValues.createSimpleBoolArrayWithBoolAfter(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer[] ptrsAfter = new JsonPointer[] { Json.createPointer("/1"), Json.createPointer("/-") }; final JsonArray outBefore = ptrBefore.add(in, SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE)); if (!JsonAssert.assertEquals(checkBefore, outBefore)) { result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + SimpleValues.BOOL_FALSE + "\" failed on simple JSON array"); } for (final JsonPointer ptrAfter : ptrsAfter) { final JsonArray outAfter = ptrAfter.add(in, SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE)); if (!JsonAssert.assertEquals(checkAfter, outAfter)) { result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + SimpleValues.BOOL_FALSE + "\" failed on simple JSON array"); } } } /** * Test pointer ADD operation for {@code boolean} on simple JSON array of size * 2. Starting with an array of size 2. *
    *
  • Adding {@code boolean} at the end, in the middle and at the beginning * of this array. *
  • Adding {@code boolean} at the beginning, in the middle and at the end * of this array. *
* * @param result * Tests result record. */ private void testAddBoolOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 2"); final JsonArray in = SimpleValues.createBoolArray2(); final JsonArray check = SimpleValues.createSimpleBoolArray5(); verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, new Boolean[] { SimpleValues.BOOL_TRUE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE }, "Pointer ADD operation", "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, new Boolean[] { SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_TRUE }, "Pointer ADD operation", "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); } /** * Test pointer ADD operation for {@code JsonObject} on empty JSON object. * * @param result * Tests result record. */ private void testAddObjectOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonObject on empty JSON object"); final JsonObject in = SimpleValues.createEmptyObject(); final JsonObject check = SimpleValues.createSimpleObjectObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.OBJ_PATH); final JsonObject out = ptr.add(in, SimpleValues.OBJ_VALUE); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.OBJ_PATH + "\" ADD \"" + SimpleValues.OBJ_VALUE + "\" failed on empty JSON object"); } } /** * Test pointer ADD operation for {@code JsonObject} on empty JSON array. Only * allowed index for empty array is {@code 0} and {@code -}. * * @param result * Tests result record. */ private void testAddObjectOnEmptyArray(final TestResult result) { LOGGER.info(" - for JsonObject on empty JSON array"); final JsonArray in = SimpleValues.createEmptyArray(); final JsonArray check = SimpleValues.createEmptyArrayWithObject(); final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), Json.createPointer("/-") }; for (final JsonPointer ptr : ptrs) { final JsonArray out = ptr.add(in, SimpleValues.OBJ_VALUE); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + SimpleValues.OBJ_VALUE + "\" failed on empty JSON array"); } } } /** * Test pointer ADD operation for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testAddObjectOnSimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject check = SimpleValues.createCompoundObjectWithObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.OBJ_PATH); final JsonObject out = ptr.add(in, SimpleValues.OBJ_VALUE); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.OBJ_PATH + "\" ADD \"" + SimpleValues.OBJ_VALUE + "\" failed on simple JSON object"); } } /** * Test pointer ADD operation for {@code JsonObject} on simple JSON array of * size 1. Using index {@code 0} to add {@code JsonObject} before already * existing element and index {@code 1} and {@code -} to add * {@code JsonObject} after already existing element. * * @param result * Tests result record. */ private void testAddObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 1"); final JsonArray in = SimpleValues.createObjectArray1(); final JsonArray checkBefore = SimpleValues.createSimpleObjectArrayWithObjectBefore(); final JsonArray checkAfter = SimpleValues.createSimpleObjectArrayWithObjectAfter(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer[] ptrsAfter = new JsonPointer[] { Json.createPointer("/1"), Json.createPointer("/-") }; final JsonArray outBefore = ptrBefore.add(in, SimpleValues.OBJ_VALUE); if (!JsonAssert.assertEquals(checkBefore, outBefore)) { result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + SimpleValues.OBJ_VALUE + "\" failed on simple JSON array"); } for (final JsonPointer ptrAfter : ptrsAfter) { final JsonArray outAfter = ptrAfter.add(in, SimpleValues.OBJ_VALUE); if (!JsonAssert.assertEquals(checkAfter, outAfter)) { result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + SimpleValues.OBJ_VALUE + "\" failed on simple JSON array"); } } } /** * Test pointer ADD operation for {@code JsonObject} on simple JSON array of * size 2. Starting with an array of size 2. *
    *
  • Adding {@code JsonObject} at the end, in the middle and at the * beginning of this array. *
  • Adding {@code JsonObject} at the beginning, in the middle and at the * end of this array. *
* * @param result * Tests result record. */ private void testAddObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 2"); final JsonArray in = SimpleValues.createObjectArray2(); final JsonArray check = SimpleValues.createSimpleObjectArray5(); verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, new JsonObject[] { SimpleValues.OBJ_VALUE_5, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_1 }, "Pointer ADD operation", "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, new JsonObject[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_5 }, "Pointer ADD operation", "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); } // Tests based on RFC 6902 definitions and examples. /** * Test that existing target object is replaced by specified array when ADD * operation is applied. * {@see RFC 6902: * 4.1. add}:
* When the operation is applied, the target location MUST reference one of: *
    *
  • A member to add to an existing object - whereupon the supplied value is * added to that object at the indicated location. If the member already * exists, it is replaced by the specified value.
  • *
  • ...
  • *
*/ private void testAddArrayToReplaceObject(final TestResult result) { LOGGER.info(" - for JsonArray to replace JsonObject"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonObject check = SimpleValues.createCompoundObjectWithObjectReplaced(); final JsonPointer ptr = Json.createPointer(SimpleValues.DEF_OBJ_PATH); final JsonArray replace = SimpleValues.createSimpleStringArray5(); final JsonObject out = ptr.add(in, replace); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.DEF_OBJ_PATH + "\" ADD array to replace existing object failed on compound JSON object"); } } /** * Test that whole document is replaced by specified array when ADD operation * is applied with root pointer. * {@see RFC 6902: * 4.1. add}:
* When the operation is applied, the target location MUST reference one of: *
    *
  • The root of the target document - whereupon the specified value becomes * the entire content of the target document.
  • *
  • ...
  • *
*/ private void testAddArrayToReplaceDocument(final TestResult result) { LOGGER.info(" - for JsonArray to replace whole document"); final JsonObject in = SimpleValues.createCompoundObject(); final JsonArray check = SimpleValues.createSimpleStringArray5(); final JsonPointer ptr = Json.createPointer(""); final JsonArray replace = SimpleValues.createSimpleStringArray5(); // Instance being replaced is JsonObject, instance being added is JsonArray final JsonStructure out = ptr.add((JsonStructure) in, replace); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"" + SimpleValues.DEF_OBJ_PATH + "\" ADD array to replace existing object failed on compound JSON object"); } } /** * Test ADD operation of an array of {@code String}s into existing array of * {@code String}s. This scenario is inspired by * {@see RFC 6902: * 4.1. add} operation example {@code { "op": "add", "path": "/a/b/c", * "value": [ "foo", "bar" ] }} and following explanation of this operation on * an array: *
    *
  • An element to add to an existing array - whereupon the supplied value * is added to the array at the indicated location. Any elements at or above * the specified index are shifted one position to the right. The specified * index MUST NOT be greater than the number of elements in the array. If the * "-" character is used to index the end of the array (see [RFC6901]), this * has the effect of appending the value to the array.
  • *
*/ private void testAddStringArrayToStringArray(final TestResult result) { LOGGER.info(" - for String array to be added to existing String array"); final JsonArray in = SimpleValues.createStringArray2(); final JsonArray check = SimpleValues.createStringArray2WithStringArrayInTheMiddle(); final JsonArray arrayToAdd = SimpleValues.createStringInnerArray2(); final JsonPointer ptr = Json.createPointer("/1"); final JsonArray out = ptr.add(in, arrayToAdd); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer ADD operation", "Pointer \"/1\" ADD array failed on JSON array"); } } /** * Test ADD operation on non existing JsonObject. This scenario is described * in {@see RFC * 6902: 4.1. add} error handling samples. Test is trying to ADD value { * "address" : "In a galaxy far far away"} into object { "name" : "John Smith" * } using path "/child/address". Even "/child" path does not exist so this * operation must fail. * */ private void testAddStringToNonExistingObject(final TestResult result) { LOGGER.info(" - for String to be added to non existing JsonObject"); final JsonObject in = SimpleValues.createSimpleObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.DEF_OBJ_PATH + SimpleValues.STR_PATH); boolean exception = false; try { ptr.add(in, Json.createValue(SimpleValues.STR_VALUE)); } catch (JsonException e) { exception = true; LOGGER.info(" - Expected exception: " + e.getMessage()); } if (!exception) { result.fail("Pointer ADD operation", "ADD operation on non existing JsonObject \"" + SimpleValues.DEF_OBJ_PATH + "\" passed"); } } /** * Test helper: Verify set of ADD operations on provided JSON array and verify * result using provided expected JSON value. JSON pointer instance is used to * modify the array. * * @param result * Test suite result. * @param in * JSON array to be modified. * @param check * Expected modified JSON array (used for operation check). * @param paths * JSON array paths of values to be added. Pairs of {@code paths[i]} * and {@code values[i]} are used for add operations. * @param values * JSON array values to be added on specified indexes. * @param testName * Name of this test. * @param errorMessage * Error message to be added on verification failure. */ private void verifyAddValues(final TestResult result, final JsonArray in, final JsonArray check, final String[] paths, final Object[] values, final String testName, final String errorMessage) { if (paths.length != values.length) { throw new IllegalArgumentException( "Number of paths does not match number of indexes"); } JsonArray out = in; for (int i = 0; i < paths.length; i++) { final JsonPointer ptr = Json.createPointer(paths[i]); out = ptr.add(out, SimpleValues.toJsonValue(values[i])); } if (!JsonAssert.assertEquals(check, out)) { result.fail(testName, errorMessage); } } } PointerRemove.java000066400000000000000000000606661451447132700344750ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/pointertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.pointertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonPointer; import java.util.logging.Logger; // $Id$ /** * {@see RFC 6901}: pointer * usage for {@see RFC 6902} * remove operation tests.
*/ public class PointerRemove { private static final Logger LOGGER = Logger.getLogger(PointerRemove.class.getName()); /** * Creates an instance of RFC 6901 pointer instance usage for RFC 6902 remove * operation tests. */ PointerRemove() { super(); } /** * Test RFC 6901 pointer instance usage for RFC 6902 remove operation. Suite * entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "RFC 6901 pointer usage for RFC 6902 remove operation"); LOGGER.info("Testing RFC 6901 pointer usage for RFC 6902 remove operation"); testRemoveStringOnEmptyObject(result); testRemoveStringOnEmptyArray(result); testRemoveStringOnSimpleObject(result); testRemoveStringOnSimpleArray(result); testRemoveStringOnSimpleArray2(result); testRemoveIntOnEmptyObject(result); testRemoveIntOnEmptyArray(result); testRemoveIntOnSimpleObject(result); testRemoveIntOnSimpleArray(result); testRemoveIntOnSimpleArray2(result); testRemoveBoolOnEmptyObject(result); testRemoveBoolOnEmptyArray(result); testRemoveBoolOnSimpleObject(result); testRemoveBoolOnSimpleArray(result); testRemoveBoolOnSimpleArray2(result); testRemoveObjectOnEmptyObject(result); testRemoveObjectOnEmptyArray(result); testRemoveObjectOnSimpleObject(result); testRemoveObjectOnSimpleArray(result); testRemoveObjectOnSimpleArray2(result); testRemoveFromNonExistingLocationInObject(result); testRemoveFromNonExistingLocationInArray(result); return result; } /** * Test pointer REMOVE operation for {@code String} to produce empty JSON * object. * * @param result * Tests result record. */ private void testRemoveStringOnEmptyObject(final TestResult result) { LOGGER.info(" - for String to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createEmptyObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.STR_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.STR_PATH + "\" REMOVE failed when producing empty JSON object"); } } /** * Test pointer REMOVE operation for {@code String} to produce empty JSON * array. Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveStringOnEmptyArray(final TestResult result) { LOGGER.info(" - for String to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithStr(); final JsonArray check = SimpleValues.createEmptyArray(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed when producing empty JSON array"); } } /** * Test pointer REMOVE operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithStr(); final JsonObject check = SimpleValues.createSimpleObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.STR_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.STR_PATH + "\" REMOVE failed on simple JSON object"); } } /** * Test pointer REMOVE operation for {@code String} on simple JSON array of * size 2. Using index {@code 0} to remove {@code String} before another * existing element and index {@code 1} to remove {@code String} after another * existing element. * * @param result * Tests result record. */ private void testRemoveStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleStringArrayWithStrBefore(); final JsonArray inAfter = SimpleValues.createSimpleStringArrayWithStrAfter(); final JsonArray check = SimpleValues.createStringArray1(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer ptrAfter = Json.createPointer("/1"); final JsonArray outBefore = ptrBefore.remove(inBefore); final JsonArray outAfter = ptrAfter.remove(inAfter); if (!JsonAssert.assertEquals(check, outBefore)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed on simple JSON array"); } if (!JsonAssert.assertEquals(check, outAfter)) { result.fail("Pointer REMOVE operation", "Pointer \"/1\" REMOVE failed on simple JSON array"); } } /** * Test pointer REMOVE for {@code String} on simple JSON array of size 5. * Starting with an array of size 2. *
    *
  • Removing {@code String} at the end, at the middle and at the beginning * of this array. *
  • Removing {@code String} at the beginning, in the middle and at the end * of this array. *
* * @param result * Tests result record. */ private void testRemoveStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleStringArray5(); final JsonArray check = SimpleValues.createStringArray2(); verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, "Pointer REMOVE operation", "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, "Pointer REMOVE operation", "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); } /** * Test pointer REMOVE operation for {@code int} to produce empty JSON object. * * @param result * Tests result record. */ private void testRemoveIntOnEmptyObject(final TestResult result) { LOGGER.info(" - for int to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createEmptyObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.INT_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.INT_PATH + "\" REMOVE failed when producing empty JSON object"); } } /** * Test pointer REMOVE operation for {@code int} to produce empty JSON array. * Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveIntOnEmptyArray(final TestResult result) { LOGGER.info(" - for int to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithInt(); final JsonArray check = SimpleValues.createEmptyArray(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed when producing empty JSON array"); } } /** * Test pointer REMOVE operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithInt(); final JsonObject check = SimpleValues.createSimpleObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.INT_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.INT_PATH + "\" REMOVE failed on simple JSON object"); } } /** * Test pointer REMOVE operation for {@code int} on simple JSON array of size * 2. Using index {@code 0} to remove {@code int} before another existing * element and index {@code 1} to remove {@code int} after another existing * element. * * @param result * Tests result record. */ private void testRemoveIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleIntArrayWithIntBefore(); final JsonArray inAfter = SimpleValues.createSimpleIntArrayWithIntAfter(); final JsonArray check = SimpleValues.createIntArray1(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer ptrAfter = Json.createPointer("/1"); final JsonArray outBefore = ptrBefore.remove(inBefore); final JsonArray outAfter = ptrAfter.remove(inAfter); if (!JsonAssert.assertEquals(check, outBefore)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed on simple JSON array"); } if (!JsonAssert.assertEquals(check, outAfter)) { result.fail("Pointer REMOVE operation", "Pointer \"/1\" REMOVE failed on simple JSON array"); } } /** * Test pointer REMOVE for {@code int} on simple JSON array of size 5. * Starting with an array of size 5. *
    *
  • Removing {@code int} at the end, at the middle and at the beginning of * this array. *
  • Removing {@code int} at the beginning, in the middle and at the end of * this array. *
* * @param result * Tests result record. */ private void testRemoveIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleIntArray5(); final JsonArray check = SimpleValues.createIntArray2(); verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, "Pointer REMOVE operation", "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, "Pointer REMOVE operation", "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); } /** * Test pointer REMOVE operation for {@code boolean} to produce empty JSON * object. * * @param result * Tests result record. */ private void testRemoveBoolOnEmptyObject(final TestResult result) { LOGGER.info(" - for boolean to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createEmptyObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.BOOL_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.BOOL_PATH + "\" REMOVE failed when producing empty JSON object"); } } /** * Test pointer REMOVE operation for {@code boolean} to produce empty JSON * array. Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveBoolOnEmptyArray(final TestResult result) { LOGGER.info(" - for boolean to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithBool(); final JsonArray check = SimpleValues.createEmptyArray(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed when producing empty JSON array"); } } /** * Test pointer REMOVE operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectWithBool(); final JsonObject check = SimpleValues.createSimpleObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.BOOL_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.BOOL_PATH + "\" REMOVE failed on simple JSON object"); } } /** * Test pointer REMOVE operation for {@code boolean} on simple JSON array of * size 2. Using index {@code 0} to remove {@code boolean} before another * existing element and index {@code 1} to remove {@code boolean} after * another existing element. * * @param result * Tests result record. */ private void testRemoveBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleBoolArrayWithBoolBefore(); final JsonArray inAfter = SimpleValues.createSimpleBoolArrayWithBoolAfter(); final JsonArray check = SimpleValues.createBoolArray1(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer ptrAfter = Json.createPointer("/1"); final JsonArray outBefore = ptrBefore.remove(inBefore); final JsonArray outAfter = ptrAfter.remove(inAfter); if (!JsonAssert.assertEquals(check, outBefore)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed on simple JSON array"); } if (!JsonAssert.assertEquals(check, outAfter)) { result.fail("Pointer REMOVE operation", "Pointer \"/1\" REMOVE failed on simple JSON array"); } } /** * Test pointer REMOVE for {@code boolean} on simple JSON array of size 5. * Starting with an array of size 5. *
    *
  • Removing {@code boolean} at the end, at the middle and at the beginning * of this array. *
  • Removing {@code boolean} at the beginning, in the middle and at the end * of this array. *
* * @param result * Tests result record. */ private void testRemoveBoolOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleBoolArray5(); final JsonArray check = SimpleValues.createBoolArray2(); verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, "Pointer REMOVE operation", "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, "Pointer REMOVE operation", "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); } /** * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON * object. * * @param result * Tests result record. */ private void testRemoveObjectOnEmptyObject(final TestResult result) { LOGGER.info(" - for JsonObject to produce empty JSON object"); final JsonObject in = SimpleValues.createSimpleObjectObject(); final JsonObject check = SimpleValues.createEmptyObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.OBJ_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.OBJ_PATH + "\" REMOVE failed when producing empty JSON object"); } } /** * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON * array. Only allowed index for empty array is {@code 0}. * * @param result * Tests result record. */ private void testRemoveObjectOnEmptyArray(final TestResult result) { LOGGER.info(" - for JsonObject to produce empty JSON array"); final JsonArray in = SimpleValues.createEmptyArrayWithObject(); final JsonArray check = SimpleValues.createEmptyArray(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed when producing empty JSON array"); } } /** * Test pointer REMOVE operation for {@code JsonObject} on simple JSON object. * * @param result * Tests result record. */ private void testRemoveObjectOnSimpleObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createCompoundObjectWithObject(); final JsonObject check = SimpleValues.createCompoundObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.OBJ_PATH); final JsonObject out = ptr.remove(in); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REMOVE operation", "Pointer \"" + SimpleValues.OBJ_PATH + "\" REMOVE failed on simple JSON object"); } } /** * Test pointer REMOVE operation for {@code JsonObject} on simple JSON array * of size 2. Using index {@code 0} to remove {@code JsonObject} before * another existing element and index {@code 1} to remove {@code JsonObject} * after another existing element. * * @param result * Tests result record. */ private void testRemoveObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 2"); final JsonArray inBefore = SimpleValues.createSimpleObjectArrayWithObjectBefore(); final JsonArray inAfter = SimpleValues.createSimpleObjectArrayWithObjectAfter(); final JsonArray check = SimpleValues.createObjectArray1(); final JsonPointer ptrBefore = Json.createPointer("/0"); final JsonPointer ptrAfter = Json.createPointer("/1"); final JsonArray outBefore = ptrBefore.remove(inBefore); final JsonArray outAfter = ptrAfter.remove(inAfter); if (!JsonAssert.assertEquals(check, outBefore)) { result.fail("Pointer REMOVE operation", "Pointer \"/0\" REMOVE failed on simple JSON array"); } if (!JsonAssert.assertEquals(check, outAfter)) { result.fail("Pointer REMOVE operation", "Pointer \"/1\" REMOVE failed on simple JSON array"); } } /** * Test pointer REMOVE for {@code JsonObject} on simple JSON array of size 5. * Starting with an array of size 5. *
    *
  • Removing {@code JsonObject} at the end, at the middle and at the * beginning of this array. *
  • Removing {@code JsonObject} at the beginning, in the middle and at the * end of this array. *
* * @param result * Tests result record. */ private void testRemoveObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleObjectArray5(); final JsonArray check = SimpleValues.createObjectArray2(); verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, "Pointer REMOVE operation", "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, "Pointer REMOVE operation", "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); } // Tests based on RFC 6902 definitions and examples. /** * Test pointer REMOVE for non existing location in object. * {@see RFC 6902: * 4.2. remove} defines:
* The target location MUST exist for the operation to be successful. */ private void testRemoveFromNonExistingLocationInObject( final TestResult result) { LOGGER.info(" - for non existing location in JsonObject"); final JsonObject[] objsIn = new JsonObject[] { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObject(), SimpleValues.createCompoundObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; // Go trough all objects for (int i = 0; i < objsIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { final JsonPointer ptr = Json.createPointer(paths[j]); try { final JsonObject out = ptr.remove(objsIn[i]); result.fail("Pointer REMOVE operation", "Pointer \"" + paths[j] + "\" REMOVE succeeded on non existing location"); } catch (JsonException e) { // There are too many combinations to log them. } } } } /** * Test pointer REMOVE for non existing location in array. * {@see RFC 6902: * 4.2. remove} defines:
* The target location MUST exist for the operation to be successful. */ private void testRemoveFromNonExistingLocationInArray( final TestResult result) { LOGGER.info(" - for non existing location in JsonArray"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray1(), SimpleValues.createIntArray2(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createObjectArray2() }; final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", SimpleValues.STR_PATH + "/0" }; // Go trough all arrays for (int i = 0; i < arraysIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { final JsonPointer ptr = Json.createPointer(paths[j]); try { final JsonArray out = ptr.remove(arraysIn[i]); result.fail("Pointer REMOVE operation", "Pointer \"" + paths[j] + "\" REMOVE succeeded on non existing location"); } catch (JsonException e) { // There are too many combinations to log them. } } } } /** * Test helper: Verify set of REMOVE operations on provided JSON array and * verify result using provided expected JSON value. JSON pointer instance is * used to modify the array. * * @param result * Test suite result. * @param in * JSON array to be modified. * @param check * Expected modified JSON array (used for operation check). * @param paths * JSON array paths of values to be added. Pairs of {@code paths[i]} * and {@code values[i]} are used for add operations. * @param testName * Name of this test. * @param errorMessage * Error message to be added on verification failure. */ private void verifyRemoveValues(final TestResult result, final JsonArray in, final JsonArray check, final String[] paths, final String testName, final String errorMessage) { JsonArray out = in; for (int i = 0; i < paths.length; i++) { final JsonPointer ptr = Json.createPointer(paths[i]); out = ptr.remove(out); } if (!JsonAssert.assertEquals(check, out)) { result.fail(testName, errorMessage); } } } PointerReplace.java000066400000000000000000000452671451447132700346130ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/pointertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.pointertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonPointer; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * {@see RFC 6901}: pointer * usage for {@see RFC 6902} * replace operation tests.
*/ public class PointerReplace { private static final Logger LOGGER = Logger.getLogger(PointerReplace.class.getName()); /** * Creates an instance of RFC 6901 pointer instance usage for RFC 6902 replace * operation tests. */ PointerReplace() { super(); } /** * Test RFC 6901 pointer instance usage for RFC 6902 replace operation. Suite * entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult( "RFC 6901 pointer usage for RFC 6902 replace operation"); LOGGER.info( "Testing RFC 6901 pointer usage for RFC 6902 replace operation"); testReplaceStringOnSimpleObject(result); testReplaceStringOnSimpleArray(result); testReplaceStringOnSimpleArray2(result); testReplaceIntOnSimpleObject(result); testReplaceIntOnSimpleArray(result); testReplaceIntOnSimpleArray2(result); testReplaceBoolOnSimpleObject(result); testReplaceBoolOnSimpleArray(result); testReplaceBoolOnSimpleArray2(result); testReplaceObjectOnCompoundObject(result); testReplaceObjectOnSimpleArray(result); testReplaceObjectOnSimpleArray2(result); testReplaceOfNonExistingLocationInObject(result); testReplaceOfNonExistingLocationInArray(result); return result; } /** * Test pointer REPLACE operation for {@code String} on simple JSON object. * * @param result * Tests result record. */ private void testReplaceStringOnSimpleObject(final TestResult result) { LOGGER.info(" - for String on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectStr(); final JsonObject check = SimpleValues.createSimpleObjectReplaceStr(); final JsonPointer ptr = Json.createPointer(SimpleValues.STR_PATH); final JsonObject out = ptr.replace(in, Json.createValue(SimpleValues.STR_VALUE2)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"" + SimpleValues.STR_PATH + "\" REPLACE \"" + SimpleValues.STR_VALUE2 + "\" failed on simple JSON object"); } } /** * Test pointer REPLACE operation for {@code String} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceStringOnSimpleArray(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 1"); final JsonArray in = SimpleValues.createStringArray1(); final JsonArray check = SimpleValues.createSimpleStringArrayReplaceStr(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.replace(in, Json.createValue(SimpleValues.STR_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + SimpleValues.STR_VALUE + "\" failed on simple JSON array"); } } /** * Test pointer REPLACE operation for {@code String} on simple JSON array of * size 5. Starting with an array of size 5. *
    *
  • Replacing {@code String} items from the end to the beginning of this * array. *
  • Replacing {@code String} from the beginning to the end of this array. *
* * @param result * Tests result record. */ private void testReplaceStringOnSimpleArray2(final TestResult result) { LOGGER.info(" - for String on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleStringArray5(); final JsonArray check = SimpleValues.createSimpleStringArray5R(); verifyReplaceValues(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new String[] { SimpleValues.STR_VALUE_1, SimpleValues.STR_VALUE_2, SimpleValues.STR_VALUE_4, SimpleValues.STR_VALUE_5 }, "Pointer REPLACE operation", "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); verifyReplaceValues(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new String[] { SimpleValues.STR_VALUE_5, SimpleValues.STR_VALUE_4, SimpleValues.STR_VALUE_2, SimpleValues.STR_VALUE_1 }, "Pointer REPLACE operation", "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); } /** * Test pointer REPLACE operation for {@code int} on simple JSON object. * * @param result * Tests result record. */ private void testReplaceIntOnSimpleObject(final TestResult result) { LOGGER.info(" - for int on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectInt(); final JsonObject check = SimpleValues.createSimpleObjectReplaceInt(); final JsonPointer ptr = Json.createPointer(SimpleValues.INT_PATH); final JsonObject out = ptr.replace(in, Json.createValue(SimpleValues.INT_VALUE2)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"" + SimpleValues.INT_PATH + "\" REPLACE \"" + SimpleValues.INT_VALUE2 + "\" failed on simple JSON object"); } } /** * Test pointer REPLACE operation for {@code int} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceIntOnSimpleArray(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 1"); final JsonArray in = SimpleValues.createIntArray1(); final JsonArray check = SimpleValues.createSimpleIntArrayReplaceInt(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.replace(in, Json.createValue(SimpleValues.INT_VALUE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + SimpleValues.INT_VALUE + "\" failed on simple JSON array"); } } /** * Test pointer REPLACE operation for {@code int} on simple JSON array of size * 5. Starting with an array of size 5. *
    *
  • Replacing {@code int} items from the end to the beginning of this * array. *
  • Replacing {@code int} from the beginning to the end of this array. *
* * @param result * Tests result record. */ private void testReplaceIntOnSimpleArray2(final TestResult result) { LOGGER.info(" - for int on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleIntArray5(); final JsonArray check = SimpleValues.createSimpleIntArray5R(); verifyReplaceValues(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new Integer[] { SimpleValues.INT_VALUE_1, SimpleValues.INT_VALUE_2, SimpleValues.INT_VALUE_4, SimpleValues.INT_VALUE_5 }, "Pointer REPLACE operation", "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); verifyReplaceValues(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new Integer[] { SimpleValues.INT_VALUE_5, SimpleValues.INT_VALUE_4, SimpleValues.INT_VALUE_2, SimpleValues.INT_VALUE_1 }, "Pointer REPLACE operation", "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); } /** * Test pointer REPLACE operation for {@code boolean} on simple JSON object. * * @param result * Tests result record. */ private void testReplaceBoolOnSimpleObject(final TestResult result) { LOGGER.info(" - for boolean on simple JSON object"); final JsonObject in = SimpleValues.createSimpleObjectBool(); final JsonObject check = SimpleValues.createSimpleObjectReplaceBool(); final JsonPointer ptr = Json.createPointer(SimpleValues.BOOL_PATH); final JsonObject out = ptr.replace(in, SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE2)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"" + SimpleValues.BOOL_PATH + "\" REPLACE \"" + SimpleValues.BOOL_VALUE2 + "\" failed on simple JSON object"); } } /** * Test pointer REPLACE operation for {@code boolean} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceBoolOnSimpleArray(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 1"); final JsonArray in = SimpleValues.createBoolArray1(); final JsonArray check = SimpleValues.createSimpleBoolArrayReplaceBool(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.replace(in, SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE)); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + SimpleValues.BOOL_FALSE + "\" failed on simple JSON array"); } } /** * Test pointer REPLACE operation for {@code boolean} on simple JSON array of * size 5. Starting with an array of size 5. *
    *
  • Replacing {@code boolean} items from the end to the beginning of this * array. *
  • Replacing {@code boolean} from the beginning to the end of this array. *
* * @param result * Tests result record. */ private void testReplaceBoolOnSimpleArray2(final TestResult result) { LOGGER.info(" - for boolean on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleBoolArray5(); final JsonArray check = SimpleValues.createSimpleBoolArray5R(); verifyReplaceValues(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new Boolean[] { SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE }, "Pointer REPLACE operation", "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); verifyReplaceValues(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new Boolean[] { SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE, SimpleValues.BOOL_TRUE, SimpleValues.BOOL_FALSE }, "Pointer REPLACE operation", "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); } /** * Test pointer REPLACE operation for {@code JsonObject} on compound JSON * object. * * @param result * Tests result record. */ private void testReplaceObjectOnCompoundObject(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON object"); final JsonObject in = SimpleValues.createCompoundObjectWithObject(); final JsonObject check = SimpleValues.createCompoundObjectReplaceObject(); final JsonPointer ptr = Json.createPointer(SimpleValues.OBJ_PATH); final JsonObject out = ptr.replace(in, SimpleValues.OBJ_VALUE2); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"" + SimpleValues.OBJ_PATH + "\" REPLACE \"" + SimpleValues.OBJ_VALUE2 + "\" failed on simple JSON object"); } } /** * Test pointer REPLACE operation for {@code JsonObject} on simple JSON array. * * @param result * Tests result record. */ private void testReplaceObjectOnSimpleArray(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 1"); final JsonArray in = SimpleValues.createObjectArray1(); final JsonArray check = SimpleValues.createSimpleObjectArrayReplaceObject(); final JsonPointer ptr = Json.createPointer("/0"); final JsonArray out = ptr.replace(in, SimpleValues.OBJ_VALUE); if (!JsonAssert.assertEquals(check, out)) { result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + SimpleValues.OBJ_VALUE + "\" failed on simple JSON array"); } } /** * Test pointer REPLACE operation for {@code JsonObject} on simple JSON array * of size 5. Starting with an array of size 5. *
    *
  • Replacing {@code JsonObject} items from the end to the beginning of * this array. *
  • Replacing {@code JsonObject} from the beginning to the end of this * array. *
* * @param result * Tests result record. */ private void testReplaceObjectOnSimpleArray2(final TestResult result) { LOGGER.info(" - for JsonObject on simple JSON array of size 5"); final JsonArray in = SimpleValues.createSimpleObjectArray5(); final JsonArray check = SimpleValues.createSimpleObjectArray5R(); verifyReplaceValues(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, new JsonObject[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_5 }, "Pointer REPLACE operation", "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); verifyReplaceValues(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, new JsonObject[] { SimpleValues.OBJ_VALUE_5, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_1 }, "Pointer REPLACE operation", "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); } // Tests based on RFC 6902 definitions and examples. /** * Test pointer REPLACE for non existing location in object. * {@see RFC 6902: * 4.3. replace} defines:
* The target location MUST exist for the operation to be successful. */ private void testReplaceOfNonExistingLocationInObject( final TestResult result) { LOGGER.info(" - for non existing location in JsonObject"); final JsonObject[] objsIn = new JsonObject[] { SimpleValues.createEmptyObject(), SimpleValues.createSimpleObject(), SimpleValues.createCompoundObject() }; final String[] paths = new String[] { SimpleValues.STR_PATH, SimpleValues.INT_PATH, SimpleValues.BOOL_PATH, SimpleValues.OBJ_PATH }; final JsonValue[] values = new JsonValue[] { Json.createValue(SimpleValues.STR_VALUE), Json.createValue(SimpleValues.INT_VALUE), SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), SimpleValues.OBJ_VALUE }; // Go trough all objects for (int i = 0; i < objsIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { final JsonPointer ptr = Json.createPointer(paths[j]); try { final JsonObject out = ptr.replace(objsIn[i], values[i]); result.fail("Pointer REPLACE operation", "Pointer \"" + paths[j] + "\" REPLACE succeeded on non existing location"); } catch (JsonException e) { // There are too many combinations to log them. } } } } /** * Test pointer REPLACE for non existing location in array. * {@see RFC 6902: * 4.2. remove} defines:
* The target location MUST exist for the operation to be successful. */ private void testReplaceOfNonExistingLocationInArray( final TestResult result) { LOGGER.info(" - for non existing location in JsonArray"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray1(), SimpleValues.createIntArray2(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createObjectArray2() }; final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", SimpleValues.STR_PATH + "/0" }; final JsonValue[] values = new JsonValue[] { Json.createValue(SimpleValues.STR_VALUE), Json.createValue(SimpleValues.STR_VALUE), Json.createValue(SimpleValues.INT_VALUE), SimpleValues.toJsonValue(SimpleValues.BOOL_VALUE), SimpleValues.OBJ_VALUE }; // Go trough all arrays for (int i = 0; i < arraysIn.length; i++) { // Go trough all paths for (int j = 0; j < paths.length; j++) { final JsonPointer ptr = Json.createPointer(paths[j]); try { final JsonArray out = ptr.replace(arraysIn[i], values[i]); result.fail("Pointer REPLACE operation", "Pointer \"" + paths[j] + "\" REPLACE succeeded on non existing location"); } catch (JsonException e) { // There are too many combinations to log them. } } } } /** * Test helper: Verify set of REPLACE operations on provided JSON array and * verify result using provided expected JSON value. JSON pointer instance is * used to modify the array. * * @param result * Test suite result. * @param in * JSON array to be modified. * @param check * Expected modified JSON array (used for operation check). * @param paths * JSON array paths of values to be added. Pairs of {@code paths[i]} * and {@code values[i]} are used for add operations. * @param values * JSON array values to be added on specified indexes. * @param testName * Name of this test. * @param errorMessage * Error message to be added on verification failure. */ private void verifyReplaceValues(final TestResult result, final JsonArray in, final JsonArray check, final String[] paths, final Object[] values, final String testName, final String errorMessage) { if (paths.length != values.length) { throw new IllegalArgumentException( "Number of paths does not match number of indexes"); } JsonArray out = in; for (int i = 0; i < paths.length; i++) { final JsonPointer ptr = Json.createPointer(paths[i]); out = ptr.replace(out, SimpleValues.toJsonValue(values[i])); } if (!JsonAssert.assertEquals(check, out)) { result.fail(testName, errorMessage); } } } PointerResolve.java000066400000000000000000000647671451447132700346650ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/pointertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.pointertests; import ee.jakarta.tck.jsonp.api.common.JsonAssert; import ee.jakarta.tck.jsonp.api.common.PointerRFCObject; import ee.jakarta.tck.jsonp.api.common.SimpleValues; import ee.jakarta.tck.jsonp.api.common.TestResult; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonException; import jakarta.json.JsonObject; import jakarta.json.JsonPointer; import jakarta.json.JsonValue; import java.util.logging.Logger; // $Id$ /** * {@see RFC 6901}: JavaScript * Object Notation (JSON) Pointer resolving tests.
*/ public class PointerResolve { private static final Logger LOGGER = Logger.getLogger(PointerResolve.class.getName()); /** * Creates an instance of RFC 6901 JSON Pointer resolver tests. */ PointerResolve() { super(); } /** * Test RFC 6901 JSON Pointer resolver tests. Suite entry point. * * @return Result of all tests in this suite. */ TestResult test() { final TestResult result = new TestResult("RFC 6901 pointer resolving"); LOGGER.info("Testing RFC 6901 pointer resolving"); testResolveWholeDocument(result); testResolveEmptyName(result); testResolveSimpleArray(result); testResolveSimpleArrayItems(result); testResolvePathWithSlash(result); testResolvePathWithEncodedSlash(result); testResolvePathWithPercent(result); testResolvePathWithCaret(result); testResolvePathWithVerticalBar(result); testResolvePathWithBackSlash(result); testResolvePathWithDoubleQuotes(result); testResolvePathWithSpace(result); testResolvePathWithTilde(result); testResolvePathWithEncodedTilde(result); testResolvePathWithEncodedTildeOne(result); testResolveValidNumericIndexInArray(result); testResolveMemberAfterLastInArray(result); testResolveNumericIndexWithLeadingZeroInArray(result); testResolvenonNumericIndexInArray(result); return result; } /** * Test RFC 6901 JSON Pointer resolver for the whole document path. * * @param result * Tests result record. */ private void testResolveWholeDocument(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_KEY_WHOLE + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = in; final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_KEY_WHOLE); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_KEY_WHOLE + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_KEY_WHOLE + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_KEY_WHOLE + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "": 0}. * * @param result * Tests result record. */ private void testResolveEmptyName(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR2 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL2); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR2); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR2 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR2 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR2 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]}. * * @param result * Tests result record. */ private void testResolveSimpleArray(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR1 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = PointerRFCObject.RFC_VAL1; final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR1); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR1 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR1 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR1 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]} array * elements. * * @param result * Tests result record. */ private void testResolveSimpleArrayItems(final TestResult result) { final String[] itemPtrs = new String[] { PointerRFCObject.RFC_PTR1_ITEM1, PointerRFCObject.RFC_PTR1_ITEM2 }; final String[] itemVals = new String[] { PointerRFCObject.RFC_VAL1_ITEM1, PointerRFCObject.RFC_VAL1_ITEM2 }; final JsonObject in = PointerRFCObject.createRFC6901Object(); for (int i = 0; i < itemPtrs.length; i++) { LOGGER.info(" - resolving of \"" + itemPtrs[i] + "\" pointer"); final JsonValue check = Json.createValue(itemVals[i]); final JsonPointer ptr = Json.createPointer(itemPtrs[i]); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + itemPtrs[i] + "\"", "GET operation failed for \"" + itemPtrs[i] + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + itemPtrs[i] + "\"", "GET operation exception: " + e.getMessage()); } } } /** * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1}. Character * {@code '/'} is encoded as {@code "~1"} string. * * @param result * Tests result record. */ private void testResolvePathWithEncodedSlash(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR3_ENC + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL3); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR3_ENC); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR3_ENC + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR3_ENC + "\" path"); } } catch (JsonException e) { LOGGER.info(" ! Exception: " + e.getMessage()); result.fail("GET \"" + PointerRFCObject.RFC_PTR3_ENC + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1}. Character * {@code '/'} is not encoded as {@code "~1"} string. This results in invalid * {@code "/a/b"} path and resolving such path must throw an exception. * * @param result * Tests result record. */ private void testResolvePathWithSlash(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR3 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR3); try { final JsonValue out = ptr.getValue(in); result.fail("GET \"" + PointerRFCObject.RFC_PTR3 + "\"", "GET operation succeeded for \"" + PointerRFCObject.RFC_PTR3 + "\" path"); } catch (JsonException e) { LOGGER.info(" - Expected exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "c%d": 2}. * * @param result * Tests result record. */ private void testResolvePathWithPercent(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR4 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL4); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR4); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR4 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR4 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR4 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "e^f": 3}. * * @param result * Tests result record. */ private void testResolvePathWithCaret(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR5 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL5); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR5); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR5 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR5 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR5 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "g|h": 4}. * * @param result * Tests result record. */ private void testResolvePathWithVerticalBar(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR6 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL6); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR6); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR6 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR6 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR6 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "i\\j": 5}. * * @param result * Tests result record. */ private void testResolvePathWithBackSlash(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR7 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL7); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR7); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR7 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR7 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR7 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "k\"l": 6}. * * @param result * Tests result record. */ private void testResolvePathWithDoubleQuotes(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR8 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL8); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR8); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR8 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR8 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR8 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code " ": 7}. * * @param result * Tests result record. */ private void testResolvePathWithSpace(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR9 + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL9); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR9); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR9 + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR9 + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR9 + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8} without encoding. * Passing this test is not mandatory. * {@see RFC 6901: 3. * Syntax} defines JSON pointer grammar as:
* {@code json-pointer = *( "/" reference-token )}
* {@code reference-token = *( unescaped / escaped )}
* {@code unescaped = %x00-2E / %x30-7D / %x7F-10FFFF}
* {@code escaped = "~" ( "0" / "1" )}
* Characters {@code '/'} and {@code '~'} are excluded from {@code unescaped}. * But having {@code '~'} outside escape sequence may be acceptable. * * @param result * Tests result record. */ private void testResolvePathWithTilde(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR10 + "\" pointer (optional)"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL10); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR10); boolean noError = true; try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { noError = false; LOGGER.info(" - Pointer \"" + PointerRFCObject.RFC_KEY10 + "\" did not return expected value"); } } catch (JsonException e) { noError = false; LOGGER.info(" - Expected exception: " + e.getMessage()); } if (noError) { LOGGER.info( " - Pointer resolving accepts '~' outside escape sequence"); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8}. Character * {@code '~'} is encoded as {@code "~0"} string. * * @param result * Tests result record. */ private void testResolvePathWithEncodedTilde(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_KEY10_ENC + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL10); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_KEY10_ENC); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_KEY10_ENC + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_KEY10_ENC + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_KEY10_ENC + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for {@code "o~1p": 9}. String * {@code "~1"} is encoded as {@code "~01"} String. Proper encoded sequences * transformation is described in * {@see RFC 6901: 4. * Evaluation} chapter: * {@code "the string '~01' correctly becomes '~1' after transformation"}. * * @param result * Tests result record. */ private void testResolvePathWithEncodedTildeOne(final TestResult result) { LOGGER.info(" - resolving of \"" + PointerRFCObject.RFC_PTR11_ENC + "\" pointer"); final JsonObject in = PointerRFCObject.createRFC6901Object(); final JsonValue check = Json.createValue(PointerRFCObject.RFC_VAL11); final JsonPointer ptr = Json.createPointer(PointerRFCObject.RFC_PTR11_ENC); try { final JsonValue out = ptr.getValue(in); if (!JsonAssert.assertEquals(out, check)) { result.fail("GET \"" + PointerRFCObject.RFC_PTR11_ENC + "\"", "GET operation failed for \"" + PointerRFCObject.RFC_PTR11_ENC + "\" path"); } } catch (JsonException e) { result.fail("GET \"" + PointerRFCObject.RFC_PTR11_ENC + "\"", "GET operation exception: " + e.getMessage()); } } /** * Test RFC 6901 JSON Pointer resolver for existing numeric indexes of an * array. {@see RFC * 6901: 4. Evaluation} chapter:
* If the currently referenced value is a JSON array, the reference token MUST * contain either: *
    *
  • characters comprised of digits (see ABNF below; note that leading zeros * are not allowed) that represent an unsigned base-10 integer value, making * the new referenced value the array element with the zero-based index * identified by the token
  • *
*/ private void testResolveValidNumericIndexInArray(final TestResult result) { LOGGER.info( " - resolving of pointer containing existing numeric array index"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createSimpleStringArray5(), SimpleValues.createSimpleIntArray5(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createSimpleObjectArray5() }; final JsonValue[] strings = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.STR_VALUE_1), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_2), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_3), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_4), SimpleValues.toJsonValue(SimpleValues.STR_VALUE_5) }; final JsonValue[] ints = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.INT_VALUE_1), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_2), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_3), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_4), SimpleValues.toJsonValue(SimpleValues.INT_VALUE_5) }; final JsonValue[] bools = new JsonValue[] { SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE), SimpleValues.toJsonValue(SimpleValues.BOOL_TRUE), SimpleValues.toJsonValue(SimpleValues.BOOL_TRUE), SimpleValues.toJsonValue(SimpleValues.BOOL_FALSE), SimpleValues.toJsonValue(SimpleValues.BOOL_TRUE) }; final JsonValue[] objs = new JsonValue[] { SimpleValues.OBJ_VALUE_1, SimpleValues.OBJ_VALUE_2, SimpleValues.OBJ_VALUE_3, SimpleValues.OBJ_VALUE_4, SimpleValues.OBJ_VALUE_5 }; final JsonValue[][] checks = new JsonValue[][] { strings, ints, bools, objs }; // Go trough all array types for (int i = 0; i < arraysIn.length; i++) { // Go trough all valid indexes in arrays for (int j = 0; j < 5; j++) { final String path = "/" + Integer.toString(j); final JsonPointer ptr = Json.createPointer(path); final JsonValue out = ptr.getValue(arraysIn[i]); if (!JsonAssert.assertEquals(out, checks[i][j])) { JsonValue.ValueType type = checks[i][j].getValueType(); String typeName = type == JsonValue.ValueType.TRUE || type == JsonValue.ValueType.FALSE ? "boolean" : type.toString().toLowerCase(); result.fail("GET \"" + path + "\"", "GET operation failed for \"" + path + "\" path on " + typeName + " array"); } } } } /** * Test RFC 6901 JSON Pointer resolver for character {@code '-'} marking the * end of an array. * {@see RFC 6901: 4. * Evaluation} chapter:
* If the currently referenced value is a JSON array, the reference token MUST * contain either: *
    *
  • exactly the single character "-", making the new referenced value the * (nonexistent) member after the last array element
  • *
* Note that the use of the "-" character to index an array will always result * in such an error condition because by definition it refers to a nonexistent * array element. Thus, applications of JSON Pointer need to specify how that * character is to be handled, if it is to be useful. */ private void testResolveMemberAfterLastInArray(final TestResult result) { LOGGER.info(" - resolving of array \"/-\" pointer"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray(), SimpleValues.createSimpleIntArray5(), SimpleValues.createBoolArray2(), SimpleValues.createSimpleObjectArray5() }; final String[] typeNames = new String[] { "empty", "String", "int", "boolean", "JsonObject" }; // Go trough all array types for (int i = 0; i < arraysIn.length; i++) { final JsonPointer ptr = Json.createPointer("/-"); try { final JsonValue out = ptr.getValue(arraysIn[i]); result.fail("GET \"/-\"", "GET operation succeeded for \"/-\" key"); } catch (JsonException e) { LOGGER.info(" - Expected exception for \"/-\" path in " + typeNames[i] + " array: " + e.getMessage()); } } } // TODO: Consider whether passing this test is mandatory or optional. /** * Test RFC 6901 JSON Pointer resolver for existing index with leading * {@code '0'} on array. * {@see RFC 6901: 4. * Evaluation} chapter:
* {@code array-index = %x30 / ( %x31-39 *(%x30-39) )} grammar rule prohibits * indexes with leading {@code '0'} except the case when index is exactly * {@code "0"}. Exact case for {@code "0"} is being checked in other tests. * This test checks illegal values with leading {@code '0'} followed by valid * index numbers. */ private void testResolveNumericIndexWithLeadingZeroInArray( final TestResult result) { LOGGER.info( " - resolving of pointer containing numeric array index with leading '0' (optional)"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createSimpleStringArray5(), SimpleValues.createSimpleIntArray5(), SimpleValues.createSimpleBoolArray5(), SimpleValues.createSimpleObjectArray5() }; final String[] typeNames = new String[] { "String", "int", "boolean", "JsonObject" }; // Go trough all array types for (int i = 0; i < arraysIn.length; i++) { // Go trough all valid indexes in arrays for (int j = 0; j < 5; j++) { final String path = "/0" + Integer.toString(j); final JsonPointer ptr = Json.createPointer(path); try { final JsonValue out = ptr.getValue(arraysIn[i]); LOGGER.info(" ! GET operation succeeded for \"" + path + "\" path on " + typeNames[i] + " array"); // result.fail("GET \""+path+"\"", // "GET operation succeeded for \""+path+"\" key on "+typeNames[i]+" // array"); } catch (JsonException e) { // There are too many combinations to log them. } } } } /** * Test RFC 6901 JSON Pointer resolver for invalid index containing non * numeric characters on array. * {@see RFC 6901: 4. * Evaluation} chapter:
* {@code array-index = %x30 / ( %x31-39 *(%x30-39) )} grammar rule prohibits * indexes with anything else than sequence of digits. Index {@code '-'} is * being checked in another tests. The only exception is path for whole * document ({@code ""}) which must return the whole array. */ private void testResolvenonNumericIndexInArray(final TestResult result) { LOGGER.info(" - resolving of pointer containing non numeric array index"); final JsonArray[] arraysIn = new JsonArray[] { SimpleValues.createEmptyArray(), SimpleValues.createStringArray(), SimpleValues.createSimpleIntArray5(), SimpleValues.createBoolArray2(), SimpleValues.createSimpleObjectArray5() }; final String[] typeNames = new String[] { "empty", "String", "int", "boolean", "JsonObject" }; final String wholeDocument = ""; final String[] paths = new String[] { "/", "/1a", "/b4", "/name" }; // Go trough all array types for (int i = 0; i < arraysIn.length; i++) { final JsonPointer wholeDocPtr = Json.createPointer(wholeDocument); try { final JsonValue wholeOut = wholeDocPtr.getValue(arraysIn[i]); if (!JsonAssert.assertEquals(wholeOut, arraysIn[i])) { result.fail("GET \"" + wholeDocument + "\"", "GET operation failed for \"" + wholeDocument + "\" path on " + typeNames[i] + " array"); } } catch (JsonException e) { result.fail("GET \"" + wholeDocument + "\"", "GET operation failed for \"" + wholeDocument + "\" path on " + typeNames[i] + " array: " + e.getMessage()); } for (int j = 0; j < paths.length; j++) { final JsonPointer ptr = Json.createPointer(paths[j]); try { final JsonValue out = ptr.getValue(arraysIn[i]); result.fail("GET \"" + paths[j] + "\"", "GET operation succeeded for \"" + paths[j] + "\" path on " + typeNames[i] + " array"); } catch (JsonException e) { // There are too many combinations to log them. } } } } } PointerTests.java000066400000000000000000000105011451447132700343210ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/pointertests/* * Copyright (c) 2020, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.pointertests; import ee.jakarta.tck.jsonp.api.common.TestResult; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; // $Id$ /** * {@see RFC 6901}: JavaScript * Object Notation (JSON) Pointer compatibility tests.
* JSON-P API defines {@link jakarta.json.JsonPointer} interface to work with RFC * 6901 JSON Pointer. */ public class PointerTests { /** * Test JSON-P API response on pointer resolving.
* Checks set of JSON pointers from sample object of RFC 6901. * {@see RFC 6901: 4. * Evaluation} and * {@see RFC 6901: 5. * JSON String Representation}. * * @throws AssertionFailedError * when this test failed. * * @testName: jsonPointerResolveTest * @assertion_ids: JSONP:JAVADOC:643; JSONP:JAVADOC:582; JSONP:JAVADOC:583; * JSONP:JAVADOC:584; JSONP:JAVADOC:661; JSONP:JAVADOC:662; * JSONP:JAVADOC:663; * @test_Strategy: Test API response on various JSON pointer values. */ @Test public void jsonPointerResolveTest() { PointerResolve resolveTest = new PointerResolve(); final TestResult result = resolveTest.test(); result.eval(); } /** * Test JSON-P API response on * {@see RFC 6902: * 4.1. add} operation using RFC 6901 pointer instance.
* Checks set of simple JSON values.
* * @throws AssertionFailedError * when this test failed. * * @testName: jsonPointerAddOperationTest * @assertion_ids: JSONP:JAVADOC:642; JSONP:JAVADOC:582; JSONP:JAVADOC:583; * JSONP:JAVADOC:584; JSONP:JAVADOC:661; JSONP:JAVADOC:662; * JSONP:JAVADOC:663; * @test_Strategy: Test API response on various JSON pointer values. */ @Test public void jsonPointerAddOperationTest() { PointerAdd addTest = new PointerAdd(); final TestResult result = addTest.test(); result.eval(); } /** * Test JSON-P API response on * {@see RFC 6902: * 4.2. remove} operation using RFC 6901 pointer instance.
* Checks set of simple JSON values.
* * @throws AssertionFailedError * when this test failed. * * @testName: jsonPointerRemoveOperationTest * @assertion_ids: JSONP:JAVADOC:644; JSONP:JAVADOC:582; JSONP:JAVADOC:661; * @test_Strategy: Test API response on various JSON pointer values. */ @Test public void jsonPointerRemoveOperationTest() { PointerRemove removeTest = new PointerRemove(); final TestResult result = removeTest.test(); result.eval(); } /** * Test JSON-P API response on * {@see RFC 6902: * 4.3. replace} operation using RFC 6901 pointer instance.
* Checks set of simple JSON values.
* * @throws AssertionFailedError * when this test failed. * * @testName: jsonPointerReplaceOperationTest * @assertion_ids: JSONP:JAVADOC:645; JSONP:JAVADOC:582; JSONP:JAVADOC:583; * JSONP:JAVADOC:584; JSONP:JAVADOC:661; JSONP:JAVADOC:662; * JSONP:JAVADOC:663; * @test_Strategy: Test API response on various JSON pointer values. */ @Test public void jsonPointerReplaceOperationTest() { PointerReplace replaceTest = new PointerReplace(); final TestResult result = replaceTest.test(); result.eval(); } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/provider/000077500000000000000000000000001451447132700301645ustar00rootroot00000000000000JsonProviderTest.java000066400000000000000000000104341451447132700342360ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/api/provider/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.api.provider; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Map; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; import jakarta.json.JsonObjectBuilder; import jakarta.json.JsonReader; import jakarta.json.JsonReaderFactory; import jakarta.json.JsonWriter; import jakarta.json.JsonWriterFactory; import jakarta.json.spi.JsonProvider; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonGeneratorFactory; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParserFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests related to JsonProvider. * */ public class JsonProviderTest { private static final String JSONP_PROVIDER_FACTORY = "jakarta.json.provider"; private String factoryValue; @BeforeEach public void setUp() { factoryValue = System.getProperty(JSONP_PROVIDER_FACTORY); System.clearProperty(JSONP_PROVIDER_FACTORY); } @AfterEach public void reset() { if (factoryValue != null) { System.setProperty(JSONP_PROVIDER_FACTORY, factoryValue); } else { System.clearProperty(JSONP_PROVIDER_FACTORY); } } /** * Verifies it is possible to obtain the JsonProvider implementation from a System property. */ @Test public void systemProperty() { System.setProperty(JSONP_PROVIDER_FACTORY, DummyJsonProvider.class.getName()); JsonProvider provider = JsonProvider.provider(); assertEquals(DummyJsonProvider.class, provider.getClass()); } public static class DummyJsonProvider extends JsonProvider { @Override public JsonParser createParser(Reader reader) { return null; } @Override public JsonParser createParser(InputStream in) { return null; } @Override public JsonParserFactory createParserFactory(Map config) { return null; } @Override public JsonGenerator createGenerator(Writer writer) { return null; } @Override public JsonGenerator createGenerator(OutputStream out) { return null; } @Override public JsonGeneratorFactory createGeneratorFactory(Map config) { return null; } @Override public JsonReader createReader(Reader reader) { return null; } @Override public JsonReader createReader(InputStream in) { return null; } @Override public JsonWriter createWriter(Writer writer) { return null; } @Override public JsonWriter createWriter(OutputStream out) { return null; } @Override public JsonWriterFactory createWriterFactory(Map config) { return null; } @Override public JsonReaderFactory createReaderFactory(Map config) { return null; } @Override public JsonObjectBuilder createObjectBuilder() { return null; } @Override public JsonArrayBuilder createArrayBuilder() { return null; } @Override public JsonBuilderFactory createBuilderFactory(Map config) { return null; } } } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/000077500000000000000000000000001451447132700304625ustar00rootroot00000000000000ApiCheckDriver.java000066400000000000000000000131721451447132700340750ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintWriter; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; public final class ApiCheckDriver extends SignatureTestDriver implements Serializable { private static final Logger LOGGER = Logger.getLogger(ApiCheckDriver.class.getName()); /* flags for the Diff utility argument list */ private static final String BASE_FLAG = "-base"; private static final String TEST_FLAG = "-test"; private static final String PACKAGE_NO_SUBS_FLAG = "-PackageWithoutSubpackages"; private static final String PACKAGE_FLAG = "-package"; private static final String EXPACKAGE_FLAG = "-expackage"; private static final String REFLECT_FLAG = "-reflect"; private static final String CONST_FLAG = "-constvalues"; // ---------------------------------------- Methods from SignatureTestDriver @Override protected String normalizeFileName(File f) { return f.getPath(); } @Override protected String[] createTestArguments(String packageListFile, String mapFile, String signatureRepositoryDir, String packageOrClassUnderTest, String classpath, boolean bStaticMode) throws Exception { Class pkgListClass = Class.forName("javasoft.sqe.apiCheck.PackageList"); Constructor pkgCtor = pkgListClass .getDeclaredConstructor(new Class[] { String.class }); Object pkgInstance = pkgCtor.newInstance(new Object[] { packageListFile }); Method pkgMethod = pkgListClass.getDeclaredMethod("getSubPackagesFormatted", new Class[] { String.class }); String excludePkgs = (String) pkgMethod.invoke(pkgInstance, new Object[] { packageOrClassUnderTest }); List sigArgsList = new LinkedList(); sigArgsList.add(BASE_FLAG); sigArgsList.add( getSigFileInfo(packageOrClassUnderTest, mapFile, signatureRepositoryDir) .getFile()); if (classpath != null && classpath.length() > 0) { sigArgsList.add(TEST_FLAG); sigArgsList.add(classpath); } sigArgsList.add(REFLECT_FLAG); sigArgsList.add(CONST_FLAG); sigArgsList.add(PACKAGE_FLAG); sigArgsList.add(packageOrClassUnderTest); if (excludePkgs != null && excludePkgs.length() > 0) { sigArgsList.add(EXPACKAGE_FLAG); sigArgsList.add(excludePkgs); } return (String[]) (sigArgsList.toArray(new String[sigArgsList.size()])); } // END createTestArguments @Override protected boolean runSignatureTest(String packageOrClassName, String[] testArguments) throws Exception { Class diffClass = Class.forName("javasoft.sqe.apiCheck.Diff"); Method mainMethod = diffClass.getDeclaredMethod("main", new Class[] { String[].class }); mainMethod.invoke(null, new Object[] { testArguments }); Method diffMethod = diffClass.getDeclaredMethod("diffsFound", new Class[] {}); return (!((Boolean) diffMethod.invoke(null, new Object[] {})) .booleanValue()); } // END runSignatureTest @Override protected boolean runPackageSearch(String packageOrClassName, String[] testArguments) throws Exception { Class sigTestClass = Class .forName("com.sun.tdk.signaturetest.SignatureTest"); Object sigTestInstance = sigTestClass.newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); // we want to replace the PACKAGE_FLAG with PACKAGE_NO_SUBS_FLAG for (int ii = 0; ii < testArguments.length; ii++) { if (testArguments[ii].equals(PACKAGE_FLAG)) { testArguments[ii] = PACKAGE_NO_SUBS_FLAG; } } // dump args for debugging aid LOGGER.fine( "\nCalling: com.sun.tdk.signaturetest.SignatureTest() with following args:"); for (int ii = 0; ii < testArguments.length; ii++) { LOGGER.fine(" testArguments[" + ii + "] = " + testArguments[ii]); } @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); String rawMessages = output.toString(); // currently, there is no way to determine if there are error msgs in // the rawmessages, so we will always dump this and call it a status. LOGGER.info( "********** Status Report '" + packageOrClassName + "' **********\n"); LOGGER.info(rawMessages); return sigTestInstance.toString().substring(7).startsWith("Passed."); } @Override protected boolean verifyJTAJarForNoXA(String classpath, String repositoryDir) throws Exception { // Need to find out whether implementing this method is really required now. // By default, signature test framework will use sigtest return true; } } // END ApiCheckDriver ApiCheckRecorder.java000066400000000000000000000046561451447132700344160ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * @(#)SigTestRecorder.java 1.1 03/03/05 */ package ee.jakarta.tck.jsonp.signaturetest; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** *

* This implementation of {@link Recorder} will record signatures using the * ApiCheck framework. *

*/ public class ApiCheckRecorder extends Recorder { // ------------------------------------------------------------ Constructors public ApiCheckRecorder(String[] args) { super(args); System.setProperty("pkg.list.file.path", packageListFile); System.setProperty("map.file.path", signatureMapFile); System.setProperty("signature.repository.dir", signatureRepositoryDir); } // END ApiCheckRecorder // ------------------------------------------------------- Protected Methods protected String[] createCommandLine(String version, String classpath, String outputFileName, String packageName) { List command = new ArrayList(); command.add("-constvalues"); command.add("-xpriv"); command.add("-in"); command.add(classpath); return ((String[]) command.toArray(new String[command.size()])); } // END getCommandLine protected void writePackageListFile(String basePackageName, String signatureFile, String packageListFile) throws Exception { // no-op as this is done internally by our version of ApiCheck } // END writePackageListFile protected void doRecord(String[] commandLine) throws Exception { Class batchSetup = Class.forName("javasoft.sqe.apiCheck.BatchSetup"); Method mainMethod = batchSetup.getDeclaredMethod("main", new Class[] { String[].class }); mainMethod.invoke(null, new Object[] { commandLine }); } // END doRecord } // END SigTestRecorder PackageList.java000066400000000000000000000367561451447132700334560ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.logging.Logger; /** * This class represents a package list file. A package list file is used in * conjunction with a set of signature files to execute API signature tests. * Users specify which set of package APIs are verified. Each package's * signature is verified independently. As such all valid sub-packages must be * excluded while a package's signature is being verified. This allows API check * to determine incompatible additional packages included in a distribution. *

* This class builds a package list file when signatures are recorded and * provides an API to provide valid sub-package lists when signatures are played * back (verified). *

* In record mode, this class reads the existing package list file, if one * exists, and removes the package (as well as sub-packages) that are currently * being recorded. All package names read from the existing package list file * are held in a tree set which sorts the package names and keeps duplicate * package names from ocurring. The user can then instruct this class to write * out the package list file. At this point this class reads the currently * recorded signature file and extracts each package names and adds it to the * tree set. After this step the previous package list file is saved as a backup * and the new package list file is written to disk. *

* In playback mode, this class reads the contents of the package list file and * stores each package name in a tree set. Users can then invoke the * getSubPackages method to retrieve the valid sub-packages for any given * package. This is done by simply examining the package names in the tree set * and returning any package name that starts with the parent package name and a * trailing period character. */ class PackageList { private static final Logger LOGGER = Logger.getLogger(PackageList.class.getName()); // Any line in the packageFile starting with this character is a comment private static final char COMMENT_CHAR = '#'; private static final String BACKUP_EXT = ".bak"; // File containing the list of packages and sub-packages private File packageFile; // Signature file where the package signatures were recorded private File sigFile; // Name of the package being recorded private String additionalPackageName; // Name of packages and sub-packages in the private Set packageNames = new TreeSet(); /** * Creates an instance of the PackageList class. The PackageList instance * reads the specified package file and populates it's internal state with the * package names found in this file. Users should use this c'tor when playing * back signature files. Users can init the PackageList instance then use the * "String[] getSubPackages(String packageName)" method to get the list of * valid sub-packages for every package who's signature is being verified. * * @param packageFileName * The name of the file that contains the package list. This file * contains the names of all the packages that exist across all the * signature files that makeup this deliverable. This file is used to * generate a list of valid sub-packages that must be exclued when * testing theor parent package's signature. * * @throws Exception * when the packageFileName does not exist. */ public PackageList(String packageFileName) throws Exception { packageFile = new File(packageFileName); if (packageFile.exists() && packageFile.isFile()) { extractExistingPackageNames(); } else { throw new FileNotFoundException(packageFileName); } } /** * Creates an instance of the PackageList class. The PackageList instance * reads the contents of the packageFileName and stores it in it's internal * state. Next, any packages whos name starts with the specified packageName * are removed from the internal package list. This is done because this is * the package being recorded and we need to remove any previously recorded * package names in case any sub-packages have been removed since the last * time the signatures were recorded. Users should use this c'tor when they * are recording signature files never during playback. * * @param packageName * The name of the package whos signatures are being recorded (along * with sub-packages). * @param sigFileName * The name of the file that contains the recored signatures. * @param packageFileName * The name of the file that contains the package list. This file * contains the names of all the packages that exist across all the * signature files that makeup this deliverable. This file is used to * generate a list of valid sub-packages that must be exclued when * testing their parent package's signature. * * @throws Exception * when an error occurs reading the packageFileName or the * sigFileName does not exist. */ public PackageList(String packageName, String sigFileName, String packageFileName) throws Exception { this.additionalPackageName = packageName; sigFile = new File(sigFileName); if (!sigFile.exists() || !sigFile.isFile()) { throw new FileNotFoundException(sigFileName); } packageFile = new File(packageFileName); if (packageFile.exists() && packageFile.isFile()) { extractExistingPackageNames(); removeExistingPackage(); } } /** * Read the package names stored in the package list file. Each package name * found in the package list file is added to the internal tree set. * * @throws Exception * if there is an error opening or reading the package list file. */ private void extractExistingPackageNames() throws Exception { BufferedReader in = new BufferedReader(new FileReader(packageFile)); String line; String trimLine; try { while ((line = in.readLine()) != null) { trimLine = line.trim(); if (isComment(trimLine) || "".equals(trimLine)) { continue; } packageNames.add(trimLine); } } finally { try { in.close(); } catch (Exception e) { } } } /** * Returns true if the specified string starts with a comment character as * denoted by the COMMENT_CHAR constant. * * @param line * Determins of this line is a comment line * * @return boolean True if the specified line is a comment line else false. */ private boolean isComment(String line) { if (line == null) { return false; } String theLine = line.trim(); if (theLine.length() > 0) { return (theLine.charAt(0) == COMMENT_CHAR); } return false; } /** * Removes package names from the package list file. The packages that are * removed are the ones currently being recorded. The packages being recorded * is denoted by this.additionalPackageName. This includes any sub-packages of * the additionalPackageName. This step is necessary in the cases where a * sub-package has been removed from a parent package in between signature * recordings. */ private void removeExistingPackage() { String delPackage = this.additionalPackageName; String packageName; List delPkgs = new ArrayList(); // iterate over package set and find package names to remove for (Iterator i = packageNames.iterator(); i.hasNext();) { packageName = (String) i.next(); if (packageName.startsWith(delPackage)) { delPkgs.add(packageName); } } // actually remove the package names from the set for (int i = 0; i < delPkgs.size(); i++) { packageName = (String) (delPkgs.get(i)); packageNames.remove(packageName); LOGGER.info( "PackageList.removeExistingPackage() \"" + packageName + "\""); } } /** * Write the package list out to the package list file. This is done by * reading all the package names in the specified signature file and adding * them to the internal tree set. Then the old package list file is removed * and the new package list file is written out. * * @throws Exception * if there is a problem removing the existing package file or * writting the new package list file. */ public void writePkgListFile() throws Exception { readPkgsFromSigFile(); removePkgFile(); writePkgFile(); } /** * Extract the package name from the specified string. The specified string * should have the form: "package jakarta.ejb;" * * @param packageLine * The string containing the package name. * * @return String The extracted package name. * * @throws Exception * if the specified string does not conform to the expected format. */ private String parsePackageName(String packageLine) throws Exception { // sig test framework doesn't have the concept of package entries // as the ApiCheck signature format does. // Instead, we need to parse an entry similar to this: // CLSS public jakarta.some.package.SomeClass return packageLine.substring(packageLine.lastIndexOf(' ') + 1, packageLine.lastIndexOf('.')); } /** * Reads the package names from the signature file. Each package name that is * read is added to this classes internal tree set. * * @throws Exception * if there is an error opening or reading the signature file. */ private void readPkgsFromSigFile() throws Exception { BufferedReader in = new BufferedReader(new FileReader(sigFile)); String line; String trimLine; try { while ((line = in.readLine()) != null) { trimLine = line.trim(); if (trimLine.startsWith("CLSS")) { packageNames.add(parsePackageName(trimLine)); } } } finally { try { in.close(); } catch (Exception e) { } } } /** * Removes the existing package list file. The package list file is actually * moved to a backup file if it exists. The old backup is lost. * * @throws Exception * if there is an error moving the current package list file to a * backup file. */ private void removePkgFile() throws Exception { File backupPkgFile = new File(packageFile.getPath() + BACKUP_EXT); if (backupPkgFile.exists() && backupPkgFile.isFile()) { backupPkgFile.delete(); } if (packageFile.isFile() && packageFile.exists()) { File copyPackageFile = new File(packageFile.getPath()); copyPackageFile.renameTo(backupPkgFile); } } /** * Write a simple header to the package list file to explain what the file is. * * @param out * The BufferedWriter to dump the header to. * * @throws Exception * if there is any errors writing the header to the specified * BufferedWriter. */ private void writeHeader(BufferedWriter out) throws Exception { out.write(COMMENT_CHAR); out.write(COMMENT_CHAR); out.newLine(); out.write(COMMENT_CHAR + " This file contains a list of all the packages"); out.newLine(); out.write(COMMENT_CHAR + " contained in the signature files for this"); out.newLine(); out.write( COMMENT_CHAR + " deliverable. This file is used to exclude valid"); out.newLine(); out.write(COMMENT_CHAR + " sub-packages from being verified when their"); out.newLine(); out.write(COMMENT_CHAR + " parent package's signature is checked."); out.newLine(); out.write(COMMENT_CHAR); out.write(COMMENT_CHAR); out.newLine(); out.newLine(); } /** * Write the list of package names out to a package list file. * * @throws Exception * if there is an error creating and writting the package list file. */ private void writePkgFile() throws Exception { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(packageFile)); writeHeader(out); for (Iterator i = packageNames.iterator(); i.hasNext();) { String packageName = (String) i.next(); out.write(packageName); out.newLine(); LOGGER.info("PackageList.writePkgFile() \"" + packageName + "\""); } } finally { if (out != null) { out.close(); } } } /** * Returns the list of sub-packages that exist in the specified package name. * * @param pkgName * The name of the package we want the sub-package list for. * * @return String[] The sub-packages that live under the specified parent * package. */ public String[] getSubPackages(String pkgName) { List result = new ArrayList(); String subPackageName = pkgName + "."; for (Iterator i = packageNames.iterator(); i.hasNext();) { String packageName = (String) i.next(); if (packageName.startsWith(subPackageName)) { result.add(packageName); } } return (String[]) (result.toArray(new String[result.size()])); } /** * Returns the list of sub-packages that exist in the specified package name. * The returned string matches the API check format of specifying multiple * packages with a single string. Each package name is separated with the "+" * character. * * @param pkgName * The name of the package we want the sub-package list for. * * @return String The sub-packages that live under the specified parent * package. */ public String getSubPackagesFormatted(String pkgName) { StringBuffer formattedResult = new StringBuffer(); String[] result = getSubPackages(pkgName); for (int i = 0; i < result.length; i++) { formattedResult.append(result[i]); if (i < (result.length - 1)) { formattedResult.append("+"); } } return formattedResult.toString(); } /* * Test Driver */ public static void main(String[] args) throws Exception { LOGGER.info("\n\n*** Creating package list file ***\n\n"); PackageList list = new PackageList("jakarta.ejb", "/home/ryano/cts-tools-master/tools/api-check/test/jakarta.ejb.sig_2.1", "/home/ryano/cts-tools-master/tools/api-check/test/pkg-list.txt"); list.writePkgListFile(); LOGGER.info("\n\n*** Reading sub-packages from package list file ***\n\n"); PackageList readList = new PackageList( "/home/ryano/cts-tools-master/tools/api-check/test/pkg-list.txt"); LOGGER.info(readList.getSubPackages("jakarta.ejb").toString()); LOGGER.info(readList.getSubPackagesFormatted("jakarta.ejb").toString()); } } // end class PackageList jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/README000066400000000000000000000050471451447132700313500ustar00rootroot00000000000000The latest signature files are updated in the jsonp-api repoitory (tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest) generated using sigtest-maven-plugin.jar(version 1.4). The signature tests are run using the sigtest-maven-plugin.jar and the framework avaliable in this folder. For TCK developers :- 1. Generate Signature Files : The signature file will be generated by the TCK team using jsonp/tck/pom.xml where the below commented code can be used. The classpath should contain the api jar for which we are generating the signature file. The signature file name expected is jakarta.json.sig_${version} , where version is the api version for which the signature is generated. For TCK users (to run the signature test as a Junit test) :- 1.Set the below system properties correctly : jimage.dir //The jdk9+(jdk11 for this release) will be extracted to this location as to use the Java modules in the path. optional.tech.packages.to.ignore // The optional package that should be ignored while running the signature test signature.sigTestClasspath // the sigTestClasspath that will contain the implementation jar that needs to be tested along with dependent jars. For eg: ${project.build.directory}/jdk11-bundle jakarta.xml.bind ${project.build.directory}/signaturedirectory/jakarta.json-api.jar:${project.build.directory}/jdk11-bundle/java.base:${project.build.directory}/jdk11-bundle/java.rmi:${project.build.directory}/jdk11-bundle/java.sql:${project.build.directory}/jdk11-bundle/java.naming 2. The signature test alone can be run using below command within impl-tck/ directory. mvn clean test -Dtest=JSONPSigTest#signatureTest jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/Recorder.java000066400000000000000000000211021451447132700330660ustar00rootroot00000000000000/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Properties; import java.util.logging.Logger; public abstract class Recorder { private static final Logger LOGGER = Logger.getLogger(Recorder.class.getName()); protected Properties signatureMap; protected String packageListFile; protected String classpath; protected String signatureRepositoryDir; protected String signatureMapFile; // ------------------------------------------------------------ Constructors public Recorder(String[] args) { LOGGER.info("\nCalling: Recorder with following args:"); for (int ii = 0; ii < args.length; ii++) { LOGGER.info(" args[" + ii + "] = " + args[ii]); } Arguments arguments = new Arguments(args); packageListFile = arguments.getPackageList(); classpath = arguments.getClasspath(); signatureRepositoryDir = arguments.getRepository(); signatureMapFile = arguments.getSignatureMap(); loadSignatureMap(signatureMapFile); } // ---------------------------------------------------------- Public Methods /** *

* Record the signatures for each package listed in the * TS_HOME/bin/sig-test.map file. *

*/ public void batchRecord() { for (Iterator i = signatureMap.keySet().iterator(); i.hasNext();) { String basePackageName = (String) i.next(); String version = (String) signatureMap.get(basePackageName); String outputFileName = getOutputFileName(basePackageName, version); String[] commandLine = createCommandLine(version, classpath, outputFileName, basePackageName); try { // dump command line args passed to Setup()... LOGGER.info("\n\nDUMPING SIGTEST COMMAND LINE: \n"); for (int ii = 0; ii < commandLine.length; ii++) { LOGGER.info("commandLine[" + ii + "] = " + commandLine[ii]); } LOGGER.info("\nDONE DUMPING SIGTEST COMMAND LINE. \n\n"); doRecord(commandLine); } catch (Exception e) { throw new RuntimeException(e); } try { writePackageListFile(basePackageName, outputFileName, packageListFile); } catch (Exception e) { LOGGER.info("Unexpected exception: " + e); e.printStackTrace(); System.exit(1); } } } // END batchRecord // ------------------------------------------------------- Protected Methods /** * Write, to a separate file, all of the packages that were recorded. How this * is accomplised will be dependent on the framework. * * @param basePackageName * the base package * @param signatureFile * the file in which the signatures were recorded to * @param packageListFile * the name of the package list file (which may or may not exist) * @throws Exception * if an error occurs writing the file */ protected abstract void writePackageListFile(String basePackageName, String signatureFile, String packageListFile) throws Exception; /** * Create a array of arguments appropriate for use with different signature * recording frameworks. * * @param version * The version of the API * @param classpath * the classpath containing classes that will be recorded * @param outputFileName * the file in which to write the recorded signatures to * @param packageName * the base package name of the signatures that will be recorded */ protected abstract String[] createCommandLine(String version, String classpath, String outputFileName, String packageName); /** * Perform whatever action in necessary to do the actual recording of the * signatures. * * @param commandLine * the options to invoke the recording facility * @throws Exception * if an error occurs during the record process */ protected abstract void doRecord(String[] commandLine) throws Exception; // --------------------------------------------------------- Private Methods private void loadSignatureMap(String signatureTestMapFile) { signatureMap = new Properties(); try { signatureMap.load( new BufferedInputStream(new FileInputStream(signatureTestMapFile))); } catch (FileNotFoundException fnfe) { throw new RuntimeException( "Unable to find or read file '" + signatureTestMapFile + '\''); } catch (IOException ioe) { throw new RuntimeException( "Error processing file '" + signatureTestMapFile + '\'', ioe); } } // END loadSignatureMap private String getOutputFileName(String name, String version) { StringBuffer fileName = new StringBuffer(); fileName.append(signatureRepositoryDir).append(File.separatorChar); fileName.append(name).append(".sig_").append(version); return fileName.toString(); } // END getOutputFileName // --------------------------------------------------- Static Nested Classes private static class Arguments { private static final String CLASSPATH_ARG = "-classpath"; private static final String PKG_LIST_ARG = "-packagelist"; private static final String SIG_MAP_ARG = "-sigmap"; private static final String REPOSITORY_ARG = "-repository"; private String classpath; private String packageList; private String signatureMap; private String repository; // -------------------------------------------------------- Constructors Arguments(String[] args) { // all 4 arguments must be defined, thus there should be 8 elements if (args.length != 8) { LOGGER.info("Error - incorrect number of args should be 8 but was: " + args.length); LOGGER.info("Args passed in were: "); for (int ii = 0; ii < args.length; ii++) { LOGGER.info("args[" + ii + "] = " + args[ii]); } throw new IllegalArgumentException(); } String[] clonedArgs = (String[]) args.clone(); Arrays.sort(clonedArgs); // ensure the proper arguments are specified if (Arrays.binarySearch(clonedArgs, CLASSPATH_ARG) < 0 || Arrays.binarySearch(clonedArgs, PKG_LIST_ARG) < 0 || Arrays.binarySearch(clonedArgs, SIG_MAP_ARG) < 0 || Arrays.binarySearch(clonedArgs, REPOSITORY_ARG) < 0) { usage(); System.exit(1); } for (int i = 0; i < args.length; i += 2) { if (CLASSPATH_ARG.equals(args[i])) { classpath = args[i + 1]; } else if (PKG_LIST_ARG.equals(args[i])) { packageList = args[i + 1]; } else if (SIG_MAP_ARG.equals(args[i])) { signatureMap = args[i + 1]; } else if (REPOSITORY_ARG.equals(args[i])) { repository = args[i + 1]; } else { // shouldn't get here usage(); System.exit(1); } } } // END Arguments // ---------------------------------------------------------- Properties public String getClasspath() { return classpath; } // END getClasspath public String getPackageList() { return packageList; } // END getPackageList public String getSignatureMap() { return signatureMap; } // END getSignatureMap public String getRepository() { return repository; } // END getRepository private static void usage() { String usage = "Usage:" + "\t-classpath (classpath to JARs and/or classes under test)\n" + "\t-packageList (Reference to the sig-test-pkg-list.txt file)\n" + "\t-sigmap (Reference to the sig-test.map file)\n" + "\t-repository (Directory in which to write the recorded" + "\tsignatures to)\n\n"; System.err.println(usage); } // END usage } // END Arguments } RecorderFactory.java000066400000000000000000000051211451447132700343420ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; /** *

* This class is a bit overloaded in that it serves as both a factory and entry * point from Ant to handle signature recording. *

* *

* The desired type is provided using a system property with a key * of recorder.type. Valid values for the * recorder.type property are: *

    *
  • apicheck
  • *
  • sigtest
  • *
*

* *

* If the recorder.type property is not set, this factory will * return a SignatureTestRecorder using the SigTest framework. *

*/ public class RecorderFactory { public static final String API_CHECK_RECORDER = "apicheck"; public static final String SIG_TEST_RECORDER = "sigtest"; // ---------------------------------------------------------- Public Methods /** * Returns a {@link Recorder} instance to handle recording signatures based on * the value specified via the type argument. * * @param type * the type of {@link Recorder} to use * @param args * the args to pass to the {@link Recorder} * @return a {@link Recorder} instanced based on the type * provided */ public static Recorder getRecorder(String type, String[] args) { if (type == null) { throw new IllegalArgumentException("'type' cannot be null"); } if (type.equals(API_CHECK_RECORDER)) { return new ApiCheckRecorder(args); } else if (type.equals(SIG_TEST_RECORDER)) { return new SigTestRecorder(args); } else { throw new IllegalArgumentException("Unknown type: " + type); } } // END getRecorder public static void main(String[] args) { String type = System.getProperty("recorder.type", SIG_TEST_RECORDER); Recorder recorder = getRecorder(type, args); recorder.batchRecord(); } // END main } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/SigTest.java000066400000000000000000000272041451447132700327140ustar00rootroot00000000000000/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates and others. * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.PrintWriter; import java.io.PrintStream; import java.util.ArrayList; import java.util.logging.Logger; /** * This class should be extended by TCK developers that wish to create a set of * signature tests that run outside of any Java EE container. Developers must * implement the getPackages method to specify which packages are to be tested * by the signature test framework. */ public abstract class SigTest { private static final Logger LOGGER = Logger.getLogger(SigTest.class.getName()); protected SignatureTestDriver driver; /** *

* Returns a {@link SignatureTestDriver} appropriate for the particular TCK * (using API check or the Signature Test Framework). *

* *

* The default implementation of this method will return a * {@link SignatureTestDriver} that will use API Check. TCK developers can * override this to return the desired {@link SignatureTestDriver} for their * TCK. */ protected SignatureTestDriver getSigTestDriver() { if (driver == null) { driver = SignatureTestDriverFactory.getInstance(SignatureTestDriverFactory.SIG_TEST); } return driver; } // END getSigTestDriver /** * Returns the location of the package list file. This file denotes the valid * sub-packages of any package being verified in the signature tests. * * Sub-classes are free to override this method if they use a different path * or filename for their package list file. Most users should be able to use * this default implementation. * * @return String The path and name of the package list file. */ protected String getPackageFile() { return getSigTestDriver().getPackageFileImpl(testInfo.getBinDir()); } /** * Returns the path and name of the signature map file that this TCK uses when * conducting signature tests. The signature map file tells the signature test * framework which API versions of tested packages to use. To keep this code * platform independent, be sure to use the File.separator string (or the * File.separatorChar) to denote path separators. * * Sub-classes are free to override this method if they use a different path * or filename for their signature map file. Most users should be able to use * this default implementation. * * @return String The path and name of the signature map file. */ protected String getMapFile() { return getSigTestDriver().getMapFileImpl(testInfo.getBinDir()); } /** * Returns the directory that contains the signature files. * * Sub-classes are free to override this method if they use a different * signature repository directory. Most users should be able to use this * default implementation. * * @return String The signature repository directory. */ protected String getRepositoryDir() { return getSigTestDriver().getRepositoryDirImpl(testInfo.getTSHome()); } /** * Returns the list of Optional Packages which are not accounted for. By * 'unlisted optional' we mean the packages which are Optional to the * technology under test that the user did NOT specifically list for testing. * For example, with Java EE 7 implementation, a user could additionally opt * to test a JSR-88 technology along with the Java EE technology. But if the * user chooses NOT to list this optional technology for testing (via ts.jte * javaee.level prop) then this method will return the packages for JSR-88 * technology with this method call. *

* This is useful for checking for a scenarios when a user may have forgotten * to identify a whole or partial technology implementation and in such cases, * Java EE platform still requires testing it. *

* Any partial or complete impl of an unlistedOptionalPackage sends up a red * flag indicating that the user must also pass tests for this optional * technology area. *

* Sub-classes are free to override this method if they use a different * signature repository directory. Most users should be able to use this * default implementation - which means that there was NO optional technology * packages that need to be tested. * * @return ArrayList */ protected ArrayList getUnlistedOptionalPackages() { return null; } /** * Returns the list of packages that must be tested by the siganture test * framework. TCK developers must implement this method in their signature * test sub-class. * * @return String A list of packages that the developer wishes to test using * the signature test framework. */ protected abstract String[] getPackages(); /** * Returns an array of individual classes that must be tested by the signature * test framwork. TCK developers may override this method when this * functionality is needed. Most will only need package level granularity. * * @return an Array of Strings containing the individual classes the framework * should test. The default implementation of this method returns a * zero-length array. */ protected String[] getClasses() { return new String[] {}; } // END getClasses protected SigTestData testInfo; // holds the bin.dir property /** * Called by the test framework to initialize this test. The method simply * retrieves some state information that is necessary to run the test when * when the test framework invokes the run method (actually the test1 method). * * @param args * List of arguments passed to this test. * @param p * Properties specified by the test user and passed to this test via * the test framework. * @throws Fault * When an error occurs reading or saving the state information * processed by this method. */ public void setup() { try { LOGGER.info("$$$ SigTest.setup() called"); this.testInfo = new SigTestData(); LOGGER.info("$$$ SigTest.setup() complete"); } catch (Exception e) { LOGGER.info("Unexpected exception " + e.getMessage()); //throw new Fault("setup failed!", e); } } /** * Called by the test framework to cleanup any outstanding state. This method * simply passes the message through to the utility class so the * implementation can be used by both framework base classes. * * @throws Fault * When an error occurs cleaning up the state of this test. */ public void cleanup() throws Fault { LOGGER.info("$$$ SigTest.cleanup() called"); try { getSigTestDriver().cleanupImpl(); LOGGER.info("$$$ SigTest.cleanup() returning"); } catch (Exception e) { throw new Fault("Cleanup failed!", e); } } public static class Fault extends Exception { private static final long serialVersionUID = -1574745208867827913L; public Throwable t; /** * creates a Fault with a message */ public Fault(String msg) { super(msg); LOGGER.info(msg); } /** * creates a Fault with a message. * * @param msg * the message * @param t * prints this exception's stacktrace */ public Fault(String msg, Throwable t) { super(msg); this.t = t; // LOGGER.info(msg, t); } /** * creates a Fault with a Throwable. * * @param t * the Throwable */ public Fault(Throwable t) { super(t); this.t = t; } /** * Prints this Throwable and its backtrace to the standard error stream. * */ public void printStackTrace() { if (this.t != null) { this.t.printStackTrace(); } else { super.printStackTrace(); } } /** * Prints this throwable and its backtrace to the specified print stream. * * @param s * PrintStream to use for output */ public void printStackTrace(PrintStream s) { if (this.t != null) { this.t.printStackTrace(s); } else { super.printStackTrace(s); } } /** * Prints this throwable and its backtrace to the specified print writer. * * @param s * PrintWriter to use for output */ public void printStackTrace(PrintWriter s) { if (this.t != null) { this.t.printStackTrace(s); } else { super.printStackTrace(s); } } @Override public Throwable getCause() { return t; } @Override public synchronized Throwable initCause(Throwable cause) { if (t != null) throw new IllegalStateException("Can't overwrite cause"); if (!Exception.class.isInstance(cause)) throw new IllegalArgumentException("Cause not permitted"); this.t = (Exception) cause; return this; } } /** * This exception is used only by EETest. Overrides 3 printStackTrace methods * to preserver the original stack trace. Using setStackTraceElement() would * be more elegant but it is not available prior to j2se 1.4. * * @author Kyle Grucci */ public static class SetupException extends Exception { private static final long serialVersionUID = -7616313680616499158L; public Exception e; /** * creates a Fault with a message */ public SetupException(String msg) { super(msg); } /** * creates a SetupException with a message * * @param msg * the message * @param e * prints this exception's stacktrace */ public SetupException(String msg, Exception e) { super(msg); this.e = e; } /** * Prints this Throwable and its backtrace to the standard error stream. * */ public void printStackTrace() { if (this.e != null) { this.e.printStackTrace(); } else { super.printStackTrace(); } } /** * Prints this throwable and its backtrace to the specified print stream. * * @param s * PrintStream to use for output */ public void printStackTrace(PrintStream s) { if (this.e != null) { this.e.printStackTrace(s); } else { super.printStackTrace(s); } } /** * Prints this throwable and its backtrace to the specified print writer. * * @param s * PrintWriter to use for output */ public void printStackTrace(PrintWriter s) { if (this.e != null) { this.e.printStackTrace(s); } else { super.printStackTrace(s); } } @Override public Throwable getCause() { return e; } @Override public synchronized Throwable initCause(Throwable cause) { if (e != null) throw new IllegalStateException("Can't overwrite cause"); if (!Exception.class.isInstance(cause)) throw new IllegalArgumentException("Cause not permitted"); this.e = (Exception) cause; return this; } } } // end class SigTest SigTestData.java000066400000000000000000000040771451447132700334320ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; import java.util.Properties; /** * This class holds the data passed to a signature test invocation during the * setup phase. This allows us to keep the passed data separate and reuse the * data between the signature test framework base classes. */ public class SigTestData { private Properties props; public SigTestData() { this.props = System.getProperties();; } public String getVehicle() { return props.getProperty("vehicle", ""); } public String getBinDir() { return props.getProperty("bin.dir", ""); } public String getTSHome() { return props.getProperty("ts_home", ""); } public String getTestClasspath() { return props.getProperty("sigTestClasspath", ""); } public String getJavaeeLevel() { return props.getProperty("javaee.level", ""); } public String getCurrentKeywords() { return props.getProperty("current.keywords", ""); } public String getProperty(String prop) { return props.getProperty(prop); } public String getOptionalTechPackagesToIgnore() { return props.getProperty("optional.tech.packages.to.ignore", "jakarta.xml.bind"); } public String getJtaJarClasspath() { return props.getProperty("jtaJarClasspath", ""); } public String getJImageDir() { return props.getProperty("jimage.dir", ""); } } // end class SigTestData SigTestDriver.java000066400000000000000000000236511451447132700340130ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** *

* Wrapper for the Sig Test framework. *

*/ public class SigTestDriver extends SignatureTestDriver { private static final Logger LOGGER = Logger.getLogger(SigTestDriver.class.getName()); private static final String CLASSPATH_FLAG = "-Classpath"; private static final String FILENAME_FLAG = "-FileName"; private static final String PACKAGE_FLAG = "-Package"; private static final String PACKAGE_NO_SUBS_FLAG = "-PackageWithoutSubpackages"; private static final String API_VERSION_FLAG = "-ApiVersion"; private static final String EXCLUDE_FLAG = "-Exclude"; private static final String STATIC_FLAG = "-Static"; private static final String CHECKVALUE_FLAG = "-CheckValue"; // only valid w/ // -static private static final String NO_CHECKVALUE_FLAG = "-NoCheckValue"; private static final String SMODE_FLAG = "-mode"; // requires arg of bin or // src private static final String DEBUG_FLAG = "-Debug"; private static final String FORMATPLAIN_FLAG = "-FormatPlain"; private static final String EXCLUDE_JDK_CLASS_FLAG = "-IgnoreJDKClass"; private static String[] excludeJdkClasses = { "java.util.Map", "java.lang.Object", "java.io.ByteArrayInputStream", "java.io.InputStream", "java.lang.Deprecated", "java.io.Writer", "java.io.OutputStream", "java.util.List", "java.util.Collection", "java.lang.instrument.IllegalClassFormatException", "javax.transaction.xa.XAException", "java.lang.annotation.Repeatable", "java.lang.InterruptedException", "java.lang.CloneNotSupportedException", "java.lang.Throwable", "java.lang.Thread", "java.lang.Enum" }; // ---------------------------------------- Methods from SignatureTestDriver @Override protected String normalizeFileName(File f) { String sURL = null; try { sURL = f.toURI().toURL().toExternalForm(); } catch (Exception e) { throw new RuntimeException(e); } return sURL; } @Override protected String[] createTestArguments(String packageListFile, String mapFile, String signatureRepositoryDir, String packageOrClassUnderTest, String classpath, boolean bStaticMode) throws Exception { SignatureFileInfo info = getSigFileInfo(packageOrClassUnderTest, mapFile, signatureRepositoryDir); PackageList packageList = new PackageList(packageListFile); String[] subPackages = packageList.getSubPackages(packageOrClassUnderTest); List command = new ArrayList(); if (bStaticMode) { // static mode allows finer level of constants checking // -CheckValue says to check the actual const values LOGGER.info("Setting static mode flag to allow constant checking."); command.add(STATIC_FLAG); command.add(CHECKVALUE_FLAG); // specifying "-mode src" allows stricter 2 way verification of constant // vals // (note that using "-mode bin" mode is less strict) command.add(SMODE_FLAG); // command.add("bin"); command.add("src"); } else { LOGGER.info("Not Setting static mode flag to allow constant checking."); } command.add("-Verbose"); command.add(FILENAME_FLAG); command.add(info.getFile()); command.add(CLASSPATH_FLAG); command.add(classpath); command.add(PACKAGE_FLAG); command.add(packageOrClassUnderTest); for (int i = 0; i < subPackages.length; i++) { command.add(EXCLUDE_FLAG); command.add(subPackages[i]); } for(String jdkClassName:excludeJdkClasses) { command.add(EXCLUDE_JDK_CLASS_FLAG); command.add(jdkClassName); } command.add(API_VERSION_FLAG); command.add(info.getVersion()); return ((String[]) command.toArray(new String[command.size()])); } // END createTestArguments @Override protected boolean runSignatureTest(String packageOrClassName, String[] testArguments) throws Exception { Class sigTestClass = Class .forName("com.sun.tdk.signaturetest.SignatureTest"); Object sigTestInstance = sigTestClass.newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); // do some logging to help with troubleshooting LOGGER.info( "\nCalling: com.sun.tdk.signaturetest.SignatureTest() with following args:"); for (int ii = 0; ii < testArguments.length; ii++) { LOGGER.info(" testArguments[" + ii + "] = " + testArguments[ii]); } @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); String rawMessages = output.toString(); // currently, there is no way to determine if there are error msgs in // the rawmessages, so we will always dump this and call it a status. LOGGER.info( "********** Status Report '" + packageOrClassName + "' **********\n"); LOGGER.info(rawMessages); return sigTestInstance.toString().substring(7).startsWith("Passed."); } // END runSignatureTest /* * * @return This returns true if the packageOrClassName is found in the impl. */ @Override protected boolean runPackageSearch(String packageOrClassName, String[] testArguments) throws Exception { Class sigTestClass = Class .forName("com.sun.tdk.signaturetest.SignatureTest"); Object sigTestInstance = sigTestClass.newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); // we want to replace the PACKAGE_FLAG with PACKAGE_NO_SUBS_FLAG for (int ii = 0; ii < testArguments.length; ii++) { if (testArguments[ii].equals(PACKAGE_FLAG)) { testArguments[ii] = PACKAGE_NO_SUBS_FLAG; } } // dump args for debugging aid LOGGER.info( "\nCalling: com.sun.tdk.signaturetest.SignatureTest() with following args:"); for (int ii = 0; ii < testArguments.length; ii++) { LOGGER.info(" testArguments[" + ii + "] = " + testArguments[ii]); } @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); String rawMessages = output.toString(); // currently, there is no way to determine if there are error msgs in // the rawmessages, so we will always dump this and call it a status. LOGGER.info( "********** Status Report '" + packageOrClassName + "' **********\n"); LOGGER.info(rawMessages); return sigTestInstance.toString().substring(7).startsWith("Passed."); } /* * @return This returns true if javax.transaction.xa is not found in the * JTA API jar */ protected boolean verifyJTAJarForNoXA(String classpath, String repositoryDir) throws Exception { LOGGER.info("SigTestDriver#verifyJTAJarForNoXA - Starting:"); boolean result = false; List command = new ArrayList(); // Build Commandline for com.sun.tdk.signaturetest.SignatureTest command.add(STATIC_FLAG); command.add(FILENAME_FLAG); command.add(repositoryDir + "empty.sig"); command.add(PACKAGE_FLAG); command.add("javax.transaction.xa"); command.add(CLASSPATH_FLAG); command.add(classpath); String testArguments [] = (String[]) command.toArray(new String[command.size()]); // do some logging to help with troubleshooting LOGGER.info("\nCalling: com.sun.tdk.signaturetest.SignatureTest() with following args:"); for (int ii=0; ii < testArguments.length; ii++) { LOGGER.info(" testArguments[" +ii+ "] = " + testArguments[ii]); } Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); Object sigTestInstance = sigTestClass.newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); String rawMessages = output.toString(); // currently, there is no way to determine if there are error msgs in // the rawmessages, so we will always dump this and call it a status. LOGGER.info("********** Status Report JTA JAR validation **********\n"); LOGGER.info(rawMessages); return sigTestInstance.toString().substring(7).startsWith("Passed."); } } SigTestEE.java000066400000000000000000000424501451447132700330470ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.PrintStream; import java.util.ArrayList; import java.util.Properties; import java.util.logging.Logger; /** * This class should be extended by TCK developers that wish to create a set of * signature tests that run inside all the Java EE containers. Developers must * implement the getPackages method to specify which packages are to be tested * by the signature test framework within which container. */ public abstract class SigTestEE { private static final Logger LOGGER = Logger.getLogger(SigTestEE.class.getName()); String[] sVehicles; private Object theSharedObject; private Object theSharedObjectArray[]; protected SignatureTestDriver driver; /** *

* Returns a {@link SignatureTestDriver} appropriate for the particular TCK * (using API check or the Signature Test Framework). *

* *

* The default implementation of this method will return a * {@link SignatureTestDriver} that will use API Check. TCK developers can * override this to return the desired {@link SignatureTestDriver} for their * TCK. */ protected SignatureTestDriver getSigTestDriver() { if (driver == null) { driver = SignatureTestDriverFactory.getInstance(SignatureTestDriverFactory.SIG_TEST); } return driver; } // END getSigTestDriver /** * Returns the location of the package list file. This file denotes the valid * sub-packages of any package being verified in the signature tests. *

* Sub-classes are free to override this method if they use a different path * or filename for their package list file. Most users should be able to use * this default implementation. * * @return String The path and name of the package list file. */ protected String getPackageFile() { return getSigTestDriver().getPackageFileImpl(testInfo.getBinDir()); } /** * Returns the path and name of the signature map file that this TCK uses when * conducting signature tests. The signature map file tells the signature test * framework which API versions of tested packages to use. To keep this code * platform independent, be sure to use the File.separator string (or the * File.separatorChar) to denote path separators. *

* Sub-classes are free to override this method if they use a different path * or filename for their signature map file. Most users should be able to use * this default implementation. * * @return String The path and name of the signature map file. */ protected String getMapFile() { return getSigTestDriver().getMapFileImpl(testInfo.getBinDir()); } /** * Returns the directory that contains the signature files. *

* Sub-classes are free to override this method if they use a different * signature repository directory. Most users should be able to use this * default implementation. * * @return String The signature repository directory. */ protected String getRepositoryDir() { return getSigTestDriver().getRepositoryDirImpl(testInfo.getTSHome()); } /** * Returns the list of Optional Packages which are not accounted for. By * 'unlisted optional' we mean the packages which are Optional to the * technology under test that the user did NOT specifically list for testing. * For example, with Java EE 7 implementation, a user could additionally opt * to test a JSR-88 technology along with the Java EE technology. But if the * user chooses NOT to list this optional technology for testing (via ts.jte * javaee.level prop) then this method will return the packages for JSR-88 * technology with this method call. *

* This is useful for checking for a scenarios when a user may have forgotten * to identify a whole or partial technology implementation and in such cases, * Java EE platform still requires testing it. *

* Any partial or complete impl of an unlistedOptionalPackage sends up a red * flag indicating that the user must also pass tests for this optional * technology area. *

* Sub-classes are free to override this method if they use a different * signature repository directory. Most users should be able to use this * default implementation - which means that there was NO optional technology * packages that need to be tested. * * @return ArrayList */ protected ArrayList getUnlistedOptionalPackages() { return null; } /** * Returns the list of packages that must be tested by the signature test * framework. TCK developers must implement this method in their signature * test sub-class. * * @param vehicleName * The name of the vehicle the signature tests should be conducted * in. Valid values for this property are ejb, servlet, ejb and * appclient. * * @return String[] A list of packages that the developer wishes to test using * the signature test framework. If the developer does not wish to * test any package signatures in the specified vehicle this method * should return null. *

* Note, The proper way to insure that this method is not called with * a vehicle name that has no package signatures to verify is to * modify the vehicle.properties in the $TS_HOME/src directory. This * file provides a mapping that maps test directories to a list of * vehicles where the tests in those directory should be run. As an * extra precaution users are encouraged to return null from this * method if the specified vehicle has no package signatures to be * verified within it. */ protected abstract String[] getPackages(String vehicleName); /** *

* Returns an array of individual classes that must be tested by the signature * test framwork within the specified vehicle. TCK developers may override * this method when this functionality is needed. Most will only need package * level granularity. *

* *

* If the developer doesn't wish to test certain classes within a particular * vehicle, the implementation of this method must return a zero-length array. *

* * @param vehicleName * The name of the vehicle the signature tests should be conducted * in. Valid values for this property are ejb, servlet, ejb and * appclient. * * @return an Array of Strings containing the individual classes the framework * should test based on the specifed vehicle. The default * implementation of this method returns a zero-length array no matter * the vehicle specified. */ protected String[] getClasses(String vehicleName) { return new String[] {}; } // END getClasses protected SigTestData testInfo; // holds the bin.dir and vehicle properties /** * Called by the test framework to initialize this test. The method simply * retrieves some state information that is necessary to run the test when * when the test framework invokes the run method (actually the test1 method). * * @param args * List of arguments passed to this test. * @param p * Properties specified by the test user and passed to this test via * the test framework. * * @throws Fault * When an error occurs reading or saving the state information * processed by this method. */ public void setup() { try { LOGGER.info("$$$ SigTestEE.setup() called"); this.testInfo = new SigTestData(); LOGGER.info("$$$ SigTestEE.setup() complete"); } catch (Exception e) { LOGGER.info("Unexpected exception " + e.getMessage()); } } /** * Called by the test framework to run this test. This method utilizes the * state information set in the setup method to run the signature tests. All * signature test code resides in the utility class so it can be reused by the * signature test framework base classes. * * @throws Fault * When an error occurs executing the signature tests. */ public void signatureTest() throws Fault { LOGGER.info("$$$ SigTestEE.signatureTest() called"); SigTestResult results = null; String mapFile = getMapFile(); String repositoryDir = getRepositoryDir(); String[] packages = getPackages(testInfo.getVehicle()); String[] classes = getClasses(testInfo.getVehicle()); String packageFile = getPackageFile(); String testClasspath = testInfo.getTestClasspath(); String optionalPkgToIgnore = testInfo.getOptionalTechPackagesToIgnore(); // unlisted optional packages are technology packages for those optional // technologies (e.g. jsr-88) that might not have been specified by the // user. // We want to ensure there are no full or partial implementations of an // optional technology which were not declared ArrayList unlistedTechnologyPkgs = getUnlistedOptionalPackages(); // If testing with Java 9+, extract the JDK's modules so they can be used // on the testcase's classpath. Properties sysProps = System.getProperties(); String version = (String) sysProps.get("java.version"); if (!version.startsWith("1.")) { String jimageDir = testInfo.getJImageDir(); File f = new File(jimageDir); f.mkdirs(); String javaHome = (String) sysProps.get("java.home"); LOGGER.info("Executing JImage"); try { ProcessBuilder pb = new ProcessBuilder(javaHome + "/bin/jimage", "extract", "--dir=" + jimageDir, javaHome + "/lib/modules"); LOGGER.info(javaHome + "/bin/jimage extract --dir=" + jimageDir + " " + javaHome + "/lib/modules"); pb.redirectErrorStream(true); Process proc = pb.start(); BufferedReader out = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = out.readLine()) != null) { LOGGER.info(line); } int rc = proc.waitFor(); LOGGER.info("JImage RC = " + rc); out.close(); } catch (Exception e) { LOGGER.info("Exception while executing JImage! Some tests may fail."); e.printStackTrace(); } } try { results = getSigTestDriver().executeSigTest(packageFile, mapFile, repositoryDir, packages, classes, testClasspath, unlistedTechnologyPkgs, optionalPkgToIgnore); LOGGER.info(results.toString()); if (!results.passed()) { LOGGER.info("results.passed() returned false"); throw new Exception(); } // Call verifyJtaJarTest based on some conditions, please check the // comment for verifyJtaJarTest. if ("standalone".equalsIgnoreCase(testInfo.getVehicle())) { Properties mapFileAsProps = getSigTestDriver().loadMapFile(mapFile); if (mapFileAsProps == null || mapFileAsProps.size() == 0) { // empty signature file, something unusual LOGGER.info("SigTestEE.signatureTest() returning, " + "as signature map file is empty."); return; } boolean isJTASigTest = false; // Determine whether the signature map file contains package // jakarta.transaction String jtaVersion = mapFileAsProps.getProperty("jakarta.transaction"); if (jtaVersion == null || "".equals(jtaVersion.trim())) { LOGGER.info("SigTestEE.signatureTest() returning, " + "as this is neither JTA TCK run, not Java EE CTS run."); return; } LOGGER.info("jtaVersion " + jtaVersion); // Signature map packaged in JTA TCK will contain a single package // jakarta.transaction if (mapFileAsProps.size() == 1) { isJTASigTest = true; } if (isJTASigTest || !jtaVersion.startsWith("1.2")) { verifyJtaJarTest(); } } LOGGER.info("$$$ SigTestEE.signatureTest() returning"); } catch (Exception e) { if (results != null && !results.passed()) { throw new Fault("SigTestEE.signatureTest() failed!, diffs found"); } else { LOGGER.info("Unexpected exception " + e.getMessage()); throw new Fault("signatureTest failed with an unexpected exception", e); } } } /** * Called by the test framework to run this test. This method utilizes the * state information set in the setup method to run. This test validates * that the javax.transaction.xa type is not in the JTA API jar * * This method is called only for standaone vehicle, as calling the same * for all the vehicles in the CTS run is not necessary. * * This method is called always from JTA 1.3 TCK. The test will be run as * part of Java EE Signature Test only when the signature map in the CTS * bundle is using JTA 1.3 (or higher) signature file. * * If property ts.jte jtaJarClasspath is removed in ts.jte of the JTA 1.3 TCK, * this test will display the available options to call SignatureTest and * fail. Similar failure will be seen in CTS run, if the signature map points * to JTA 1.3 signature file and the property jtaJarClasspath is removed from * ts.jte of CTS bundle. * * @throws Fault When an error occurs executing the signature tests. */ public void verifyJtaJarTest() throws Exception { LOGGER.info("SigTestEE#verifyJtaJarTest - Starting:"); String repositoryDir = getRepositoryDir(); String jtaJarClasspath = testInfo.getJtaJarClasspath(); boolean result = getSigTestDriver().verifyJTAJarForNoXA( testInfo.getJtaJarClasspath(), repositoryDir); if(result) { LOGGER.info("PASS: javax.transaction.xa not found in API jar"); } else { LOGGER.info("FAIL: javax.transaction.xa found in API jar"); throw new Fault("javax.transaction.xa validation failed"); } LOGGER.info("SigTestEE#verifyJtaJarTest returning"); } /** * Called by the test framework to cleanup any outstanding state. This method * simply passes the message through to the utility class so the * implementation can be used by both framework base classes. * * @throws Fault * When an error occurs cleaning up the state of this test. */ public void cleanup() throws Fault { LOGGER.info("$$$ SigTestEE.cleanup() called"); try { getSigTestDriver().cleanupImpl(); LOGGER.info("$$$ SigTestEE.cleanup() returning"); } catch (Exception e) { throw new Fault("Cleanup failed!", e); } } public static class Fault extends Exception { private static final long serialVersionUID = -1574745208867827913L; public Throwable t; /** * creates a Fault with a message */ public Fault(String msg) { super(msg); LOGGER.info(msg); } /** * creates a Fault with a message. * * @param msg * the message * @param t * prints this exception's stacktrace */ public Fault(String msg, Throwable t) { super(msg); this.t = t; LOGGER.info(msg); t.printStackTrace(); } /** * creates a Fault with a Throwable. * * @param t * the Throwable */ public Fault(Throwable t) { super(t); this.t = t; } /** * Prints this Throwable and its backtrace to the standard error stream. * */ public void printStackTrace() { if (this.t != null) { this.t.printStackTrace(); } else { super.printStackTrace(); } } /** * Prints this throwable and its backtrace to the specified print stream. * * @param s * PrintStream to use for output */ public void printStackTrace(PrintStream s) { if (this.t != null) { this.t.printStackTrace(s); } else { super.printStackTrace(s); } } /** * Prints this throwable and its backtrace to the specified print writer. * * @param s * PrintWriter to use for output */ public void printStackTrace(PrintWriter s) { if (this.t != null) { this.t.printStackTrace(s); } else { super.printStackTrace(s); } } @Override public Throwable getCause() { return t; } @Override public synchronized Throwable initCause(Throwable cause) { if (t != null) throw new IllegalStateException("Can't overwrite cause"); if (!Exception.class.isInstance(cause)) throw new IllegalArgumentException("Cause not permitted"); this.t = (Exception) cause; return this; } } } // end class SigTestEE SigTestRecorder.java000066400000000000000000000056241451447132700343250ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * @(#)SigTestRecorder.java 1.1 03/03/05 */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.File; import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** *

* This implementation of {@link Recorder} will record signatures using the * Signature Test framework. *

*/ public class SigTestRecorder extends Recorder { // ------------------------------------------------------------ Constructors public SigTestRecorder(String[] args) { super(args); } // END SigTestRecorder // ------------------------------------------------------- Protected Methods protected String[] createCommandLine(String version, String classpath, String outputFileName, String packageName) { List command = new ArrayList(); // command.add("-xReflection"); command.add("-static"); command.add("-debug"); command.add("-verbose"); command.add("-classpath"); command.add(classpath); command.add("-FileName"); try { command.add(new File(outputFileName).toURI().toURL().toExternalForm()); } catch (Exception e) { throw new RuntimeException(e); } command.add("-package"); command.add(packageName); command.add("-apiVersion"); command.add(version); return ((String[]) command.toArray(new String[command.size()])); } // END getCommandLine protected void writePackageListFile(String basePackageName, String signatureFile, String packageListFile) throws Exception { PackageList packageList = new PackageList(basePackageName, signatureFile, packageListFile); packageList.writePkgListFile(); } // END writePackageListFile protected void doRecord(String[] commandLine) throws Exception { Class batchSetup = Class.forName("com.sun.tdk.signaturetest.Setup"); Object batchSetupInstance = batchSetup.newInstance(); Method runMethod = batchSetup.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(batchSetupInstance, new Object[] { commandLine, new PrintWriter(System.out, true), new PrintWriter(System.err, true) }); } // END doRecord } // END SigTestRecorder SigTestResult.java000066400000000000000000000072211451447132700340310ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class SigTestResult implements Serializable { private static final String NL = System.getProperty("line.separator", "\n"); private List failedPkgs = new ArrayList(); private List passedPkgs = new ArrayList(); private List failedClasses = new ArrayList(); private List passedClasses = new ArrayList(); // ---------------------------------------------------------- Public Methods public synchronized boolean passed() { return (failedPkgs.size() == 0 && failedClasses.size() == 0); } // end passed public synchronized void addFailedPkg(String pkg) { failedPkgs.add(pkg); } // END addFailedPkg public synchronized void addPassedPkg(String pkg) { passedPkgs.add(pkg); } // END addPassedPkg public synchronized void addFailedClass(String className) { failedClasses.add(className); } // END addFailedClass public synchronized void addPassedClass(String className) { passedClasses.add(className); } // END addPassedClass public String toString() { String delim = "******************************************************" + NL; if (!pkgsTested() && !classesTested()) { return (delim + "******** No packages or classes were tested **********" + NL + delim); } StringBuffer buf = new StringBuffer(); buf.append(delim); buf.append(delim); if (passed()) { buf.append("All package signatures passed.").append(NL); } else { buf.append("Some signatures failed.").append(NL); if (failedPkgs.size() > 0) { buf.append("\tFailed packages listed below: ").append(NL); formatList(failedPkgs, buf); } if (failedClasses.size() > 0) { buf.append("\tFailed classes listed below: ").append(NL); formatList(failedClasses, buf); } } if (passedPkgs.size() > 0) { buf.append("\tPassed packages listed below: ").append(NL); formatList(passedPkgs, buf); } if (passedClasses.size() > 0) { buf.append("\tPassed classes listed below: ").append(NL); formatList(passedClasses, buf); } buf.append("\t"); buf.append(delim); buf.append(delim); return buf.toString(); } // END toString // --------------------------------------------------------- Private Methods private synchronized void formatList(List list, StringBuffer buf) { synchronized (this) { for (int i = 0; i < list.size(); i++) { String pkg = (String) (list.get(i)); buf.append("\t\t").append(pkg).append(NL); } } } // END formatList private synchronized boolean pkgsTested() { return (failedPkgs.size() != 0 || passedPkgs.size() != 0); } // END pkgsTested private synchronized boolean classesTested() { return (failedClasses.size() != 0 || passedClasses.size() != 0); } // END classesTested } // end class SigTestResult SignatureTestDriver.java000066400000000000000000000616221451447132700352320ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates and others. * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package ee.jakarta.tck.jsonp.signaturetest; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Properties; import java.util.logging.Logger; /** * Allows the sigtest framework to be extended using different signature test * implementations (e.g. ApiCheck, or SigTest) */ public abstract class SignatureTestDriver { private static final Logger LOGGER = Logger.getLogger(SignatureTestDriver.class.getName()); private static final String SIG_FILE_EXT = ".sig"; private static final String SIG_FILE_VER_SEP = "_"; // ---------------------------------------------------------- Public Methods /** * Implementation of the getPackageFile method defined in both the SigTest and * SigTestEE class. */ public String getPackageFileImpl(String binDir) { String thePkgListFile = "sig-test-pkg-list.txt"; LOGGER.info( "Using the following as the SigTest Package file: " + thePkgListFile); String theFile = binDir + File.separator + thePkgListFile; File ff = new File(theFile); if (!ff.exists()) { // we could not find the map file that coresponded to our SE version so // lets // try to default to use the sig-test-pkg-list.txt LOGGER.warning("The SigTest Package file does not exist: " + thePkgListFile); theFile = binDir + File.separator + "sig-test-pkg-list.txt"; File ff2 = new File(theFile); if (!ff2.exists()) { LOGGER.warning("The Default SigTest Package file does not exist either: " + theFile); } else { LOGGER.info("Defaulting to using SigTest Package file: " + theFile); } } return (theFile); } // END getPackageFileImpl /** * Implementation of the getMapFile method defined in both the SigTest and * SigTestEE class. */ public String getMapFileImpl(String binDir) { String theMapFile = "sig-test.map"; LOGGER.info("Using the following as the sig-Test map file: " + theMapFile); String theFile = binDir + File.separator + theMapFile; File ff = new File(theFile); if (!ff.exists()) { // we could not find the map file that coresponded to our SE version so // lets // try to default to use the sig-test.map LOGGER.warning("The SigTest Map file does not exist: " + theMapFile); theFile = binDir + File.separator + "sig-test.map"; File ff2 = new File(theFile); if (!ff2.exists()) { LOGGER.warning("The SigTest Map file does not exist either: " + theFile); } else { LOGGER.info("Defaulting to using SigTest Map file: " + theFile); } } return (theFile); } // END getMapFileImpl /** * Returns true if the passed in version matches the current Java version * being used. * */ public Boolean isJavaSEVersion(String ver) { String strOSVersion = System.getProperty("java.version"); if (strOSVersion.startsWith(ver)) { return true; } else { return false; } } /** * Implementation of the getRepositoryDir method defined in both the SigTest * and SigTestEE class. */ public String getRepositoryDirImpl(String tsHome) { return (tsHome + File.separator + "src" + File.separator + "com" + File.separator + "sun" + File.separator + "ts" + File.separator + "tests" + File.separator + "signaturetest" + File.separator + "signature-repository" + File.separator); } // END getRepositoryDirImpl /** * Implementation of the cleanup method defined in both the SigTest and * SigTestEE class. */ public void cleanupImpl() throws Exception { try { LOGGER.info("cleanup"); } catch (Exception e) { LOGGER.warning("Exception in cleanup method" + e); throw e; } } // END cleanupImpl /** *

* Execute the signature test. By default, this method passes the result of * {@link #createTestArguments(String, String, String, String, String)} and * passes the result to {@link #runSignatureTest(String, String[])}. * * @param packageListFile * - file containing the packages/classes that are to be verified * @param mapFile * sig-test.map file * @param signatureRepositoryDir * directory containing the recorded signatures * @param packagesUnderTest * packages, defined by the test client, that should be tested * @param classesUnderTest * classes, defined by the test client, that should be tested * @param classpath * The location of the API being verified. Normally the checked API * will be available in the test environment and testClasspath will * be null. In some rare cases the tested API may not be part of the * test environment and will have to specified using this parameter. * @param unaccountedTechPkgs * packages that should not exist within the technology under test. * These will be searched for and if found, will be flagged as error * since they were not explicitly declared as being under test. Their * existence requires explicit testing. * * @return a {@link SigTestResult} containing the result of the test execution */ public SigTestResult executeSigTest(String packageListFile, String mapFile, String signatureRepositoryDir, String[] packagesUnderTest, String[] classesUnderTest, String classpath, ArrayList unaccountedTechPkgs, String optionalPkgToIgnore) throws Exception { SigTestResult result = new SigTestResult(); LOGGER.info("optionalPkgToIgnore = " + optionalPkgToIgnore); String[] arrayOptionalPkgsToIgnore = null; if (optionalPkgToIgnore != null) { arrayOptionalPkgsToIgnore = optionalPkgToIgnore.split(","); } if (packagesUnderTest != null && packagesUnderTest.length > 0) { LOGGER.info("********** BEGIN PACKAGE LEVEL SIGNATURE " + "VALIDATION **********\n\n"); for (int i = 0; i < packagesUnderTest.length; i++) { String packageName = packagesUnderTest[i]; LOGGER.info("********** BEGIN VALIDATE PACKAGE '" + packagesUnderTest[i] + "' **********\n"); LOGGER.info( "********** VALIDATE IN STATIC MODE - TO CHECK CONSANT VALUES ****"); LOGGER.info("Static mode supports checks of static constants values "); String[] args = createTestArguments(packageListFile, mapFile, signatureRepositoryDir, packageName, classpath, true); dumpTestArguments(args); if (runSignatureTest(packageName, args)) { LOGGER.info("********** Package '" + packageName + "' - PASSED (STATIC MODE) **********"); result.addPassedPkg(packageName + "(static mode)"); } else { result.addFailedPkg(packageName + "(static mode)"); LOGGER.info("********** Package '" + packageName + "' - FAILED (STATIC MODE) **********"); } LOGGER.info("\n\n"); LOGGER.info("********** VALIDATE IN REFLECTIVE MODE ****"); LOGGER.info( "Reflective mode supports verification within containers (ie ejb, servlet, etc)"); String[] args2 = createTestArguments(packageListFile, mapFile, signatureRepositoryDir, packageName, classpath, false); dumpTestArguments(args2); if (runSignatureTest(packageName, args2)) { LOGGER.info("********** Package '" + packageName + "' - PASSED (REFLECTION MODE) **********"); result.addPassedPkg(packageName + "(reflection mode)"); } else { result.addFailedPkg(packageName + "(reflection mode)"); LOGGER.info("********** Package '" + packageName + "' - FAILED (REFLECTION MODE) **********"); } LOGGER.info("********** END VALIDATE PACKAGE '" + packagesUnderTest[i] + "' **********\n"); LOGGER.info("\n"); LOGGER.info("\n"); } } if (classesUnderTest != null && classesUnderTest.length > 0) { LOGGER.info("********** BEGIN CLASS LEVEL SIGNATURE " + "VALIDATION **********\n\n"); for (int i = 0; i < classesUnderTest.length; i++) { String className = classesUnderTest[i]; LOGGER.info("********** BEGIN VALIDATE CLASS '" + classesUnderTest[i] + "' **********\n"); LOGGER.info( "********** VALIDATE IN STATIC MODE - TO CHECK CONSANT VALUES ****"); LOGGER.info("Static mode supports checks of static constants values "); String[] args = createTestArguments(packageListFile, mapFile, signatureRepositoryDir, className, classpath, true); dumpTestArguments(args); if (runSignatureTest(className, args)) { LOGGER.info("********** Class '" + className + "' - PASSED (STATIC MODE) **********"); result.addPassedClass(className + "(static mode)"); } else { LOGGER.info("********** Class '" + className + "' - FAILED (STATIC MODE) **********"); result.addFailedClass(className + "(static mode)"); } LOGGER.info("\n\n"); LOGGER.info("********** VALIDATE IN REFLECTIVE MODE ****"); LOGGER.info( "Reflective mode supports verification within containers (ie ejb, servlet, etc)"); String[] args2 = createTestArguments(packageListFile, mapFile, signatureRepositoryDir, className, classpath, false); dumpTestArguments(args2); if (runSignatureTest(className, args2)) { LOGGER.info("********** Class '" + className + "' - PASSED (REFLECTION MODE) **********"); result.addPassedClass(className + "(reflection mode)"); } else { LOGGER.info("********** Class '" + className + "' - FAILED (REFLECTION MODE) **********"); result.addFailedClass(className + "(reflection mode)"); } LOGGER.info("********** END VALIDATE CLASS '" + classesUnderTest[i] + "' **********\n"); LOGGER.info("\n"); LOGGER.info("\n"); } } /* * The following will check if there are Optional Technologies being * implemented but not explicitly defined thru (ts.jte) javaee.level * property. This is a problem because if an optional technolgy is defined * (either whole or partially) than the TCK tests (and sig tests) for those * Optional Technology(s) MUST be run according to related specs. */ if (unaccountedTechPkgs != null) { for (int ii = 0; ii < unaccountedTechPkgs.size(); ii++) { // 'unaccountedTechPkgs' are t hose packages which do not beling to // base technology nor one of the *declared* optionalal technologies. // 'unaccountedTechPkgs' refers to packages for Optional Technologies // which were not defined thru (ts.jte) javaee.level property. // So, make sure there are no whole or partial implementations of // undeclared optional technologies in the implementation String packageName = unaccountedTechPkgs.get(ii); // this is a special case exception to our validation of Optional // Technologies. Normally any partial technology implementations // would be a compatibility failure. HOWEVER, EE 7 Spec (see section // EE 6.1.2 of the Platform spec in the footnote on p. 156.) // requires us to add special handling to avoid testing 'certain' pkgs // within an optional technology. if (isIgnorePackageUnderTest(packageName, arrayOptionalPkgsToIgnore)) { LOGGER.info( "Ignoring special optional technology package: " + packageName); continue; } LOGGER.info("\n\n"); LOGGER.info( "********** CHECK IF OPTIONAL TECHNOLOGIES EXIST IN REFLECTIVE MODE ****"); LOGGER.info( "Reflective mode supports verification within containers (ie ejb, servlet, etc)"); String[] args3 = createTestArguments(packageListFile, mapFile, signatureRepositoryDir, packageName, classpath, false); dumpTestArguments(args3); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - // NOTE: this is the opposite of above in that *if* we find that an // undeclared // optional technology package exists - then we want to raise a red // flag. // The user would have to either remove the technology from the impl if // they do not want to include it in their impl -OR- they must // explicitly // set javaee.level (in ts.jte) to include that Optional Technology AND // after setting this property, they have to pass all related TCK tests. if (runPackageSearch(packageName, args3)) { // if this passed we have an issue because it should not exist - thus // should NOT pass. LOGGER.info("********** Package '" + packageName + "' - WAS FOUND BUT SHOULD NOT BE (REFLECTION MODE) **********"); String err = "ERROR: An area of concern has been identified. "; err += "You must run sigtests with (ts.jte) javaee.level set to "; err += "include all optional technology keywords. Whole and/or "; err += "partial implementations of Optional Technologies "; err += "must be implemented according to the specs AND must pass "; err += "all related TCK tests. To properly pass the "; err += "signature tests - you must identify all Optional Technology "; err += "areas (via javaee.level) that you wish to pass signature tests for."; LOGGER.info(err); result.addFailedPkg(packageName + " (Undeclared Optional Technology package found in reflection mode)"); } else { LOGGER.info("********** Undeclared Optional Technology package '" + packageName + "' - PASSED (REFLECTION MODE) **********"); } } } return result; } // END executeSigTest // ------------------------------------------------------- Protected Methods /** * Using a common set of information, create arguments that are appropriate to * be used with the underlying signature test framework. * * @param packageListFile * - file containing the packages/classes that are to be verified * @param mapFile * sig-test.map file * @param signatureRepositoryDir * directory containing the recorded signatures * @param packageOrClassUnderTest * the class or package * @param classpath * The location of the API being verified. Normally the checked API * will be available in the test environment and testClasspath will * be null. In some rare cases the tested API may not be part of the * test environment and will have to specified using this parameter. */ protected abstract String[] createTestArguments(String packageListFile, String mapFile, String signatureRepositoryDir, String packageOrClassUnderTest, String classpath, boolean bStaticMode) throws Exception; /** * Invoke the underlying signature test framework for the specified package or * class. * * @param packageOrClassName * the package or class to be validated * @param testArguments * the arguments necessary to invoke the signature test framework * * @return true if the test passed, otherwise false */ protected abstract boolean runSignatureTest(String packageOrClassName, String[] testArguments) throws Exception; /** * This checks if a class exists or not within the impl. * * @param packageOrClassName * the package or class to be validated * * @return true if the package was found to exist, otherwise * false */ protected abstract boolean runPackageSearch(String packageOrClassName, String[] testArguments) throws Exception; /** * This method checks whether JTA API jar contains classes from * javax.transaction.xa package * * @param classpath * the classpath, pointing JTA API jar * @param repositoryDir * the directory containing an empty signature file * * @return true if the package javax.transaction.xa is not * found in the JTA API jar, otherwise false */ protected abstract boolean verifyJTAJarForNoXA(String classpath, String repositoryDir) throws Exception; /** * Loads the specified file into a Properties object provided the specified * file exists and is a regular file. The call to new FileInputStream verifies * that the specfied file is a regular file and exists. * * @param mapFile * the path and name of the map file to be loaded * * @return Properties The Properties object initialized with the contents of * the specified file * * @throws java.io.IOException * If the specified map file does not exist or is not a regular * file, can also be thrown if there is an error creating an input * stream from the specified file. */ public Properties loadMapFile(String mapFile) throws IOException, FileNotFoundException { FileInputStream in = null; try { File map = new File(mapFile); Properties props = new Properties(); in = new FileInputStream(map); props.load(in); return props; } finally { try { if (in != null) { in.close(); } } catch (Throwable t) { // do nothing } } } // END loadMapFile /** * This method will attempt to build a fully-qualified filename in the format * of respositoryDir + baseName + * .sig_ + version. * * @param baseName * the base portion of the signature filename * @param repositoryDir * the directory in which the signatures are stored * @param version * the version of the signature file * @throws FileNotFoundException * if the file cannot be validated as existing and is in fact a file * @return a valid, fully qualified filename, appropriate for the system the * test is being run on */ protected String getSigFileName(String baseName, String repositoryDir, String version) throws FileNotFoundException { String sigFile; if (repositoryDir.endsWith(File.separator)) { sigFile = repositoryDir + baseName + SIG_FILE_EXT + SIG_FILE_VER_SEP + version; } else { sigFile = repositoryDir + File.separator + baseName + SIG_FILE_EXT + SIG_FILE_VER_SEP + version; } File testFile = new File(sigFile); if (!testFile.exists() && !testFile.isFile()) { throw new FileNotFoundException( "Signature file \"" + sigFile + "\" does not exist."); } // we are actually requiring this normalizeFileName call to get // things working on Windows. Without this, if we just return the // testFile; we will fail on windows. (Solaris works either way) // IMPORTANT UPDATE!! (4/5/2011) // in sigtest 2.2: they stopped supporting the normalized version which // created a string filename = // "file://com/sun/ts/tests/signaturetest/foo.sig" // so now use file path and name only. // return normalizeFileName(testFile); return testFile.toString(); } // END getSigFileName protected abstract String normalizeFileName(File f); /** * Returns the name and path to the signature file that contains the specified * package's signatures. * * @param packageName * The package under test * @param mapFile * The name of the file that maps package names to versions * @param repositoryDir * The directory that conatisn all signature files * * @return String The path and name of the siganture file that contains the * specified package's signatures * * @throws Exception * if the determined signature file is not a regular file or does * not exist */ protected SignatureFileInfo getSigFileInfo(String packageName, String mapFile, String repositoryDir) throws Exception { String originalPackage = packageName; String name = null; String version = null; Properties props = loadMapFile(mapFile); while (true) { boolean packageFound = false; for (Enumeration e = props.propertyNames(); e.hasMoreElements();) { name = (String) (e.nextElement()); if (name.equals(packageName)) { version = props.getProperty(name); packageFound = true; break; } // end if } // end for if (packageFound) { break; } /* * If we get here we did not find a package name in the properties file * that matches the package name under test. So we look for a package name * in the properties file that could be the parent package for the package * under test. We do this by removing the specified packages last package * name section. So jakarta.ejb.spi would become jakarta.ejb */ int index = packageName.lastIndexOf("."); if (index <= 0) { throw new Exception("Package \"" + originalPackage + "\" not specified in mapping file \"" + mapFile + "\"."); } packageName = packageName.substring(0, index); } // end while /* Return the expected name of the signature file */ return new SignatureFileInfo(getSigFileName(name, repositoryDir, version), version); } // END getSigFileInfo // --------------------------------------------------------- Private Methods /* * This returns true is the passed in packageName matches one of the packages * that are listed in the arrayOptionalPkgsToIgnore. arrayOptionalPkgsToIgnore * is ultimately defined in the ts.jte property * 'optional.tech.packages.to.ignore' If one of the entries in * arrayOptionalPkgsToIgnore matches the packageName then that means we return * TRUE to indicate we should ignore and NOT TEST that particular package. */ private static boolean isIgnorePackageUnderTest(String packageName, String[] arrayOptionalPkgsToIgnore) { // if anything is null - consider no match if ((packageName == null) || (arrayOptionalPkgsToIgnore == null)) { return false; } for (int ii = 0; ii < arrayOptionalPkgsToIgnore.length; ii++) { if (packageName.equals(arrayOptionalPkgsToIgnore[ii])) { // we found a match - return true; } } return false; } /** * Prints the specified list of parameters to the message log. Used for * debugging purposes only. * * @param params * The list of parameters to dump. */ private static void dumpTestArguments(String[] params) { if (params != null && params.length > 0) { LOGGER.fine("----------------- BEGIN SIG PARAM DUMP -----------------"); for (int i = 0; i < params.length; i++) { LOGGER.fine(" Param[" + i + "]: " + params[i]); } LOGGER.fine("------------------ END SIG PARAM DUMP ------------------"); } } // END dumpTestArguments // ----------------------------------------------------------- Inner Classes /** * A simple data structure containing the fully qualified path to the * signature file as well as the version being tested. */ protected static class SignatureFileInfo { private String file; private String version; // -------------------------------------------------------- Constructors public SignatureFileInfo(String file, String version) { if (file == null) { throw new IllegalArgumentException("'file' argument cannot be null"); } if (version == null) { throw new IllegalArgumentException("'version' argument cannot be null"); } this.file = file; this.version = version; } // END SignatureFileInfo // ------------------------------------------------------ Public Methods public String getFile() { return file; } // END getFileIncludingPath public String getVersion() { return version; } // END getVersion } } // END SigTestDriver SignatureTestDriverFactory.java000066400000000000000000000043011451447132700365510ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest; /** *

* Factory to obtain SignatureTestDriver implementations. *

*/ public class SignatureTestDriverFactory { /** *

* Identifier for the driver that uses API Check to perform signature * validation. *

*/ public static final String API_CHECK = "apicheck"; /** *

* Identifier for the driver that uses the Signature Test framwork for * signature validation. *

*/ public static final String SIG_TEST = "sigtest"; // ------------------------------------------------------------ Constructors // Access via factory method private SignatureTestDriverFactory() { } // END SignatureTestDriverFactory // ---------------------------------------------------------- Public Methods /** *

* Obtain a {@link SignatureTestDriver} instance based on the * type argument. * * @param type * the driver type to create * @return a {@link SignatureTestDriver} implementation */ public static SignatureTestDriver getInstance(String type) { if (type == null || type.length() == 0) { throw new IllegalArgumentException("Type was null or empty"); } if (API_CHECK.equals(type)) { return new ApiCheckDriver(); } else if (SIG_TEST.equals(type)) { return new SigTestDriver(); } else { throw new IllegalArgumentException("Unknown Type: '" + type + '\''); } } // END getInstance } // END SignatureTestDriverFactory jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/jsonp/000077500000000000000000000000001451447132700316135ustar00rootroot00000000000000JSONPSigTest.java000066400000000000000000000246421451447132700346030ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/java/ee/jakarta/tck/jsonp/signaturetest/jsonp/* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package ee.jakarta.tck.jsonp.signaturetest.jsonp; import java.util.Properties; import ee.jakarta.tck.jsonp.signaturetest.SigTestEE; import ee.jakarta.tck.jsonp.signaturetest.SigTestResult; import org.junit.jupiter.api.Test; import java.io.*; import java.util.ArrayList; import java.util.logging.Logger; /* * This class is a simple example of a signature test that extends the * SigTest framework class. This signature test is run outside of the * Java EE containers. This class also contains the boilerplate * code necessary to create a signature test using the test framework. * To see a complete TCK example see the javaee directory for the Java EE * TCK signature test class. */ public class JSONPSigTest extends SigTestEE { private static final Logger LOGGER = Logger.getLogger(JSONPSigTest.class.getName()); public JSONPSigTest(){ setup(); } /***** Abstract Method Implementation *****/ /** * Returns a list of strings where each string represents a package name. Each * package name will have it's signature tested by the signature test * framework. * * @return String[] The names of the packages whose signatures should be * verified. */ protected String[] getPackages(String vehicleName) { return new String[] { "jakarta.json", "jakarta.json.spi", "jakarta.json.stream", }; } public File writeStreamToTempFile(InputStream inputStream, String tempFilePrefix, String tempFileSuffix) throws IOException { FileOutputStream outputStream = null; try { File file = File.createTempFile(tempFilePrefix, tempFileSuffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return file; } finally { if (outputStream != null) { outputStream.close(); } } } public File writeStreamToSigFile(InputStream inputStream, String packageVersion) throws IOException { FileOutputStream outputStream = null; String tmpdir = System.getProperty("java.io.tmpdir"); try { File sigfile = new File(tmpdir+File.separator+"jakarta.json.sig_"+packageVersion); if(sigfile.exists()){ sigfile.delete(); LOGGER.info("Existing signature file deleted to create new one"); } if(!sigfile.createNewFile()){ LOGGER.info("signature file is not created"); } outputStream = new FileOutputStream(sigfile); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return sigfile; } finally { if (outputStream != null) { outputStream.close(); } } } /***** Boilerplate Code *****/ /* * The following comments are specified in the base class that defines the * signature tests. This is done so the test finders will find the right class * to run. The implementation of these methods is inherited from the super * class which is part of the signature test framework. */ // NOTE: If the API under test is not part of your testing runtime // environment, you may use the property sigTestClasspath to specify // where the API under test lives. This should almost never be used. // Normally the API under test should be specified in the classpath // of the VM running the signature tests. Use either the first // comment or the one below it depending on which properties your // signature tests need. Please do not use both comments. /* * @class.setup_props: ts_home, The base path of this TCK; sigTestClasspath; */ /* * @testName: signatureTest * * @assertion: A JSONP container must implement the required classes and APIs * specified in the JSONP Specification. * * @test_Strategy: Using reflection, gather the implementation specific * classes and APIs. Compare these results with the expected (required) * classes and APIs. * */ @Test public void signatureTest() throws Fault { LOGGER.info("$$$ JSONPSigTest.signatureTest() called"); SigTestResult results = null; String mapFile = null; String packageFile = null; String repositoryDir = null; Properties mapFileAsProps = null; try { InputStream inStreamMapfile = JSONPSigTest.class.getClassLoader().getResourceAsStream("ee/jakarta/tck/jsonp/signaturetest/sig-test.map"); File mFile = writeStreamToTempFile(inStreamMapfile, "sig-test", ".map"); mapFile = mFile.getCanonicalPath(); LOGGER.info("mapFile location is :"+mapFile); InputStream inStreamPackageFile = JSONPSigTest.class.getClassLoader().getResourceAsStream("ee/jakarta/tck/jsonp/signaturetest/sig-test-pkg-list.txt"); File pFile = writeStreamToTempFile(inStreamPackageFile, "sig-test-pkg-list", ".txt"); packageFile = pFile.getCanonicalPath(); LOGGER.info("packageFile location is :"+packageFile); mapFileAsProps = getSigTestDriver().loadMapFile(mapFile); String packageVersion = mapFileAsProps.getProperty("jakarta.json"); LOGGER.info("Package version from mapfile :"+ packageVersion); InputStream inStreamSigFile = JSONPSigTest.class.getClassLoader().getResourceAsStream("ee/jakarta/tck/jsonp/signaturetest/jakarta.json.sig_"+packageVersion); File sigFile = writeStreamToSigFile(inStreamSigFile, packageVersion); LOGGER.info("signature File location is :"+sigFile.getCanonicalPath()); repositoryDir = System.getProperty("java.io.tmpdir"); } catch(IOException ex){ LOGGER.info("Exception while creating temp files :"+ex); } String[] packages = getPackages(testInfo.getVehicle()); String[] classes = getClasses(testInfo.getVehicle()); String testClasspath = System.getProperty("signature.sigTestClasspath"); String optionalPkgToIgnore = testInfo.getOptionalTechPackagesToIgnore(); // unlisted optional packages are technology packages for those optional // technologies (e.g. jsr-88) that might not have been specified by the // user. // We want to ensure there are no full or partial implementations of an // optional technology which were not declared ArrayList unlistedTechnologyPkgs = getUnlistedOptionalPackages(); // If testing with Java 9+, extract the JDK's modules so they can be used // on the testcase's classpath. Properties sysProps = System.getProperties(); String version = (String) sysProps.get("java.version"); if (!version.startsWith("1.")) { String jimageDir = testInfo.getJImageDir(); File f = new File(jimageDir); f.mkdirs(); String javaHome = (String) sysProps.get("java.home"); LOGGER.info("Executing JImage"); try { ProcessBuilder pb = new ProcessBuilder(javaHome + "/bin/jimage", "extract", "--dir=" + jimageDir, javaHome + "/lib/modules"); LOGGER.info(javaHome + "/bin/jimage extract --dir=" + jimageDir + " " + javaHome + "/lib/modules"); pb.redirectErrorStream(true); Process proc = pb.start(); BufferedReader out = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = out.readLine()) != null) { LOGGER.info(line); } int rc = proc.waitFor(); LOGGER.info("JImage RC = " + rc); out.close(); } catch (Exception e) { LOGGER.info("Exception while executing JImage! Some tests may fail."); e.printStackTrace(); } } try { results = getSigTestDriver().executeSigTest(packageFile, mapFile, repositoryDir, packages, classes, testClasspath, unlistedTechnologyPkgs, optionalPkgToIgnore); LOGGER.info(results.toString()); if (!results.passed()) { LOGGER.info("results.passed() returned false"); throw new Exception(); } // Call verifyJtaJarTest based on some conditions, please check the // comment for verifyJtaJarTest. if ("standalone".equalsIgnoreCase(testInfo.getVehicle())) { if (mapFileAsProps == null || mapFileAsProps.size() == 0) { // empty signature file, something unusual LOGGER.info("JSONPSigTest.signatureTest() returning, " + "as signature map file is empty."); return; } boolean isJTASigTest = false; // Determine whether the signature map file contains package // jakarta.transaction String jtaVersion = mapFileAsProps.getProperty("jakarta.transaction"); if (jtaVersion == null || "".equals(jtaVersion.trim())) { LOGGER.info("JSONPSigTest.signatureTest() returning, " + "as this is neither JTA TCK run, not Java EE CTS run."); return; } LOGGER.info("jtaVersion " + jtaVersion); // Signature map packaged in JTA TCK will contain a single package // jakarta.transaction if (mapFileAsProps.size() == 1) { isJTASigTest = true; } if (isJTASigTest || !jtaVersion.startsWith("1.2")) { verifyJtaJarTest(); } } LOGGER.info("$$$ JSONPSigTest.signatureTest() returning"); } catch (Exception e) { if (results != null && !results.passed()) { throw new Fault("JSONPSigTest.signatureTest() failed!, diffs found"); } else { LOGGER.info("Unexpected exception " + e.getMessage()); throw new Fault("signatureTest failed with an unexpected exception", e); } } } /* * Call the parent class's cleanup method. */ } // end class JSONPSigTest jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/000077500000000000000000000000001451447132700227325ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/000077500000000000000000000000001451447132700233235ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/000077500000000000000000000000001451447132700247405ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/tck/000077500000000000000000000000001451447132700255215ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/tck/jsonp/000077500000000000000000000000001451447132700266525ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/tck/jsonp/signaturetest/000077500000000000000000000000001451447132700315535ustar00rootroot00000000000000jakarta.json.sig_2.1.0000066400000000000000000001200611451447132700353030ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/tck/jsonp/signaturetest#Signature file v4.1 #Version 2.1_se11 CLSS public final jakarta.json.Json meth public static jakarta.json.JsonArrayBuilder createArrayBuilder() meth public static jakarta.json.JsonArrayBuilder createArrayBuilder(jakarta.json.JsonArray) meth public static jakarta.json.JsonArrayBuilder createArrayBuilder(java.util.Collection) meth public static jakarta.json.JsonBuilderFactory createBuilderFactory(java.util.Map) meth public static jakarta.json.JsonMergePatch createMergeDiff(jakarta.json.JsonValue,jakarta.json.JsonValue) meth public static jakarta.json.JsonMergePatch createMergePatch(jakarta.json.JsonValue) meth public static jakarta.json.JsonNumber createValue(double) meth public static jakarta.json.JsonNumber createValue(int) meth public static jakarta.json.JsonNumber createValue(java.lang.Number) meth public static jakarta.json.JsonNumber createValue(java.math.BigDecimal) meth public static jakarta.json.JsonNumber createValue(java.math.BigInteger) meth public static jakarta.json.JsonNumber createValue(long) meth public static jakarta.json.JsonObjectBuilder createObjectBuilder() meth public static jakarta.json.JsonObjectBuilder createObjectBuilder(jakarta.json.JsonObject) meth public static jakarta.json.JsonObjectBuilder createObjectBuilder(java.util.Map) meth public static jakarta.json.JsonPatch createDiff(jakarta.json.JsonStructure,jakarta.json.JsonStructure) meth public static jakarta.json.JsonPatch createPatch(jakarta.json.JsonArray) meth public static jakarta.json.JsonPatchBuilder createPatchBuilder() meth public static jakarta.json.JsonPatchBuilder createPatchBuilder(jakarta.json.JsonArray) meth public static jakarta.json.JsonPointer createPointer(java.lang.String) meth public static jakarta.json.JsonReader createReader(java.io.InputStream) meth public static jakarta.json.JsonReader createReader(java.io.Reader) meth public static jakarta.json.JsonReaderFactory createReaderFactory(java.util.Map) meth public static jakarta.json.JsonString createValue(java.lang.String) meth public static jakarta.json.JsonWriter createWriter(java.io.OutputStream) meth public static jakarta.json.JsonWriter createWriter(java.io.Writer) meth public static jakarta.json.JsonWriterFactory createWriterFactory(java.util.Map) meth public static jakarta.json.stream.JsonGenerator createGenerator(java.io.OutputStream) meth public static jakarta.json.stream.JsonGenerator createGenerator(java.io.Writer) meth public static jakarta.json.stream.JsonGeneratorFactory createGeneratorFactory(java.util.Map) meth public static jakarta.json.stream.JsonParser createParser(java.io.InputStream) meth public static jakarta.json.stream.JsonParser createParser(java.io.Reader) meth public static jakarta.json.stream.JsonParserFactory createParserFactory(java.util.Map) meth public static java.lang.String decodePointer(java.lang.String) meth public static java.lang.String encodePointer(java.lang.String) supr java.lang.Object CLSS public abstract interface jakarta.json.JsonArray intf jakarta.json.JsonStructure intf java.util.List meth public <%0 extends java.lang.Object, %1 extends jakarta.json.JsonValue> java.util.List<{%%0}> getValuesAs(java.util.function.Function<{%%1},{%%0}>) meth public abstract <%0 extends jakarta.json.JsonValue> java.util.List<{%%0}> getValuesAs(java.lang.Class<{%%0}>) meth public abstract boolean getBoolean(int) meth public abstract boolean getBoolean(int,boolean) meth public abstract boolean isNull(int) meth public abstract int getInt(int) meth public abstract int getInt(int,int) meth public abstract jakarta.json.JsonArray getJsonArray(int) meth public abstract jakarta.json.JsonNumber getJsonNumber(int) meth public abstract jakarta.json.JsonObject getJsonObject(int) meth public abstract jakarta.json.JsonString getJsonString(int) meth public abstract java.lang.String getString(int) meth public abstract java.lang.String getString(int,java.lang.String) CLSS public abstract interface jakarta.json.JsonArrayBuilder meth public abstract jakarta.json.JsonArray build() meth public abstract jakarta.json.JsonArrayBuilder add(boolean) meth public abstract jakarta.json.JsonArrayBuilder add(double) meth public abstract jakarta.json.JsonArrayBuilder add(int) meth public abstract jakarta.json.JsonArrayBuilder add(jakarta.json.JsonArrayBuilder) meth public abstract jakarta.json.JsonArrayBuilder add(jakarta.json.JsonObjectBuilder) meth public abstract jakarta.json.JsonArrayBuilder add(jakarta.json.JsonValue) meth public abstract jakarta.json.JsonArrayBuilder add(java.lang.String) meth public abstract jakarta.json.JsonArrayBuilder add(java.math.BigDecimal) meth public abstract jakarta.json.JsonArrayBuilder add(java.math.BigInteger) meth public abstract jakarta.json.JsonArrayBuilder add(long) meth public abstract jakarta.json.JsonArrayBuilder addNull() meth public jakarta.json.JsonArrayBuilder add(int,boolean) meth public jakarta.json.JsonArrayBuilder add(int,double) meth public jakarta.json.JsonArrayBuilder add(int,int) meth public jakarta.json.JsonArrayBuilder add(int,jakarta.json.JsonArrayBuilder) meth public jakarta.json.JsonArrayBuilder add(int,jakarta.json.JsonObjectBuilder) meth public jakarta.json.JsonArrayBuilder add(int,jakarta.json.JsonValue) meth public jakarta.json.JsonArrayBuilder add(int,java.lang.String) meth public jakarta.json.JsonArrayBuilder add(int,java.math.BigDecimal) meth public jakarta.json.JsonArrayBuilder add(int,java.math.BigInteger) meth public jakarta.json.JsonArrayBuilder add(int,long) meth public jakarta.json.JsonArrayBuilder addAll(jakarta.json.JsonArrayBuilder) meth public jakarta.json.JsonArrayBuilder addNull(int) meth public jakarta.json.JsonArrayBuilder remove(int) meth public jakarta.json.JsonArrayBuilder set(int,boolean) meth public jakarta.json.JsonArrayBuilder set(int,double) meth public jakarta.json.JsonArrayBuilder set(int,int) meth public jakarta.json.JsonArrayBuilder set(int,jakarta.json.JsonArrayBuilder) meth public jakarta.json.JsonArrayBuilder set(int,jakarta.json.JsonObjectBuilder) meth public jakarta.json.JsonArrayBuilder set(int,jakarta.json.JsonValue) meth public jakarta.json.JsonArrayBuilder set(int,java.lang.String) meth public jakarta.json.JsonArrayBuilder set(int,java.math.BigDecimal) meth public jakarta.json.JsonArrayBuilder set(int,java.math.BigInteger) meth public jakarta.json.JsonArrayBuilder set(int,long) meth public jakarta.json.JsonArrayBuilder setNull(int) CLSS public abstract interface jakarta.json.JsonBuilderFactory meth public abstract jakarta.json.JsonArrayBuilder createArrayBuilder() meth public abstract jakarta.json.JsonObjectBuilder createObjectBuilder() meth public abstract java.util.Map getConfigInUse() meth public jakarta.json.JsonArrayBuilder createArrayBuilder(jakarta.json.JsonArray) meth public jakarta.json.JsonArrayBuilder createArrayBuilder(java.util.Collection) meth public jakarta.json.JsonObjectBuilder createObjectBuilder(jakarta.json.JsonObject) meth public jakarta.json.JsonObjectBuilder createObjectBuilder(java.util.Map) CLSS public final jakarta.json.JsonConfig fld public final static java.lang.String KEY_STRATEGY = "jakarta.json.JsonConfig.keyStrategy" innr public final static !enum KeyStrategy supr java.lang.Object CLSS public final static !enum jakarta.json.JsonConfig$KeyStrategy outer jakarta.json.JsonConfig fld public final static jakarta.json.JsonConfig$KeyStrategy FIRST fld public final static jakarta.json.JsonConfig$KeyStrategy LAST fld public final static jakarta.json.JsonConfig$KeyStrategy NONE meth public static jakarta.json.JsonConfig$KeyStrategy valueOf(java.lang.String) meth public static jakarta.json.JsonConfig$KeyStrategy[] values() supr java.lang.Enum CLSS public jakarta.json.JsonException cons public init(java.lang.String) cons public init(java.lang.String,java.lang.Throwable) supr java.lang.RuntimeException hfds serialVersionUID CLSS public abstract interface jakarta.json.JsonMergePatch meth public abstract jakarta.json.JsonValue apply(jakarta.json.JsonValue) meth public abstract jakarta.json.JsonValue toJsonValue() CLSS public abstract interface jakarta.json.JsonNumber intf jakarta.json.JsonValue meth public abstract boolean equals(java.lang.Object) meth public abstract boolean isIntegral() meth public abstract double doubleValue() meth public abstract int hashCode() meth public abstract int intValue() meth public abstract int intValueExact() meth public abstract java.lang.String toString() meth public abstract java.math.BigDecimal bigDecimalValue() meth public abstract java.math.BigInteger bigIntegerValue() meth public abstract java.math.BigInteger bigIntegerValueExact() meth public abstract long longValue() meth public abstract long longValueExact() meth public java.lang.Number numberValue() CLSS public abstract interface jakarta.json.JsonObject intf jakarta.json.JsonStructure intf java.util.Map meth public abstract boolean getBoolean(java.lang.String) meth public abstract boolean getBoolean(java.lang.String,boolean) meth public abstract boolean isNull(java.lang.String) meth public abstract int getInt(java.lang.String) meth public abstract int getInt(java.lang.String,int) meth public abstract jakarta.json.JsonArray getJsonArray(java.lang.String) meth public abstract jakarta.json.JsonNumber getJsonNumber(java.lang.String) meth public abstract jakarta.json.JsonObject getJsonObject(java.lang.String) meth public abstract jakarta.json.JsonString getJsonString(java.lang.String) meth public abstract java.lang.String getString(java.lang.String) meth public abstract java.lang.String getString(java.lang.String,java.lang.String) CLSS public abstract interface jakarta.json.JsonObjectBuilder meth public abstract jakarta.json.JsonObject build() meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,boolean) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,double) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,int) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,jakarta.json.JsonArrayBuilder) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,jakarta.json.JsonObjectBuilder) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,jakarta.json.JsonValue) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,java.lang.String) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,java.math.BigDecimal) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,java.math.BigInteger) meth public abstract jakarta.json.JsonObjectBuilder add(java.lang.String,long) meth public abstract jakarta.json.JsonObjectBuilder addNull(java.lang.String) meth public jakarta.json.JsonObjectBuilder addAll(jakarta.json.JsonObjectBuilder) meth public jakarta.json.JsonObjectBuilder remove(java.lang.String) CLSS public abstract interface jakarta.json.JsonPatch innr public final static !enum Operation meth public abstract <%0 extends jakarta.json.JsonStructure> {%%0} apply({%%0}) meth public abstract jakarta.json.JsonArray toJsonArray() CLSS public final static !enum jakarta.json.JsonPatch$Operation outer jakarta.json.JsonPatch fld public final static jakarta.json.JsonPatch$Operation ADD fld public final static jakarta.json.JsonPatch$Operation COPY fld public final static jakarta.json.JsonPatch$Operation MOVE fld public final static jakarta.json.JsonPatch$Operation REMOVE fld public final static jakarta.json.JsonPatch$Operation REPLACE fld public final static jakarta.json.JsonPatch$Operation TEST meth public java.lang.String operationName() meth public static jakarta.json.JsonPatch$Operation fromOperationName(java.lang.String) meth public static jakarta.json.JsonPatch$Operation valueOf(java.lang.String) meth public static jakarta.json.JsonPatch$Operation[] values() supr java.lang.Enum hfds operationName CLSS public abstract interface jakarta.json.JsonPatchBuilder meth public abstract jakarta.json.JsonPatch build() meth public abstract jakarta.json.JsonPatchBuilder add(java.lang.String,boolean) meth public abstract jakarta.json.JsonPatchBuilder add(java.lang.String,int) meth public abstract jakarta.json.JsonPatchBuilder add(java.lang.String,jakarta.json.JsonValue) meth public abstract jakarta.json.JsonPatchBuilder add(java.lang.String,java.lang.String) meth public abstract jakarta.json.JsonPatchBuilder copy(java.lang.String,java.lang.String) meth public abstract jakarta.json.JsonPatchBuilder move(java.lang.String,java.lang.String) meth public abstract jakarta.json.JsonPatchBuilder remove(java.lang.String) meth public abstract jakarta.json.JsonPatchBuilder replace(java.lang.String,boolean) meth public abstract jakarta.json.JsonPatchBuilder replace(java.lang.String,int) meth public abstract jakarta.json.JsonPatchBuilder replace(java.lang.String,jakarta.json.JsonValue) meth public abstract jakarta.json.JsonPatchBuilder replace(java.lang.String,java.lang.String) meth public abstract jakarta.json.JsonPatchBuilder test(java.lang.String,boolean) meth public abstract jakarta.json.JsonPatchBuilder test(java.lang.String,int) meth public abstract jakarta.json.JsonPatchBuilder test(java.lang.String,jakarta.json.JsonValue) meth public abstract jakarta.json.JsonPatchBuilder test(java.lang.String,java.lang.String) CLSS public abstract interface jakarta.json.JsonPointer meth public abstract <%0 extends jakarta.json.JsonStructure> {%%0} add({%%0},jakarta.json.JsonValue) meth public abstract <%0 extends jakarta.json.JsonStructure> {%%0} remove({%%0}) meth public abstract <%0 extends jakarta.json.JsonStructure> {%%0} replace({%%0},jakarta.json.JsonValue) meth public abstract boolean containsValue(jakarta.json.JsonStructure) meth public abstract jakarta.json.JsonValue getValue(jakarta.json.JsonStructure) meth public abstract java.lang.String toString() CLSS public abstract interface jakarta.json.JsonReader intf java.io.Closeable meth public abstract jakarta.json.JsonArray readArray() meth public abstract jakarta.json.JsonObject readObject() meth public abstract jakarta.json.JsonStructure read() meth public abstract void close() meth public jakarta.json.JsonValue readValue() CLSS public abstract interface jakarta.json.JsonReaderFactory meth public abstract jakarta.json.JsonReader createReader(java.io.InputStream) meth public abstract jakarta.json.JsonReader createReader(java.io.InputStream,java.nio.charset.Charset) meth public abstract jakarta.json.JsonReader createReader(java.io.Reader) meth public abstract java.util.Map getConfigInUse() CLSS public abstract interface jakarta.json.JsonString intf jakarta.json.JsonValue meth public abstract boolean equals(java.lang.Object) meth public abstract int hashCode() meth public abstract java.lang.CharSequence getChars() meth public abstract java.lang.String getString() CLSS public abstract interface jakarta.json.JsonStructure intf jakarta.json.JsonValue meth public jakarta.json.JsonValue getValue(java.lang.String) CLSS public abstract interface jakarta.json.JsonValue fld public final static jakarta.json.JsonArray EMPTY_JSON_ARRAY fld public final static jakarta.json.JsonObject EMPTY_JSON_OBJECT fld public final static jakarta.json.JsonValue FALSE fld public final static jakarta.json.JsonValue NULL fld public final static jakarta.json.JsonValue TRUE innr public final static !enum ValueType meth public abstract jakarta.json.JsonValue$ValueType getValueType() meth public abstract java.lang.String toString() meth public jakarta.json.JsonArray asJsonArray() meth public jakarta.json.JsonObject asJsonObject() CLSS public final static !enum jakarta.json.JsonValue$ValueType outer jakarta.json.JsonValue fld public final static jakarta.json.JsonValue$ValueType ARRAY fld public final static jakarta.json.JsonValue$ValueType FALSE fld public final static jakarta.json.JsonValue$ValueType NULL fld public final static jakarta.json.JsonValue$ValueType NUMBER fld public final static jakarta.json.JsonValue$ValueType OBJECT fld public final static jakarta.json.JsonValue$ValueType STRING fld public final static jakarta.json.JsonValue$ValueType TRUE meth public static jakarta.json.JsonValue$ValueType valueOf(java.lang.String) meth public static jakarta.json.JsonValue$ValueType[] values() supr java.lang.Enum CLSS public abstract interface jakarta.json.JsonWriter intf java.io.Closeable meth public abstract void close() meth public abstract void write(jakarta.json.JsonStructure) meth public abstract void writeArray(jakarta.json.JsonArray) meth public abstract void writeObject(jakarta.json.JsonObject) meth public void write(jakarta.json.JsonValue) CLSS public abstract interface jakarta.json.JsonWriterFactory meth public abstract jakarta.json.JsonWriter createWriter(java.io.OutputStream) meth public abstract jakarta.json.JsonWriter createWriter(java.io.OutputStream,java.nio.charset.Charset) meth public abstract jakarta.json.JsonWriter createWriter(java.io.Writer) meth public abstract java.util.Map getConfigInUse() CLSS public abstract jakarta.json.spi.JsonProvider cons protected init() fld public final static java.lang.String JSONP_PROVIDER_FACTORY = "jakarta.json.provider" meth public abstract jakarta.json.JsonArrayBuilder createArrayBuilder() meth public abstract jakarta.json.JsonBuilderFactory createBuilderFactory(java.util.Map) meth public abstract jakarta.json.JsonObjectBuilder createObjectBuilder() meth public abstract jakarta.json.JsonReader createReader(java.io.InputStream) meth public abstract jakarta.json.JsonReader createReader(java.io.Reader) meth public abstract jakarta.json.JsonReaderFactory createReaderFactory(java.util.Map) meth public abstract jakarta.json.JsonWriter createWriter(java.io.OutputStream) meth public abstract jakarta.json.JsonWriter createWriter(java.io.Writer) meth public abstract jakarta.json.JsonWriterFactory createWriterFactory(java.util.Map) meth public abstract jakarta.json.stream.JsonGenerator createGenerator(java.io.OutputStream) meth public abstract jakarta.json.stream.JsonGenerator createGenerator(java.io.Writer) meth public abstract jakarta.json.stream.JsonGeneratorFactory createGeneratorFactory(java.util.Map) meth public abstract jakarta.json.stream.JsonParser createParser(java.io.InputStream) meth public abstract jakarta.json.stream.JsonParser createParser(java.io.Reader) meth public abstract jakarta.json.stream.JsonParserFactory createParserFactory(java.util.Map) meth public jakarta.json.JsonArrayBuilder createArrayBuilder(jakarta.json.JsonArray) meth public jakarta.json.JsonArrayBuilder createArrayBuilder(java.util.Collection) meth public jakarta.json.JsonMergePatch createMergeDiff(jakarta.json.JsonValue,jakarta.json.JsonValue) meth public jakarta.json.JsonMergePatch createMergePatch(jakarta.json.JsonValue) meth public jakarta.json.JsonNumber createValue(double) meth public jakarta.json.JsonNumber createValue(int) meth public jakarta.json.JsonNumber createValue(java.lang.Number) meth public jakarta.json.JsonNumber createValue(java.math.BigDecimal) meth public jakarta.json.JsonNumber createValue(java.math.BigInteger) meth public jakarta.json.JsonNumber createValue(long) meth public jakarta.json.JsonObjectBuilder createObjectBuilder(jakarta.json.JsonObject) meth public jakarta.json.JsonObjectBuilder createObjectBuilder(java.util.Map) meth public jakarta.json.JsonPatch createDiff(jakarta.json.JsonStructure,jakarta.json.JsonStructure) meth public jakarta.json.JsonPatch createPatch(jakarta.json.JsonArray) meth public jakarta.json.JsonPatchBuilder createPatchBuilder() meth public jakarta.json.JsonPatchBuilder createPatchBuilder(jakarta.json.JsonArray) meth public jakarta.json.JsonPointer createPointer(java.lang.String) meth public jakarta.json.JsonString createValue(java.lang.String) meth public static jakarta.json.spi.JsonProvider provider() supr java.lang.Object hfds DEFAULT_PROVIDER,OSGI_SERVICE_LOADER_CLASS_NAME hcls LazyFactoryLoader CLSS public final jakarta.json.stream.JsonCollectors meth public static <%0 extends jakarta.json.JsonArrayBuilder> java.util.stream.Collector,jakarta.json.JsonObject> groupingBy(java.util.function.Function,java.util.stream.Collector) meth public static java.util.stream.Collector toJsonArray() meth public static java.util.stream.Collector toJsonObject(java.util.function.Function,java.util.function.Function) meth public static java.util.stream.Collector,jakarta.json.JsonObject> groupingBy(java.util.function.Function) meth public static java.util.stream.Collector,jakarta.json.JsonObjectBuilder,jakarta.json.JsonObject> toJsonObject() supr java.lang.Object CLSS public jakarta.json.stream.JsonGenerationException cons public init(java.lang.String) cons public init(java.lang.String,java.lang.Throwable) supr jakarta.json.JsonException hfds serialVersionUID CLSS public abstract interface jakarta.json.stream.JsonGenerator fld public final static java.lang.String PRETTY_PRINTING = "jakarta.json.stream.JsonGenerator.prettyPrinting" intf java.io.Closeable intf java.io.Flushable meth public abstract jakarta.json.stream.JsonGenerator write(boolean) meth public abstract jakarta.json.stream.JsonGenerator write(double) meth public abstract jakarta.json.stream.JsonGenerator write(int) meth public abstract jakarta.json.stream.JsonGenerator write(jakarta.json.JsonValue) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,boolean) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,double) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,int) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,jakarta.json.JsonValue) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,java.lang.String) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,java.math.BigDecimal) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,java.math.BigInteger) meth public abstract jakarta.json.stream.JsonGenerator write(java.lang.String,long) meth public abstract jakarta.json.stream.JsonGenerator write(java.math.BigDecimal) meth public abstract jakarta.json.stream.JsonGenerator write(java.math.BigInteger) meth public abstract jakarta.json.stream.JsonGenerator write(long) meth public abstract jakarta.json.stream.JsonGenerator writeEnd() meth public abstract jakarta.json.stream.JsonGenerator writeKey(java.lang.String) meth public abstract jakarta.json.stream.JsonGenerator writeNull() meth public abstract jakarta.json.stream.JsonGenerator writeNull(java.lang.String) meth public abstract jakarta.json.stream.JsonGenerator writeStartArray() meth public abstract jakarta.json.stream.JsonGenerator writeStartArray(java.lang.String) meth public abstract jakarta.json.stream.JsonGenerator writeStartObject() meth public abstract jakarta.json.stream.JsonGenerator writeStartObject(java.lang.String) meth public abstract void close() meth public abstract void flush() CLSS public abstract interface jakarta.json.stream.JsonGeneratorFactory meth public abstract jakarta.json.stream.JsonGenerator createGenerator(java.io.OutputStream) meth public abstract jakarta.json.stream.JsonGenerator createGenerator(java.io.OutputStream,java.nio.charset.Charset) meth public abstract jakarta.json.stream.JsonGenerator createGenerator(java.io.Writer) meth public abstract java.util.Map getConfigInUse() CLSS public abstract interface jakarta.json.stream.JsonLocation meth public abstract long getColumnNumber() meth public abstract long getLineNumber() meth public abstract long getStreamOffset() CLSS public abstract interface jakarta.json.stream.JsonParser innr public final static !enum Event intf java.io.Closeable meth public abstract boolean hasNext() meth public abstract boolean isIntegralNumber() meth public abstract int getInt() meth public abstract jakarta.json.stream.JsonLocation getLocation() meth public abstract jakarta.json.stream.JsonParser$Event next() meth public abstract java.lang.String getString() meth public abstract java.math.BigDecimal getBigDecimal() meth public abstract long getLong() meth public abstract void close() meth public jakarta.json.JsonArray getArray() meth public jakarta.json.JsonObject getObject() meth public jakarta.json.JsonValue getValue() meth public jakarta.json.stream.JsonParser$Event currentEvent() meth public java.util.stream.Stream getArrayStream() meth public java.util.stream.Stream getValueStream() meth public java.util.stream.Stream> getObjectStream() meth public void skipArray() meth public void skipObject() CLSS public final static !enum jakarta.json.stream.JsonParser$Event outer jakarta.json.stream.JsonParser fld public final static jakarta.json.stream.JsonParser$Event END_ARRAY fld public final static jakarta.json.stream.JsonParser$Event END_OBJECT fld public final static jakarta.json.stream.JsonParser$Event KEY_NAME fld public final static jakarta.json.stream.JsonParser$Event START_ARRAY fld public final static jakarta.json.stream.JsonParser$Event START_OBJECT fld public final static jakarta.json.stream.JsonParser$Event VALUE_FALSE fld public final static jakarta.json.stream.JsonParser$Event VALUE_NULL fld public final static jakarta.json.stream.JsonParser$Event VALUE_NUMBER fld public final static jakarta.json.stream.JsonParser$Event VALUE_STRING fld public final static jakarta.json.stream.JsonParser$Event VALUE_TRUE meth public static jakarta.json.stream.JsonParser$Event valueOf(java.lang.String) meth public static jakarta.json.stream.JsonParser$Event[] values() supr java.lang.Enum CLSS public abstract interface jakarta.json.stream.JsonParserFactory meth public abstract jakarta.json.stream.JsonParser createParser(jakarta.json.JsonArray) meth public abstract jakarta.json.stream.JsonParser createParser(jakarta.json.JsonObject) meth public abstract jakarta.json.stream.JsonParser createParser(java.io.InputStream) meth public abstract jakarta.json.stream.JsonParser createParser(java.io.InputStream,java.nio.charset.Charset) meth public abstract jakarta.json.stream.JsonParser createParser(java.io.Reader) meth public abstract java.util.Map getConfigInUse() CLSS public jakarta.json.stream.JsonParsingException cons public init(java.lang.String,jakarta.json.stream.JsonLocation) cons public init(java.lang.String,java.lang.Throwable,jakarta.json.stream.JsonLocation) meth public jakarta.json.stream.JsonLocation getLocation() supr jakarta.json.JsonException hfds location,serialVersionUID CLSS public abstract interface java.io.Closeable intf java.lang.AutoCloseable meth public abstract void close() throws java.io.IOException CLSS public abstract interface java.io.Flushable meth public abstract void flush() throws java.io.IOException CLSS public abstract interface java.io.Serializable CLSS public abstract interface java.lang.AutoCloseable meth public abstract void close() throws java.lang.Exception CLSS public abstract interface java.lang.Comparable<%0 extends java.lang.Object> meth public abstract int compareTo({java.lang.Comparable%0}) CLSS public abstract java.lang.Enum<%0 extends java.lang.Enum<{java.lang.Enum%0}>> cons protected init(java.lang.String,int) intf java.io.Serializable intf java.lang.Comparable<{java.lang.Enum%0}> meth protected final java.lang.Object clone() throws java.lang.CloneNotSupportedException meth protected final void finalize() meth public final boolean equals(java.lang.Object) meth public final int compareTo({java.lang.Enum%0}) meth public final int hashCode() meth public final int ordinal() meth public final java.lang.Class<{java.lang.Enum%0}> getDeclaringClass() meth public final java.lang.String name() meth public java.lang.String toString() meth public static <%0 extends java.lang.Enum<{%%0}>> {%%0} valueOf(java.lang.Class<{%%0}>,java.lang.String) supr java.lang.Object CLSS public java.lang.Exception cons protected init(java.lang.String,java.lang.Throwable,boolean,boolean) cons public init() cons public init(java.lang.String) cons public init(java.lang.String,java.lang.Throwable) cons public init(java.lang.Throwable) supr java.lang.Throwable CLSS public abstract interface java.lang.Iterable<%0 extends java.lang.Object> meth public abstract java.util.Iterator<{java.lang.Iterable%0}> iterator() meth public java.util.Spliterator<{java.lang.Iterable%0}> spliterator() meth public void forEach(java.util.function.Consumer) CLSS public java.lang.Object cons public init() meth protected java.lang.Object clone() throws java.lang.CloneNotSupportedException meth protected void finalize() throws java.lang.Throwable anno 0 java.lang.Deprecated(boolean forRemoval=false, java.lang.String since="9") meth public boolean equals(java.lang.Object) meth public final java.lang.Class getClass() meth public final void notify() meth public final void notifyAll() meth public final void wait() throws java.lang.InterruptedException meth public final void wait(long) throws java.lang.InterruptedException meth public final void wait(long,int) throws java.lang.InterruptedException meth public int hashCode() meth public java.lang.String toString() CLSS public java.lang.RuntimeException cons protected init(java.lang.String,java.lang.Throwable,boolean,boolean) cons public init() cons public init(java.lang.String) cons public init(java.lang.String,java.lang.Throwable) cons public init(java.lang.Throwable) supr java.lang.Exception CLSS public java.lang.Throwable cons protected init(java.lang.String,java.lang.Throwable,boolean,boolean) cons public init() cons public init(java.lang.String) cons public init(java.lang.String,java.lang.Throwable) cons public init(java.lang.Throwable) intf java.io.Serializable meth public final java.lang.Throwable[] getSuppressed() meth public final void addSuppressed(java.lang.Throwable) meth public java.lang.StackTraceElement[] getStackTrace() meth public java.lang.String getLocalizedMessage() meth public java.lang.String getMessage() meth public java.lang.String toString() meth public java.lang.Throwable fillInStackTrace() meth public java.lang.Throwable getCause() meth public java.lang.Throwable initCause(java.lang.Throwable) meth public void printStackTrace() meth public void printStackTrace(java.io.PrintStream) meth public void printStackTrace(java.io.PrintWriter) meth public void setStackTrace(java.lang.StackTraceElement[]) supr java.lang.Object CLSS public abstract interface java.util.Collection<%0 extends java.lang.Object> intf java.lang.Iterable<{java.util.Collection%0}> meth public <%0 extends java.lang.Object> {%%0}[] toArray(java.util.function.IntFunction<{%%0}[]>) meth public abstract <%0 extends java.lang.Object> {%%0}[] toArray({%%0}[]) meth public abstract boolean add({java.util.Collection%0}) meth public abstract boolean addAll(java.util.Collection) meth public abstract boolean contains(java.lang.Object) meth public abstract boolean containsAll(java.util.Collection) meth public abstract boolean equals(java.lang.Object) meth public abstract boolean isEmpty() meth public abstract boolean remove(java.lang.Object) meth public abstract boolean removeAll(java.util.Collection) meth public abstract boolean retainAll(java.util.Collection) meth public abstract int hashCode() meth public abstract int size() meth public abstract java.lang.Object[] toArray() meth public abstract java.util.Iterator<{java.util.Collection%0}> iterator() meth public abstract void clear() meth public boolean removeIf(java.util.function.Predicate) meth public java.util.Spliterator<{java.util.Collection%0}> spliterator() meth public java.util.stream.Stream<{java.util.Collection%0}> parallelStream() meth public java.util.stream.Stream<{java.util.Collection%0}> stream() CLSS public abstract interface java.util.List<%0 extends java.lang.Object> intf java.util.Collection<{java.util.List%0}> meth public !varargs static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0}[]) anno 0 java.lang.SafeVarargs() meth public abstract <%0 extends java.lang.Object> {%%0}[] toArray({%%0}[]) meth public abstract boolean add({java.util.List%0}) meth public abstract boolean addAll(int,java.util.Collection) meth public abstract boolean addAll(java.util.Collection) meth public abstract boolean contains(java.lang.Object) meth public abstract boolean containsAll(java.util.Collection) meth public abstract boolean equals(java.lang.Object) meth public abstract boolean isEmpty() meth public abstract boolean remove(java.lang.Object) meth public abstract boolean removeAll(java.util.Collection) meth public abstract boolean retainAll(java.util.Collection) meth public abstract int hashCode() meth public abstract int indexOf(java.lang.Object) meth public abstract int lastIndexOf(java.lang.Object) meth public abstract int size() meth public abstract java.lang.Object[] toArray() meth public abstract java.util.Iterator<{java.util.List%0}> iterator() meth public abstract java.util.List<{java.util.List%0}> subList(int,int) meth public abstract java.util.ListIterator<{java.util.List%0}> listIterator() meth public abstract java.util.ListIterator<{java.util.List%0}> listIterator(int) meth public abstract void add(int,{java.util.List%0}) meth public abstract void clear() meth public abstract {java.util.List%0} get(int) meth public abstract {java.util.List%0} remove(int) meth public abstract {java.util.List%0} set(int,{java.util.List%0}) meth public java.util.Spliterator<{java.util.List%0}> spliterator() meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> copyOf(java.util.Collection) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of() meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0}) meth public static <%0 extends java.lang.Object> java.util.List<{%%0}> of({%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0},{%%0}) meth public void replaceAll(java.util.function.UnaryOperator<{java.util.List%0}>) meth public void sort(java.util.Comparator) CLSS public abstract interface java.util.Map<%0 extends java.lang.Object, %1 extends java.lang.Object> innr public abstract interface static Entry meth public !varargs static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> ofEntries(java.util.Map$Entry[]) anno 0 java.lang.SafeVarargs() meth public abstract boolean containsKey(java.lang.Object) meth public abstract boolean containsValue(java.lang.Object) meth public abstract boolean equals(java.lang.Object) meth public abstract boolean isEmpty() meth public abstract int hashCode() meth public abstract int size() meth public abstract java.util.Collection<{java.util.Map%1}> values() meth public abstract java.util.Set> entrySet() meth public abstract java.util.Set<{java.util.Map%0}> keySet() meth public abstract void clear() meth public abstract void putAll(java.util.Map) meth public abstract {java.util.Map%1} get(java.lang.Object) meth public abstract {java.util.Map%1} put({java.util.Map%0},{java.util.Map%1}) meth public abstract {java.util.Map%1} remove(java.lang.Object) meth public boolean remove(java.lang.Object,java.lang.Object) meth public boolean replace({java.util.Map%0},{java.util.Map%1},{java.util.Map%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map$Entry<{%%0},{%%1}> entry({%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> copyOf(java.util.Map) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of() meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public static <%0 extends java.lang.Object, %1 extends java.lang.Object> java.util.Map<{%%0},{%%1}> of({%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1},{%%0},{%%1}) meth public void forEach(java.util.function.BiConsumer) meth public void replaceAll(java.util.function.BiFunction) meth public {java.util.Map%1} compute({java.util.Map%0},java.util.function.BiFunction) meth public {java.util.Map%1} computeIfAbsent({java.util.Map%0},java.util.function.Function) meth public {java.util.Map%1} computeIfPresent({java.util.Map%0},java.util.function.BiFunction) meth public {java.util.Map%1} getOrDefault(java.lang.Object,{java.util.Map%1}) meth public {java.util.Map%1} merge({java.util.Map%0},{java.util.Map%1},java.util.function.BiFunction) meth public {java.util.Map%1} putIfAbsent({java.util.Map%0},{java.util.Map%1}) meth public {java.util.Map%1} replace({java.util.Map%0},{java.util.Map%1}) sig-test-pkg-list.txt000066400000000000000000000017371451447132700355340ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/tck/jsonp/signaturetest# # Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. # # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v. 2.0, which is available at # http://www.eclipse.org/legal/epl-2.0. # # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the # Eclipse Public License v. 2.0 are satisfied: GNU General Public License, # version 2 with the GNU Classpath Exception, which is available at # https://www.gnu.org/software/classpath/license.html. # # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 # # # $Id$ # ## # This file contains a list of all the packages # contained in the signature files for this # deliverable. This file is used to exclude valid # sub-packages from being verified when their # parent package's signature is checked. ## jakarta.json jakarta.json.spi jakarta.json.stream sig-test.map000066400000000000000000000040261451447132700337340ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/ee/jakarta/tck/jsonp/signaturetest# # Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved. # # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v. 2.0, which is available at # http://www.eclipse.org/legal/epl-2.0. # # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the # Eclipse Public License v. 2.0 are satisfied: GNU General Public License, # version 2 with the GNU Classpath Exception, which is available at # https://www.gnu.org/software/classpath/license.html. # # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 # # # $Id$ # ############################################################### # # IMPORTANT: this sig-test.map file for use with JDK 8 only! # Using this file with other version of JDK will yield errors. # # The signature test mapping file for the JSON-P 2.0.0 TCK. This file # should be formatted as a standard java properties file. The # name is the package name and the value is the version of the # package that should be tested by the signature tests. # # The resultant signature file name has a name that complies # with the following format: # .sig__ # Given this format, the following example breaks down as follows: # jakarta.json.sig_2.0.0_se8: # jakarta.json.sig_2.0.0_se11: # = jakarta.json # = 2.0.0 (for JSON-P) # = se8 and se11 # # For this release valid versions are: "_se8", "_se11", or "_se8_se11" # This sig-test.map file is designed to be run using JDK 8 so any # signature file that ends with "_se8" or "se8_se11" will be valid. # if a signature file contains only "_se8" and no reference to "_se11" # in the signature name, than that means that signature file MUST only # be referenced when using JDK 8. # ############################################################### jakarta.json=2.1.0 jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayUTF16BE.json000066400000000000000000000000321451447132700265250ustar00rootroot00000000000000["aeE,e\WRz"] jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayUTF8.json000066400000000000000000000000301451447132700262350ustar00rootroot00000000000000["a旨䔬讞斉屗列z"]jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfData.json000066400000000000000000000010721451447132700311660ustar00rootroot00000000000000[ "", [], {}, "string", 100, true, false, null, { "emptyString" : "", "emptyArray" : [], "emptyObject" : {}, "string" : "string", "number" : 100, "true" : true, "false" : false, "null" : null, "object" : { "name" : "value" }, "array" : [ "one", "two" ] }, [ "string", 100, true, false, null, { "name" : "value" }, [ "one", "two" ] ], 100, -100, 9223372036854775807, -9223372036854775808, 0.5, -0.5, 7e3, 7e+3, 9E3, 9E+3, 7e-3, 7E-3, "!@#$%^&*()_+|~1234567890-=;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" ] jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfDataUTF16BE.json000066400000000000000000000021641451447132700321260ustar00rootroot00000000000000[ "", [], {}, "string", 100, true, false, null, { "emptyString" : "", "emptyArray" : [], "emptyObject" : {}, "string" : "string", "number" : 100, "true" : true, "false" : false, "null" : null, "object" : { "name" : "value" }, "array" : [ "one", "two" ] }, [ "string", 100, true, false, null, { "name" : "value" }, [ "one", "two" ] ], 100, -100, 9223372036854775807, -9223372036854775808, 0.5, -0.5, 7e3, 7e+3, 9E3, 9E+3, 7e-3, 7E-3, "!@#$%^&*()_+|~1234567890-=;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" ] jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayWithEscapeCharsData.json000066400000000000000000000000431451447132700313220ustar00rootroot00000000000000[ "popeye\"\\\/\b\f\n\r\tolive" ] jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedArraysData.json000066400000000000000000000046111451447132700327010ustar00rootroot00000000000000[ [ "name1","value1", "nested2",[ "name2","value2", "nested3",[ "name3","value3", "nested4",[ "name4","value4", "nested5",[ "name5","value5", "nested6",[ "name6","value6", "nested7",[ "name7","value7", "nested8",[ "name8","value8", "nested9",[ "name9","value9", "nested10",[ "name10","value10", "nested11",[ "name11","value11", "nested12",[ "name12","value12", "nested13",[ "name13","value13", "nested14",[ "name14","value14", "nested15",[ "name15","value15", "nested16",[ "name16","value16", "nested17",[ "name17","value17", "nested18",[ "name18","value18", "nested19",[ "name19","value19", "nested20",[ "name20","value20", "nested21",[ "name21","value21", "nested22",[ "name22","value22", "nested23",[ "name23","value23", "nested24",[ "name24","value24", "nested25",[ "name25","value25", "nested26",[ "name26","value26", "nested27",[ "name27","value27", "nested28",[ "name28","value28", "nested29",[ "name29","value29", "nested30",[ "name30","value30" ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedObjectsData.json000066400000000000000000000047771451447132700330460ustar00rootroot00000000000000[ { "name1" : "value1", "nested2" : { "name2" : "value2", "nested3" : { "name3" : "value3", "nested4" : { "name4" : "value4", "nested5" : { "name5" : "value5", "nested6" : { "name6" : "value6", "nested7" : { "name7" : "value7", "nested8" : { "name8" : "value8", "nested9" : { "name9" : "value9", "nested10" : { "name10" : "value10", "nested11" : { "name11" : "value11", "nested12" : { "name12" : "value12", "nested13" : { "name13" : "value13", "nested14" : { "name14" : "value14", "nested15" : { "name15" : "value15", "nested16" : { "name16" : "value16", "nested17" : { "name17" : "value17", "nested18" : { "name18" : "value18", "nested19" : { "name19" : "value19", "nested20" : { "name20" : "value20", "nested21" : { "name21" : "value21", "nested22" : { "name22" : "value22", "nested23" : { "name23" : "value23", "nested24" : { "name24" : "value24", "nested25" : { "name25" : "value25", "nested26" : { "name26" : "value26", "nested27" : { "name27" : "value27", "nested28" : { "name28" : "value28", "nested29" : { "name29" : "value29", "nested30" : { "name30" : "value30" } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } ] jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonHelloWorld.json000066400000000000000000000001071451447132700265700ustar00rootroot00000000000000{ "greetingObj":{"hello":"world"}, "greetingArr":["hello","world"] } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16.json000066400000000000000000000002321451447132700301170ustar00rootroot00000000000000{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16BE.json000066400000000000000000000002301451447132700303240ustar00rootroot00000000000000{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16LE.json000066400000000000000000000002301451447132700303360ustar00rootroot00000000000000{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32BE.json000066400000000000000000000004601451447132700303270ustar00rootroot00000000000000{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32LE.json000066400000000000000000000004601451447132700303410ustar00rootroot00000000000000{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF8.json000066400000000000000000000001141451447132700300370ustar00rootroot00000000000000{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectUTF16LE.json000066400000000000000000000000701451447132700266710ustar00rootroot00000000000000{"unicodeChars":"ae,EeW\Rz"} jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectUTF8.json000066400000000000000000000000471451447132700263750ustar00rootroot00000000000000{"unicodeChars":"a旨䔬讞斉屗列z"}jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectUnknownEncoding.json000066400000000000000000000000011451447132700307430ustar00rootroot00000000000000jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfData.json000066400000000000000000000016071451447132700313220ustar00rootroot00000000000000{ "emptyString" : "", "emptyArray" : [], "emptyObject" : {}, "string" : "string", "number" : 100, "true" : true, "false" : false, "null" : null, "object" : { "emptyString" : "", "emptyArray" : [], "emptyObject" : {}, "string" : "string", "number" : 100, "true" : true, "false" : false, "null" : null, "object" : { "name" : "value" }, "array" : [ "one", "two" ] }, "array" : [ "string", 100, true, false, null, { "name" : "value" }, [ "one", "two" ] ], "intPositive" : 100, "intNegative" : -100, "longMax" : 9223372036854775807, "longMin" : -9223372036854775808, "fracPositive" : 0.5, "fracNegative" : -0.5, "expPositive1" : 7e3, "expPositive2" : 7e+3, "expPositive3" : 9E3, "expPositive4" : 9E+3, "expNegative1" : 7e-3, "expNegative2" : 7E-3, "asciiChars" : "!@#$%^&*()_+|~1234567890-=;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfDataUTF16LE.json000066400000000000000000000034161451447132700322710ustar00rootroot00000000000000{ "emptyString" : "", "emptyArray" : [], "emptyObject" : {}, "string" : "string", "number" : 100, "true" : true, "false" : false, "null" : null, "object" : { "emptyString" : "", "emptyArray" : [], "emptyObject" : {}, "string" : "string", "number" : 100, "true" : true, "false" : false, "null" : null, "object" : { "name" : "value" }, "array" : [ "one", "two" ] }, "array" : [ "string", 100, true, false, null, { "name" : "value" }, [ "one", "two" ] ], "intPositive" : 100, "intNegative" : -100, "longMax" : 9223372036854775807, "longMin" : -9223372036854775808, "fracPositive" : 0.5, "fracNegative" : -0.5, "expPositive1" : 7e3, "expPositive2" : 7e+3, "expPositive3" : 9E3, "expPositive4" : 9E+3, "expNegative1" : 7e-3, "expNegative2" : 7E-3, "asciiChars" : "!@#$%^&*()_+|~1234567890-=;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectWithEscapeCharsData.json000066400000000000000000000000631451447132700314540ustar00rootroot00000000000000{ "escapeChars" : "popeye\"\\\/\b\f\n\r\tolive" } jsonp-api-2.1.3-RELEASE/tck/tck-tests/src/main/resources/jsonObjectWithLotsOfNestedObjectsData.json000066400000000000000000000050131451447132700331560ustar00rootroot00000000000000{ "nested1" : { "name1" : "value1", "nested2" : { "name2" : "value2", "nested3" : { "name3" : "value3", "nested4" : { "name4" : "value4", "nested5" : { "name5" : "value5", "nested6" : { "name6" : "value6", "nested7" : { "name7" : "value7", "nested8" : { "name8" : "value8", "nested9" : { "name9" : "value9", "nested10" : { "name10" : "value10", "nested11" : { "name11" : "value11", "nested12" : { "name12" : "value12", "nested13" : { "name13" : "value13", "nested14" : { "name14" : "value14", "nested15" : { "name15" : "value15", "nested16" : { "name16" : "value16", "nested17" : { "name17" : "value17", "nested18" : { "name18" : "value18", "nested19" : { "name19" : "value19", "nested20" : { "name20" : "value20", "nested21" : { "name21" : "value21", "nested22" : { "name22" : "value22", "nested23" : { "name23" : "value23", "nested24" : { "name24" : "value24", "nested25" : { "name25" : "value25", "nested26" : { "name26" : "value26", "nested27" : { "name27" : "value27", "nested28" : { "name28" : "value28", "nested29" : { "name29" : "value29", "nested30" : { "name30" : "value30" } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } }