pax_global_header00006660000000000000000000000064147527412330014522gustar00rootroot0000000000000052 comment=69711919796ae97d0e36e23d9d4c2631f215c5fc jtreg7-7.5.1+1+ds1/000077500000000000000000000000001475274123300135555ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/.gitignore000066400000000000000000000000531475274123300155430ustar00rootroot00000000000000/build/ /.idea/ /webrev .DS_Store .src-rev jtreg7-7.5.1+1+ds1/.hgignore000066400000000000000000000001131475274123300153530ustar00rootroot00000000000000^(build|dist)/ nbproject/private/ plugins/idea/.idea/ plugins/idea/build/ jtreg7-7.5.1+1+ds1/.hgtags000066400000000000000000000034571475274123300150440ustar00rootroot000000000000009f51ef22f00a3d5b681472cacf3ce15868073103 jtreg4.1-b01 2cf779985e18ba2f79aaec88f543be9efecf352f jtreg4.1-b02 bd7a3ed1210fa61f92f066c65d5e589e2aa26813 jtreg4.1-b03 cbc1f04a52ea2488e8dc7715fc59a5a122be9851 jtreg4.1-b04 46b8c02be3b356c7f953dbfa18246b357b5e7101 jtreg4.1-b05 d47a6e238c3e0f6d8ca1a6640c182be14c45eab2 jtreg-4.1-b06 d47a6e238c3e0f6d8ca1a6640c182be14c45eab2 jtreg4.1-b06 8ab579624a503e1df21841070ae5f869c301de8f jtreg4.1-b07 d47a6e238c3e0f6d8ca1a6640c182be14c45eab2 jtreg-4.1-b06 0000000000000000000000000000000000000000 jtreg-4.1-b06 e08a5e0b79ba57743222bbea19c0bdb142968769 jtreg4.1-b08 c54815dea64cf7b011f8473c18d54a86b9a9d5af jtreg4.1-b09 8c3179c3ebdab7df35b8e9907bd8ad8bc5a9f9f8 jtreg4.1-b10 04f40c388713f11c1cfb2094556d4b024b9ab939 jtreg4.1-b11 79705dae19e74b0693cda9ece8eaf0984159ab97 jtreg4.1-b12 5e994d1f9840ba39b82977a56e02c4f702a1dcbd jtreg4.1-b13 1159c9f96a4470dec79e6fa71b4f1a4895c4b20f jtreg4.2-b01 dbccea90c34dacf7e0824d5e3d3e9e1e930a103a jtreg4.2-b02 45590e2d6af12da44cc160764a9b552516be8440 jtreg4.2-b03 585f794e105997ab44109d70dbaa1c072b03afcc jtreg4.2-b04 4b0cd55e7741825de6ea79e9d4338d2972460678 jtreg4.2-b05 2d96b4cf02660b1580542379d77492f68d3ca73b jtreg4.2-b06 26d8a4a47674c4ca304b9e290dccca1dd1c7224f jtreg4.2-b07 cce0ac75e87864ed365a420fb836a4430421ab0f jtreg4.2-b08 684f12eef4a8c2f42afe2abe3d79eead72efcc5f jtreg4.2-b09 746c6d1328721541d3b16154c25a0179fbf53f7c jtreg4.2-b10 a13ec77e7adcc4c9ed434e664abc350abaacc045 jtreg4.2-b11 652902f7fb0ed0b4f307d61a799caf50a6e609be jtreg4.2-b12 7a38f21e077821a5015792e85b3793c90c81b866 jtreg4.2-b13 ec37d2900cd42987270f98423a60eb6297bdc37b jtreg4.2-b14 d5a9216fad5ca01002e18526be2c31cafb43e178 jtreg4.2-b15 deee95d5d8ff6406b77c0d5b9297736eb7c98c6d jtreg4.2-b16 03c4dff80b0f55865c6e5fe0aa8ea94d0ca1a2ac jtreg5.0-b01 95aa601b8100c6c56a14d35cfe493372214b1d94 jtreg5.1-b01 jtreg7-7.5.1+1+ds1/.jcheck/000077500000000000000000000000001475274123300150625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/.jcheck/conf000066400000000000000000000010671475274123300157360ustar00rootroot00000000000000[general] project=code-tools comments=lax jbs=CODETOOLS [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,whitespace [repository] tags=jtreg(?:4\.1-b[0-9]{2}|5\.[01]-b[0-9]{2}|6|-[6789](?:\.[0-9]+)*\+[0-9]+) branches= [census] version=0 domain=openjdk.org [checks "whitespace"] files=.*\.java|.*\.m|.*\.mm|.*\.gmk|.*\.m4|.*\.ac|Makefile ignore-tabs=.*\.gmk|Makefile [checks "merge"] message=Merge [checks "reviewers"] reviewers=1 ignore=duke [checks "committer"] role=committer [checks "issues"] pattern=^(79[0-9]{5}): (\S.*)$ jtreg7-7.5.1+1+ds1/CHANGELOG.md000066400000000000000000000307011475274123300153670ustar00rootroot00000000000000## [Unreleased](https://git.openjdk.org/jtreg/compare/jtreg-7.5.1+1...master) _nothing noteworthy, yet_ ## [7.5.1](https://git.openjdk.org/jtreg/compare/jtreg-7.5+1...jtreg-7.5.1+1) * Support running individual parameterized tests and @Nested test classes [CODETOOLS-7903930](https://bugs.openjdk.org/browse/CODETOOLS-7903930) * Remove problematic implementation for `LIBRARY.properties` support [CODETOOLS-7903940](https://bugs.openjdk.org/browse/CODETOOLS-7903940) * Add `test.thread.factory` property to filter tests based on test thread factory value [CODETOOLS-7903931](https://bugs.openjdk.org/browse/CODETOOLS-7903931) * Fix and improve `--verify-exclude` feature [CODETOOLS-7903883](https://bugs.openjdk.org/browse/CODETOOLS-7903883) [CODETOOLS-7903935](https://bugs.openjdk.org/browse/CODETOOLS-7903935) ## [7.5](https://git.openjdk.org/jtreg/compare/jtreg-7.4+1...jtreg-7.5+1) * Restore `jtdiff` tool [CODETOOLS-7903760](https://bugs.openjdk.org/browse/CODETOOLS-7903760) * Add support for `LIBRARY.properties` file in the directory specified in the `@library` tag [CODETOOLS-7903775](https://bugs.openjdk.org/browse/CODETOOLS-7903775) * The verbose option given at the command-line is now propagated to test agents, including the JUnit test runner. [CODETOOLS-7903443](https://bugs.openjdk.org/browse/CODETOOLS-7903443) [CODETOOLS-7903745](https://bugs.openjdk.org/browse/CODETOOLS-7903745) * Report test duration information in JUnit and TestNG-based tests [CODETOOLS-7903752](https://bugs.openjdk.org/browse/CODETOOLS-7903752) [CODETOOLS-7903753](https://bugs.openjdk.org/browse/CODETOOLS-7903753) * Improve message when test times out in Agent VM mode [CODETOOLS-7902346](https://bugs.openjdk.org/browse/CODETOOLS-7902346) * Log time spent waiting to acquire exclusive access lock [CODETOOLS-7903188](https://bugs.openjdk.org/browse/CODETOOLS-7903188) * Speed-up error reporting on hosts with slow hostname lookups [CODETOOLS-7903746](https://bugs.openjdk.org/browse/CODETOOLS-7903746) * Updated jtreg to bundle JUnit 5.11.0 [CODETOOLS-7903821](https://bugs.openjdk.org/browse/CODETOOLS-7903821) ## [7.4](https://git.openjdk.org/jtreg/compare/jtreg-7.3.1+1...jtreg-7.4+1) * Remove support for `jtdiff` [CODETOOLS-7903622](https://bugs.openjdk.org/browse/CODETOOLS-7903622) * jtreg now verifies ProblemList files [CODETOOLS-7903659](https://bugs.openjdk.org/browse/CODETOOLS-7903659) * jtreg no longer ignores VM exit code when test process reports status with "STATUS: " line [CODETOOLS-7903621](https://bugs.openjdk.org/browse/CODETOOLS-7903621) * Use SOURCE_BUILD_EPOCH to support reproducible builds [CODETOOLS-7903539](https://bugs.openjdk.org/browse/CODETOOLS-7903539) * Updated jtreg to bundle JUnit 5.10.2 [CODETOOLS-7903578](https://bugs.openjdk.org/browse/CODETOOLS-7903578) * jtreg, when communicating with the AgentServer in agentvm mode, will now bind to loopback address. [CODETOOLS-7903686](https://bugs.openjdk.org/browse/CODETOOLS-7903686) * jtreg, in certain cases, would incorrectly report a test as PASSED when the test process would exit with a non-zero exit code. [CODETOOLS-7903621](https://bugs.openjdk.org/browse/CODETOOLS-7903621) ## [7.3.1](https://git.openjdk.org/jtreg/compare/jtreg-7.3+1...jtreg-7.3.1+1) * Fixed setting default environment variables on Windows * [CODETOOLS-7903515](https://bugs.openjdk.org/browse/CODETOOLS-7903515) ## [7.3](https://git.openjdk.org/jtreg/compare/jtreg-7.2+1...jtreg-7.3+1) * Updated set of default environment variables set for tests on Unix-like platforms. * Includes `DBUS_SESSION_BUS_ADDRESS`, `WAYLAND_DISPLAY`, and `XDG-*` [CODETOOLS-7903400](https://bugs.openjdk.org/browse/CODETOOLS-7903400) * Updated external dependencies. * Guice to 5.1.0 [CODETOOLS-7903468](https://bugs.openjdk.org/browse/CODETOOLS-7903468) * JCommander to 1.82 [CODETOOLS-7903469](https://bugs.openjdk.org/browse/CODETOOLS-7903469) * Fixed output-related issues. * AgentServer log() does not flush [CODETOOLS-7903470](https://bugs.openjdk.org/browse/CODETOOLS-7903470) * System.out and System.err messages are missing in jtr file when a test times out in agentvm mode [CODETOOLS-7903441](https://bugs.openjdk.org/browse/CODETOOLS-7903441) * Timeout refired %s times message confusing [CODETOOLS-7902485](https://bugs.openjdk.org/browse/CODETOOLS-7902485) * Fixed race-condition when running tests with a multi-module setup * [CODETOOLS-7903507](https://bugs.openjdk.org/browse/CODETOOLS-7903507) ## [7.2](https://git.openjdk.org/jtreg/compare/jtreg-7.1.1+1...jtreg-7.2+1) * Improved support for JUnit Jupiter. * Update jtreg to bundle JUnit 5.9.2 [CODETOOLS-7903406](https://bugs.openjdk.org/browse/CODETOOLS-7903406) * Improve reporting for errors in JUnit's lifecycle methods [CODETOOLS-7903430](https://bugs.openjdk.org/browse/CODETOOLS-7903430) * Improved support for TestNG. * Support `test.query` for TestNG tests [CODETOOLS-7903414](https://bugs.openjdk.org/browse/CODETOOLS-7903414) * Generate all debugging info when compiling `jtreg` [CODETOOLS-7903393](https://bugs.openjdk.org/browse/CODETOOLS-7903393) * RISC-V Port has been integrated into JDK mainline * Set `simpleArch` to `riscv64` when `os.arch` is `riscv64` [CODETOOLS-7903138](https://bugs.openjdk.org/browse/CODETOOLS-7903138) * Fix incorrect format for version in error message [CODETOOLS-7903398](https://bugs.openjdk.org/browse/CODETOOLS-7903398) * Add options -testThreadFactory and -testThreadFactoryPath to allow the use of a custom thread factory, to be used to create the thread to run a test. * [CODETOOLS-7903373](https://bugs.openjdk.org/browse/CODETOOLS-79033734) ## [7.1.1](https://git.openjdk.org/jtreg/compare/jtreg-7.1+1...jtreg-7.1.1+1) * Summary reporter getter is now thread-safe. * [CODETOOLS-7903390](https://bugs.openjdk.org/browse/CODETOOLS-7903390) ## [7.1](https://git.openjdk.org/jtreg/compare/jtreg-7+1...jtreg-7.1+1) * Improved support for JUnit Jupiter. * Avoid using TestNG mixed mode. [CODETOOLS-7903264](https://bugs.openjdk.org/browse/CODETOOLS-7903264) * Support JUnit tests in a system module. [CODETOOLS-7903260](https://bugs.openjdk.org/browse/CODETOOLS-7903260) * Support executing a single method. [CODETOOLS-7903267](https://bugs.openjdk.org/browse/CODETOOLS-7903267) * Improve per-class reporting of JUnit tests, in `.jtr` file. [CODETOOLS-7903324](https://bugs.openjdk.org/browse/CODETOOLS-7903324) * Support a group of "all tests", represented by `.`. * [CODETOOLS-7903331](https://bugs.openjdk.org/browse/CODETOOLS-7903331) * Improve performance when writing reports; new reporting option `-report:files`. * [CODETOOLS-7903323](https://bugs.openjdk.org/browse/CODETOOLS-7903323) * Updates for building jtreg with recent JDKs. * [CODETOOLS-7903346](https://bugs.openjdk.org/browse/CODETOOLS-7903346) * Improve OS detection on Mac. * Use `sw_vers`. [CODETOOLS-7903294](https://bugs.openjdk.org/browse/CODETOOLS-7903294) * Check process exit code. [CODETOOLS-7903325](https://bugs.openjdk.org/browse/CODETOOLS-7903325) * Trace reasons to recompile extra property definition files. * [CODETOOLS-7903329](https://bugs.openjdk.org/browse/CODETOOLS-7903329) * FAQ updates. * Time taken to run tests. [CODETOOLS-7903261](https://bugs.openjdk.org/browse/CODETOOLS-7903261) * Accessing TestNG and JUnit libraries. [CODETOOLS-7903244](https://bugs.openjdk.org/browse/CODETOOLS-7903244) ## [7](https://git.openjdk.org/jtreg/compare/jtreg-6.2+1...jtreg-7+1) * Improved support for JUnit Jupiter. * Use JUnit Platform Launcher. [CODETOOLS-7903047](https://bugs.openjdk.org/browse/CODETOOLS-7903047) * Use JUnit uber-jar. [CODETOOLS-7903055](https://bugs.openjdk.org/browse/CODETOOLS-7903055) * Support MSYS2 for building jtreg on Windows. * [CODETOOLS-7903206](https://bugs.openjdk.org/browse/CODETOOLS-7903206) * `os.simpleArch` is `x64` for `linux-loongarch64`/`mips64`/`mips64el` in `@require` context. * [CODETOOLS-7903120](https://bugs.openjdk.org/browse/CODETOOLS-7903120) * Log start time for every action. * [CODETOOLS-7903183](https://bugs.openjdk.org/browse/CODETOOLS-7903183) * Update OS version check. * [CODETOOLS-7903184](https://bugs.openjdk.org/browse/CODETOOLS-7903184) * Support invocation via ToolProvider. * [CODETOOLS-7903097](https://bugs.openjdk.org/browse/CODETOOLS-7903097) * Report `os.*` system properties in `.jtr` file. * [CODETOOLS-7903044](https://bugs.openjdk.org/browse/CODETOOLS-7903044) ## [6.2](https://git.openjdk.org/jtreg/compare/jtreg-6.1+1...jtreg-6.2+1) * Provide system property or option to override timeout. * [CODETOOLS-7903083](https://bugs.openjdk.org/browse/CODETOOLS-7903083) * Updates for building jtreg with recent JDKs. * [CODETOOLS-7903073](https://bugs.openjdk.org/browse/CODETOOLS-7903073) * Add an FAQ entry for `javatest.maxOutputSize`. * [CODETOOLS-7903050](https://bugs.openjdk.org/browse/CODETOOLS-7903050) * Allow subtest ids with dashes and underscores. * [CODETOOLS-7903037](https://bugs.openjdk.org/browse/CODETOOLS-7903037) * jtreg should print stdout if JVM gathering properties fails. * [CODETOOLS-7903030](https://bugs.openjdk.org/browse/CODETOOLS-7903030) ## [6.1](https://git.openjdk.org/jtreg/compare/jtreg-6+1...jtreg-6.1+1) * Elapsed time of `MainAction` is including serialization wait time * [CODETOOLS-7902942](https://bugs.openjdk.org/browse/CODETOOLS-7902942) * Support building jtreg with recent JDKs. * [CODETOOLS-7902966](https://bugs.openjdk.org/browse/CODETOOLS-7902966) * [CODETOOLS-7902991](https://bugs.openjdk.org/browse/CODETOOLS-7902991) * Update/improve jcheck settings for jtreg repo. * [CODETOOLS-7902995](https://bugs.openjdk.org/browse/CODETOOLS-7902995) * Introduce support for `HEADLESS` to disable tests that require a display. * jtreg should not set a security manager for JDK 18. * [CODETOOLS-7902990](https://bugs.openjdk.org/browse/CODETOOLS-7902990) ## [6](https://git.openjdk.org/jtreg/compare/jtreg5.1-b01...jtreg-6+1) * Add support for `Automatic-Module-Name` in jar files. * Update versions of jtreg dependencies. * [CODETOOLS-7902791](https://bugs.openjdk.org/browse/CODETOOLS-7902791) * User modules can be used only in othervm. * [CODETOOLS-7902707](https://bugs.openjdk.org/browse/CODETOOLS-7902707) * Improve diagnostic output when failing to get version for JDK under test. * [CODETOOLS-7902748](https://bugs.openjdk.org/browse/CODETOOLS-7902748) * Initial support for new-style version numbers for jtreg. * Improve support for `@enablePreview`. * [CODETOOLS-7902754](https://bugs.openjdk.org/browse/CODETOOLS-7902754) * Move details of environment variables to new appendix. * Add FAQ reference to `doc/testing.md`. * Add support for explicit `-retain:lastRun`. ## [5.1](https://git.openjdk.org/jtreg/compare/jtreg5.0-b01...jtreg5.1-b01) * Update AsmTools to 7.0 b08; update JT Harness to 6.0-b11. * Add `test.name` to properties given to test. * [CODETOOLS-7902671](https://bugs.openjdk.org/browse/CODETOOLS-7902671) * Pass `test.*` to `requires.extraPropDefns` classes. * [CODETOOLS-7902336](https://bugs.openjdk.org/browse/CODETOOLS-7902336) * Add mean, standard deviation to agent stats. * Report jtreg version info to work directory. * Report agent pool statistics. * Improve version details for JT Harness and AsmTools. * Log Agent Pool activity to `agent.trace` file. * Catch output written to agent stdout (fd1) and stderr (fd2). * [CODETOOLS-7902657](https://bugs.openjdk.org/browse/CODETOOLS-7902657) * Log agent activity to files in the work directory. * [CODETOOLS-7902656](https://bugs.openjdk.org/browse/CODETOOLS-7902656) * Propagate client-side "id" to agent server. * [CODETOOLS-7902655](https://bugs.openjdk.org/browse/CODETOOLS-7902655) * Support `@enablePreview`. * [CODETOOLS-7902654](https://bugs.openjdk.org/browse/CODETOOLS-7902654) * Use https://git.openjdk.org for CODE_TOOLS_URL. * [CODETOOLS-7902637](https://bugs.openjdk.org/browse/CODETOOLS-7902637) * Ignore specified lines in `@compile/fail/ref=`. * [CODETOOLS-7902633](https://bugs.openjdk.org/browse/CODETOOLS-7902633) * Validate test group names. * [CODETOOLS-7902606](https://bugs.openjdk.org/browse/CODETOOLS-7902606) ## [5](https://git.openjdk.org/jtreg/compare/jtreg4.2-b16...jtreg5.0-b01) * Improve Cygwin detection by relaxing constraints on expected installation directory. * Incorrect handling of paths in smart action args for Windows. * [CODETOOLS-7902571](https://bugs.openjdk.org/browse/CODETOOLS-7902571) * Introduce `test.file`. * [CODETOOLS-7902545](https://bugs.openjdk.org/browse/CODETOOLS-7902545) jtreg7-7.5.1+1+ds1/CONTRIBUTING.md000066400000000000000000000003071475274123300160060ustar00rootroot00000000000000# Contributing to JTReg JTReg is part of the OpenJDK [CodeTools] Project. Please see for how to contribute. [CodeTools]: https://openjdk.org/projects/code-tools jtreg7-7.5.1+1+ds1/CONTRIBUTORS000066400000000000000000000010721475274123300154350ustar00rootroot00000000000000The following people have contributed to the development of jtreg. Original Author: Iris Clark Tag Specification: Mark Reinhold Currently Maintained As Part Of: OpenJDK CodeTools Project Other Early Contributors: Brian Kurotsuchi Dawn Phillips Jessica Mauvais John Rose Maurizio Cimadamore Kumar Srinivasan Since open-sourcing the code in 2006, and the use of first Mercurial and subsequently Git, the Contributors are tracked in the SCM metadata. For all recent contributors and contributions, see `git shortlog` or `git log`. jtreg7-7.5.1+1+ds1/COPYRIGHT000066400000000000000000000017421475274123300150540ustar00rootroot00000000000000Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 only, as published by the Free Software Foundation. This code 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 version 2 for more details (a copy is included in the LICENSE file that accompanied this code). You should have received a copy of the GNU General Public License version 2 along with this work; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or visit www.oracle.com if you need additional information or have any questions. jtreg7-7.5.1+1+ds1/LICENSE000066400000000000000000000455121475274123300145710ustar00rootroot00000000000000The 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-1301 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-1301 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 TO THE GPL Certain source files distributed by Oracle America and/or its affiliates are subject to the following clarification and special exception to the GPL, but only where Oracle has expressly included in the particular source file's header the words "Oracle designates this particular file as subject to the "Classpath" exception as provided by Oracle in the LICENSE file that accompanied this code." 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 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. jtreg7-7.5.1+1+ds1/README.md000066400000000000000000000017541475274123300150430ustar00rootroot00000000000000# The Regression Test Harness for the OpenJDK platform: `jtreg` * For details on writing tests for `jtreg`, see [The JDK Test Framework: Tag Language Specification][tagspec]. * For details on building `jtreg`, see [doc/building.md](doc/building.md). * For additional details about `jtreg`, see [The `jtreg` FAQ][faq]. * For details on running JDK tests using the JDK _make test_ framework, see [Using "make test" (the run-test framework)][make-test]. [faq]: https://openjdk.org/jtreg/faq.html [tagspec]: https://openjdk.org/jtreg/tag-spec.html [make-test]: https://github.com/openjdk/jdk/blob/master/doc/testing.md ## Using IntelliJ IDEA The `jtreg` repo also contains a plugin for the IntelliJ IDEA IDE. This is a convenience plugin which adds `jtreg` capabilities to the IDE. With this plugin, OpenJDK developers can write, run, and debug `jtreg` tests without leaving their IDE environment. For more details, see the file [plugins/idea/README.md](plugins/idea/README.md) in this repo. jtreg7-7.5.1+1+ds1/apiguardian/000077500000000000000000000000001475274123300160415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/.github/000077500000000000000000000000001475274123300174015ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/.github/workflows/000077500000000000000000000000001475274123300214365ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/.github/workflows/main.yml000066400000000000000000000031131475274123300231030ustar00rootroot00000000000000name: CI on: push: branches: - main - 'releases/*' pull_request: branches: - '*' jobs: gradle: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: java-version: 11 - uses: eskatos/gradle-command-action@v1 with: arguments: --stacktrace build publish_artifacts: name: Publish Snapshot Artifacts needs: gradle runs-on: ubuntu-latest if: github.event_name == 'push' && github.repository == 'apiguardian-team/apiguardian' && (startsWith(github.ref, 'refs/heads/releases/') || github.ref == 'refs/heads/main') steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: java-version: 11 - name: 'Publish' env: ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }} ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }} run: ./gradlew publish -x check update_documentation: name: Update Snapshot Documentation needs: gradle runs-on: ubuntu-latest if: github.event_name == 'push' && github.repository == 'apiguardian-team/apiguardian' && github.ref == 'refs/heads/main' steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: java-version: 11 - name: 'Upload Documentation' env: GRGIT_USER: ${{ secrets.GH_TOKEN }} run: ./gradlew gitPublishPush -x check jtreg7-7.5.1+1+ds1/apiguardian/.gitignore000066400000000000000000000002571475274123300200350ustar00rootroot00000000000000# Gradle .gradle build/ # Ignore Gradle GUI config gradle-app.setting # Eclipse .classpath .settings/ .project bin/ # IntelliJ *.iml *.ipr *.iws *.uml .idea/ # Misc *.log jtreg7-7.5.1+1+ds1/apiguardian/LICENSE000066400000000000000000000261351475274123300170550ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. jtreg7-7.5.1+1+ds1/apiguardian/README.md000066400000000000000000000015461475274123300173260ustar00rootroot00000000000000# @API Guardian [![CI Status](https://github.com/apiguardian-team/apiguardian/workflows/CI/badge.svg)](https://github.com/apiguardian-team/apiguardian/actions) Library that provides the `@API` annotation that is used to annotate public types, methods, constructors, and fields within a framework or application in order to publish their status and level of stability and to indicate how they are intended to be used by consumers of the API. ## How to use it The @API Guardian library is deployed to Maven Central. You can simply add it as a dependency: ### Apache Maven ```xml org.apiguardian apiguardian-api 1.1.2 ``` ### Gradle ```gradle repositories { mavenCentral() } dependencies { compileOnlyApi("org.apiguardian:apiguardian-api:1.1.2") } ``` jtreg7-7.5.1+1+ds1/apiguardian/build.gradle.kts000066400000000000000000000133451475274123300211260ustar00rootroot00000000000000import java.time.OffsetDateTime import java.time.format.DateTimeFormatter plugins { id("java") id("eclipse") id("idea") id("maven-publish") id("signing") id("biz.aQute.bnd.builder") version "5.3.0" id("net.nemerosa.versioning") version "2.14.0" id("org.ajoberstar.git-publish") version "3.0.0" id("io.github.gradle-nexus.publish-plugin") version "1.1.0" } val buildTimeAndDate = OffsetDateTime.now() val buildDate = DateTimeFormatter.ISO_LOCAL_DATE.format(buildTimeAndDate) val buildTime = DateTimeFormatter.ofPattern("HH:mm:ss.SSSZ").format(buildTimeAndDate) val builtByValue = project.findProperty("builtBy") ?: project.property("defaultBuiltBy") val isSnapshot = project.version.toString().contains("SNAPSHOT") val docsVersion = if (isSnapshot) "snapshot" else project.version val docsDir = File(buildDir, "ghpages-docs") val replaceCurrentDocs = project.hasProperty("replaceCurrentDocs") description = "@API Guardian" val moduleName = "org.apiguardian.api" repositories { mavenCentral() } java { withJavadocJar() withSourcesJar() } val moduleSourceDir = file("src/module/java") tasks { compileJava { options.release.set(6) } val compileModule by registering(JavaCompile::class) { source(moduleSourceDir) destinationDir = file("$buildDir/classes/java/modules") classpath = files(compileJava.map { it.classpath }) inputs.property("moduleName", moduleName) inputs.property("moduleVersion", project.version) options.release.set(9) options.compilerArgs = listOf( "--module-version", project.version as String, "--module-source-path", moduleSourceDir.toString(), "--patch-module", "$moduleName=${sourceSets.main.get().allJava.srcDirs.joinToString(":")}", "--module", moduleName ) } jar { fun normalizeVersion(versionLiteral: String): String { val regex = Regex("(\\d+\\.\\d+\\.\\d+).*") val match = regex.matchEntire(versionLiteral) require(match != null) { "Version '$versionLiteral' does not match version pattern, e.g. 1.0.0-QUALIFIER" } return match.groupValues[1] } manifest { attributes( "Created-By" to "${System.getProperty("java.version")} (${System.getProperty("java.vendor")} ${System.getProperty("java.vm.version")})", "Built-By" to builtByValue, "Build-Date" to buildDate, "Build-Time" to buildTime, "Build-Revision" to versioning.info.commit, "Specification-Title" to project.name, "Specification-Version" to normalizeVersion(project.version.toString()), "Specification-Vendor" to "apiguardian.org", "Implementation-Title" to project.name, "Implementation-Version" to project.version, "Implementation-Vendor" to "apiguardian.org", "Bundle-Name" to project.name, "Bundle-Description" to project.description, "Bundle-DocURL" to "https://github.com/apiguardian-team/apiguardian", "Bundle-Vendor" to "apiguardian.org", "-exportcontents" to "org.apiguardian.api", "Bundle-SymbolicName" to moduleName ) } from(files(compileModule.map { "${it.destinationDir}/${moduleName}" })) { include("module-info.class") } } javadoc { (options as StandardJavadocDocletOptions).apply { memberLevel = JavadocMemberLevel.PROTECTED isAuthor = true header = "@API Guardian" addStringOption("Xdoclint:html,syntax,reference", "-quiet") links("https://docs.oracle.com/en/java/javase/11/docs/api/") } } named("sourcesJar") { from("${moduleSourceDir}/${moduleName}") { include("module-info.java") } } named("javadocJar") { from(javadoc.map { File(it.destinationDir, "element-list") }) { // For compatibility with older tools, e.g. NetBeans 11 rename { "package-list" } } } withType().configureEach { from(rootDir) { include("LICENSE") into("META-INF") } } val prepareDocsForUploadToGhPages by registering(Copy::class) { dependsOn(javadoc) outputs.dir(docsDir) from("$buildDir/docs") { include("javadoc/**") } from("$buildDir/docs/javadoc") { // For compatibility with pre JDK 10 versions of the Javadoc tool include("element-list") rename { "api/package-list" } } into("${docsDir}/${docsVersion}") filesMatching("javadoc/**") { path = path.replace("javadoc/", "api/") } includeEmptyDirs = false } val createCurrentDocsFolder by registering(Copy::class) { dependsOn(prepareDocsForUploadToGhPages) enabled = replaceCurrentDocs outputs.dir("${docsDir}/current") from("${docsDir}/${docsVersion}") into("${docsDir}/current") } gitPublishCommit { dependsOn(prepareDocsForUploadToGhPages, createCurrentDocsFolder) } } if (!isSnapshot) { signing { sign(publishing.publications) } } nexusPublishing { packageGroup.set(group.toString()) repositories { sonatype() } } publishing { publications { create("maven") { from(components["java"]) pom { name.set("${project.group}:${project.name}") description.set("@API Guardian") url.set("https://github.com/apiguardian-team/apiguardian") scm { connection.set("scm:git:git://github.com/apiguardian-team/apiguardian.git") developerConnection.set("scm:git:git://github.com/apiguardian-team/apiguardian.git") url.set("https://github.com/apiguardian-team/apiguardian") } licenses { license { name.set("The Apache License, Version 2.0") url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") } } developers { developer { id.set("apiguardian") name.set("@API Guardian Team") email.set("team@apiguardian.org") } } } } } } gitPublish { repoUri.set("https://github.com/apiguardian-team/apiguardian.git") branch.set("gh-pages") contents { from(docsDir) into("docs") } preserve { include("**/*") exclude("docs/$docsVersion/**") if (replaceCurrentDocs) { exclude("docs/current/**") } } } jtreg7-7.5.1+1+ds1/apiguardian/gradle.properties000066400000000000000000000001651475274123300214170ustar00rootroot00000000000000group = org.apiguardian version = 1.1.2 defaultBuiltBy = @API Guardian Team releaseBranch = master jtreg7-7.5.1+1+ds1/apiguardian/gradlew000077500000000000000000000132161475274123300174170ustar00rootroot00000000000000#!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MSYS* | MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" jtreg7-7.5.1+1+ds1/apiguardian/gradlew.bat000066400000000000000000000053131475274123300201600ustar00rootroot00000000000000@rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega jtreg7-7.5.1+1+ds1/apiguardian/settings.gradle.kts000066400000000000000000000002721475274123300216620ustar00rootroot00000000000000rootProject.name = "apiguardian-api" require(JavaVersion.current().isJava11) { "The @API Guardian build requires Java 11. Currently executing with Java ${JavaVersion.current()}." } jtreg7-7.5.1+1+ds1/apiguardian/src/000077500000000000000000000000001475274123300166305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/main/000077500000000000000000000000001475274123300175545ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/main/java/000077500000000000000000000000001475274123300204755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/main/java/org/000077500000000000000000000000001475274123300212645ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/main/java/org/apiguardian/000077500000000000000000000000001475274123300235505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/main/java/org/apiguardian/api/000077500000000000000000000000001475274123300243215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/main/java/org/apiguardian/api/API.java000066400000000000000000000101161475274123300255740ustar00rootroot00000000000000/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apiguardian.api; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * {@code @API} is used to annotate public types, methods, constructors, and * fields within a framework or application in order to publish their * {@link #status} and level of stability and to indicate how they are intended * to be used by {@link #consumers} of the API. * *

If {@code @API} is present on a type, it is considered to hold for all * public members of the type as well. However, a member of such an annotated * type is allowed to declare a {@link Status} of lower stability. For example, * a class annotated with {@code @API(status = STABLE)} may declare a constructor * for internal usage that is annotated with {@code @API(status = INTERNAL)}. * *

If {@code @API} is present on a package, it is considered to hold for all * public types in its package. The same rules for lowered stability apply as * if they were specified on a type. * * @since 1.0 */ @Target({ TYPE, METHOD, CONSTRUCTOR, FIELD, PACKAGE }) @Retention(RUNTIME) @Documented public @interface API { /** * The current {@linkplain Status status} of the API. */ Status status(); /** * The version of the API when the {@link #status} was last changed. * *

Defaults to an empty string, signifying that the since * version is unknown. */ String since() default ""; /** * List of packages belonging to intended consumers. * *

The supplied packages can be fully qualified package names or * patterns containing asterisks that will be used as wildcards. * *

Defaults to {@code "*"}, signifying that the API is intended to be * consumed by any package. */ String[] consumers() default "*"; /** * Indicates the status of an API element and therefore its level of * stability as well. */ enum Status { /** * Must not be used by any external code. Might be removed without prior * notice. */ INTERNAL, /** * Should no longer be used. Might disappear in the next minor release. * *

This status is usually used in combination with the standard annotation * {@link Deprecated @Deprecated} because that annotation is recognized by * IDEs and the compiler. However, there are also cases where this status * can be used on its own, for example when transitioning a {@link #MAINTAINED} * feature to an {@link #INTERNAL} one. */ DEPRECATED, /** * Intended for new, experimental features where the publisher of the * API is looking for feedback. * *

Use with caution. Might be promoted to {@link #MAINTAINED} or * {@link #STABLE} in the future, but might also be removed without * prior notice. */ EXPERIMENTAL, /** * Intended for features that will not be changed in a backwards-incompatible * way for at least the next minor release of the current major version. * If scheduled for removal, such a feature will be demoted to * {@link #DEPRECATED} first. */ MAINTAINED, /** * Intended for features that will not be changed in a backwards-incompatible * way in the current major version. */ STABLE; } } jtreg7-7.5.1+1+ds1/apiguardian/src/module/000077500000000000000000000000001475274123300201155ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/module/java/000077500000000000000000000000001475274123300210365ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/module/java/org.apiguardian.api/000077500000000000000000000000001475274123300246605ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/apiguardian/src/module/java/org.apiguardian.api/module-info.java000066400000000000000000000000761475274123300277440ustar00rootroot00000000000000module org.apiguardian.api { exports org.apiguardian.api; } jtreg7-7.5.1+1+ds1/doc/000077500000000000000000000000001475274123300143225ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/doc/building.md000066400000000000000000000164541475274123300164530ustar00rootroot00000000000000# Building The Regression Test Harness for the OpenJDK platform: `jtreg` (This information is also available at ) `jtreg` depends on a number of external components: JT Harness, TestNG, JUnit, AsmTools, and JCov. The fundamental way to build `jtreg` is with GNU make, specifying where to find those external components, but a script is also available that will download appropriate copies of those components before building `jtreg`. ## Building `jtreg` with the `build.sh` script This is the recommended way to build `jtreg`, for those that want a simple, basic way to build `jtreg`. *Note:* The _build.sh_ script supersedes the earlier _build-all.sh_ script. The script is intended to be run in a Unix-like shell, such as `bash` on Linux or Mac OS X, or with Cygwin, MSYS2, or WSL on Windows. At a minimum, you must either set the `JAVA_HOME` environment variable or specify the location of the JDK to be used to build `jtreg` with the `--jdk` command-line option. It must be a recent build of JDK 11 or later. % cd jtreg-root-directory % sh make/build.sh --jdk JDK-directory If your shell is not compatible with `bash`, you may need to invoke `bash` explicitly: % bash make/build.sh --jdk JDK-directory The script will create a `build` sub-directory, download and build dependencies, and finally build `jtreg` itself. The resulting image will be in _build/images/jtreg_ . If you have access to the public Internet, no environment variables need to be specified to get a standard build of `jtreg`. However, you can set environment variables used to define the location of dependencies to be downloaded. These are documented in _make/build.sh_ and are normally specified in _make/build-support/version-numbers_ and _make/build-support/*/version-numbers_ . ### Rebuilding faster with `build/make.sh` After you have run `make/build.sh` once, if you wish to rebuild after making some changes, you can run `build/make.sh`. It skips the steps to download and build the dependencies, and so should be significantly faster. ## Building `jtreg` with GNU Make If you don't want to use `build.sh` to build `jtreg`, you can invoke the makefile directly, or by writing and using your own alternative wrapper. The makefiles require a number of variables to be set, identifying the parts of all the dependencies. In general, there are two kinds of variable to be set for each dependency: the location of any jar files that may be required to use the component, and the location of any "legal notices" (such as license files) that may need to be included in the `jtreg` image. There are five dependencies that need to be made available. The following lists the variables that need to be set for each dependency. 1. [JT Harness] (JavaTest) * `JAVATEST_JAR`: a jar file containing the classes for JT Harness * `JTHARNESS_NOTICES`: any legal notices that may be required to use JT Harness 2. [AsmTools] * `ASMTOOLS_JAR`: a jar file containing the classes for AsmTools * `ASMTOOLS_NOTICES`: any legal notices that may be required to use AsmTools 3. [JCov] * `JCOV_JAR`: a jar file containing the main set classes for JCov tools * `JCOV_NETWORK_SAVER_JAR`: a jar file containing the classes to inject into a JVM to save coverage information * `JCOV_NOTICES`: any legal notices that may be required to use JCov 4. [JUnit] * `JUNIT_JARS`: a list of one or more jar files containing the classes for JUnit and its dependencies: the list may be a series of jar files or a singleton "uber-jar" * `JUNIT_NOTICES`: any legal notices that be required to use JUnit Consult the JUnit documentation to see if there are any additional dependencies that may be required when running JUnit. 5. [TestNG] * `TESTNG_JARS`: a list of one or more jar files containing the classes for TestNG and its dependencies: the list may be a series of jar files or a singleton "uber-jar" * `TESTNG_NOTICES`: any legal notices that be required to use TestNG Consult the TestNG documentation to see if there are any additional dependencies that may be required when running TestNG. In general, any jar files identified by `*_JAR` or `*_JARS` variables will be copied to the `lib` directory in the generated image. Any files identified by `*_NOTICES` variables will be copied to a component-specific subdirectory of the `legal` directory in the generated image. [AsmTools]: https://github.com/openjdk/asmtools [JCov]: https://github.com/openjdk/jcov [JT Harness]: https://github.com/openjdk/jtharness [JUnit]: https://junit.org/ [TestNG]: https://testng.org/ ## Running `jtreg` Self-Tests The tests can be invoked with individual make targets, or collectively via the `test` target. Individual make targets for self-tests are explained [here](../test/README.md#makefiles). For example, the [ControlTest.gmk](../test/ctrl/ControlTest.gmk) makefile has a `$(BUILDTESTDIR)/ControlTest.ok` target which runs one of the self-tests. In order to run that individual test, use a command such as the following: ```shell bash build/make.sh $(pwd)/build/test/ControlTest.ok ``` Some tests depend on specific versions of JDK being available, specified by the following variables: `JDK8HOME`, `JDK9HOME`, `JDK14HOME`, `JDK18HOME`. A test that requires any of these version of JDK will be skipped if the variable is not set. Some of the tests need to pop up windows while they execute. No interaction with these windows is normally required. Since this can be a problem on a headless server machine, and an annoyance on a personal workstation, the tests will attempt to use VNC to create a dummy X-server for use by the tests while they are running. Various implementations of VNC are available, such as from . Using VNC is optional; it is not required in order to run the tests. By default, VNC will be used if `vncserver` is found on your execution path, or if VNC_HOME points to an installed copy of VNC. To explicitly disable the use of VNC, set the VNC environment variable to one of false, off, no, or 0. Unless explicitly disabled, the tests will check the following: * You must have a password set in _$HOME/.vnc/passwd_. This is the standard location used by the vncserver command. * If you set the environment variable `VNC_HOME`, it will be prepended to your execution path to find vncserver. * vncserver must be on your execution path, after `VNC_HOME` has been added, if set. If the tests find any issue with using VNC, it will not be used. If VNC is used to create a dummy X server, the server will be terminated when the test is complete. The logic for using VNC is encapsulated within the script _make/display.sh_. # Contribution guidelines Contributors are encouraged to follow code style conventions in [Java Style Guidelines](https://cr.openjdk.org/~alundblad/styleguide/index-v6.html) where reasonable. Existing `jtreg` command-line options have a certain style due to their age, but new options should strive to follow [JEP 293: Guidelines for JDK Command-Line Tool Options](https://openjdk.org/jeps/293). For backwards compatibility, `jtreg` option names are case-insensitive. The `jtreg` codebase is very dependent on (jtharness)[https://github.com/openjdk/jtharness]. The two repos should most often be viewed together. This also places constraints on what changes can (easily) be made in jtreg. jtreg7-7.5.1+1+ds1/hawt-jni/000077500000000000000000000000001475274123300152765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/.gitignore000066400000000000000000000001671475274123300172720ustar00rootroot00000000000000.classpath .project .settings *.iml *.ipr *.iws .idea webgen/out webgen/webgen.cache target dependency-reduced-pom.xml jtreg7-7.5.1+1+ds1/hawt-jni/.travis.yml000066400000000000000000000006021475274123300174050ustar00rootroot00000000000000language: java jobs: include: - arch: amd64 - arch: ppc64le before_install: - mkdir -p /opt/maven - curl https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz|tar -xz --strip 1 -C /opt/maven - export MAVEN_HOME=/opt/maven - export PATH=${MAVEN_HOME}/bin:${PATH} after_failure: print_surefire_reports.sh jtreg7-7.5.1+1+ds1/hawt-jni/changelog.md000066400000000000000000000510421475274123300175510ustar00rootroot00000000000000# ![HawtJNI](http://fusesource.github.io/hawtjni/images/project-logo.png) ## HawtJNI 1.18, released 2020-10-21 * [`84606da`](https://github.com/fusesource/hawtjni/commit/84606dacef9bced4d21c2d47bb641b2737738ceb) Bump junit from 4.13 to 4.13.1 in /hawtjni-example * [`de46737`](https://github.com/fusesource/hawtjni/commit/de4673789a0f0892516450f837c301f5e81246d0) Merge pull request #70 from Siddhesh-Ghadi/ci-power * [`c06f662`](https://github.com/fusesource/hawtjni/commit/c06f662b9e7ef74dd98bf73f9458cae7a3f5fd86) Add ppc64le support on travis-ci * [`2976527`](https://github.com/fusesource/hawtjni/commit/2976527a43ec256c98c383110d436bba7aff8c9c) Add doc to setup the native build environment macOS * [`c00e2d2`](https://github.com/fusesource/hawtjni/commit/c00e2d22b4dfa105d31754bf044874845d7cacb5) Support for shared pointers, fixes #57 * [`5b4e5ad`](https://github.com/fusesource/hawtjni/commit/5b4e5ad74e63f1c1c180b2169eedd20c9b64e716) Merge pull request #59 from voutilad/master * [`8678713`](https://github.com/fusesource/hawtjni/commit/8678713caf00652f4f7d52e36b8b384cf611dde5) Merge pull request #61 from remkop/master * [`d145a1d`](https://github.com/fusesource/hawtjni/commit/d145a1dea37bbd8f98c9f1e6f21d756f849d7979) Do not force JDK 11 but rather support it * [`8ee5b21`](https://github.com/fusesource/hawtjni/commit/8ee5b2113069399c79610a1de6e01af7d5ae8c45) Updated to work with JDK11 * [`d1f1492`](https://github.com/fusesource/hawtjni/commit/d1f14926156d103357e7761c4182085b27e7c663) Fix example on OSX * [`b7277af`](https://github.com/fusesource/hawtjni/commit/b7277aff8f3b01c1c462ede437efb3a4a33973ff) prepare 1.17 release website * [`56b5bd0`](https://github.com/fusesource/hawtjni/commit/56b5bd0dd3e9a3091905cf262dbe232b65447e07) use hawtjni-maven-plugin for Maven Central badge * [`c14fec0`](https://github.com/fusesource/hawtjni/commit/c14fec00b9976ff6b84e62e483d678594a7d3832) Support for OSX Catalina * [`2c64ed4`](https://github.com/fusesource/hawtjni/commit/2c64ed4134de9b3cefd9423382a59f60c8f3ad25) jansi/#162 fix issue where bitModel could not be retrieved on GraalVM * [`e7806ff`](https://github.com/fusesource/hawtjni/commit/e7806ff89508fce6a61c300ea9a16992324c0ce1) support for OpenBSD ## HawtJNI 1.17, released 2019-04-03 * [`1c4a17b`](https://github.com/fusesource/hawtjni/commit/1c4a17b31bf988f99df6da7085f86829b935c342) Remove shared_ptr support until it's working * [`d3f9d0a`](https://github.com/fusesource/hawtjni/commit/d3f9d0ab71fd25d8d6f6eb9c3de6c6b47ddae92e) Keep (long*) for standard pointers * [`906aa15`](https://github.com/fusesource/hawtjni/commit/906aa158c24d3603aca6f3766b7fa0da306d23d6) Merge branch 'calin-iorgulescu-master' * [`c5130eb`](https://github.com/fusesource/hawtjni/commit/c5130eb900279531f67d4734ccf1ad2f2ad95a70) Fix typo * [`9d38df2`](https://github.com/fusesource/hawtjni/commit/9d38df2f4a25ee55fbb0dc921fb2004b33c59541) Merge branch 'master' of https://github.com/calin-iorgulescu/hawtjni into calin-iorgulescu-master * [`1c42406`](https://github.com/fusesource/hawtjni/commit/1c42406ec55ed1955d2fc573e3002e5fa557c984) Merge branch 'master' of https://github.com/batterseapower/hawtjni into batterseapower-master * [`55afd36`](https://github.com/fusesource/hawtjni/commit/55afd361a8fe44d4d6126de30b279c5b941894ba) Add 10.14 in OSX SDK version list * [`d094c95`](https://github.com/fusesource/hawtjni/commit/d094c95e7fd0fb879f896b49c796a92adee72369) Merge pull request #45 from wjsl/osx10.13 * [`d028542`](https://github.com/fusesource/hawtjni/commit/d028542040a23e090633ab0b192ca9c08f7838e2) Merge pull request #48 from castortech/master * [`c0cfb25`](https://github.com/fusesource/hawtjni/commit/c0cfb2558b8e11edd224f08fd7da6daa84876b34) Merge branch 'master' into master * [`73e0b4f`](https://github.com/fusesource/hawtjni/commit/73e0b4f68d4597295bcb6d0196a1c030ff14589a) Merge pull request #55 from tdemande/hawtjni-issue-54 * [`ec9cc6c`](https://github.com/fusesource/hawtjni/commit/ec9cc6c3ce72b7fcd99d356f1abbc0f36fbb9a29) Merge branch 'hawtjni_shared_pointer' of https://github.com/ossdev07/hawtjni into ossdev07-hawtjni_shared_pointer * [`bd514b7`](https://github.com/fusesource/hawtjni/commit/bd514b71878415e7091b914420a291310de3ec30) Implement a different strategy with sha1 checksum for extracting libraries, fixes #56 * [`40e0b2f`](https://github.com/fusesource/hawtjni/commit/40e0b2f27a2218b4d10ae3989a4ed74bcf40562d) Formatting * [`bc3f187`](https://github.com/fusesource/hawtjni/commit/bc3f187087a043caa6737a78c10f982159bd8c2c) #54 Also search in base dir when finding/extracting native lib * [`8f464d0`](https://github.com/fusesource/hawtjni/commit/8f464d07bc9a807acf33f0f2e355065471f15235) Implement new JNIField accessor model: allow support for separate getter/setter methods for individual fields. * [`5f52fee`](https://github.com/fusesource/hawtjni/commit/5f52fee5720c5cbeeaae71cfaa90611bcba56e8d) StructsGenerator: Fix bug where a JniClass extending another class that has only ignored fields would generate calls to cache the fields. * [`2b88a8f`](https://github.com/fusesource/hawtjni/commit/2b88a8f56fdbbf0e71b213f15b333a681e7dc72f) StructsGenerator: Fix bug where an empty field declaration would be created if only skipped fields are declared in a struct. * [`235f0b9`](https://github.com/fusesource/hawtjni/commit/235f0b985acba4559cfda588a0312287f9420791) Change maven settings to allow building. * [`839ddcf`](https://github.com/fusesource/hawtjni/commit/839ddcf2bff9e53020f162feeac7258ea6ac97db) added icon for hawtjni-runtime artifact in Central * [`27af76b`](https://github.com/fusesource/hawtjni/commit/27af76b5f73af61ef592cc66ed65fb12438cc166) Update StructsGenerator.java * [`f29f849`](https://github.com/fusesource/hawtjni/commit/f29f84960133e5a5740bcd6b6120b8bb7f172f0d) added Automatic-Module-Name to manifest for Java 9 auto-module name * [`1c2d511`](https://github.com/fusesource/hawtjni/commit/1c2d511d970ad07924ebdbb1e8566fb56e2edf6c) Hawtjni: Shared_pointer support added in hawtjni * [`7a6082f`](https://github.com/fusesource/hawtjni/commit/7a6082faed85ea73945065466e68ad6035cf724d) fixed typo * [`35c061c`](https://github.com/fusesource/hawtjni/commit/35c061ca7ffedb11fa52a18c8c087a41bbb5cd88) added Runtime API as a feature * [`6c1f140`](https://github.com/fusesource/hawtjni/commit/6c1f140970a59727a102b8ee2daef909eb991b78) Added customization for the Windows build. * [`98b1531`](https://github.com/fusesource/hawtjni/commit/98b1531628f236aa9a68fd49b67ac09f1b547868) Added missing case of "no directory" as per method documentation. * [`a103c50`](https://github.com/fusesource/hawtjni/commit/a103c50b1b1b357d6a5d932cac7ebc599bb0d16b) Added support to detect newer versions of Visual Studio as candidates for msbuild * [`6f891af`](https://github.com/fusesource/hawtjni/commit/6f891af96768e77f5e800fd0f723712b87e30735) Updated documentation to clearly indicate the vcbuild is deprecated and that msbuild is supported. * [`84aa381`](https://github.com/fusesource/hawtjni/commit/84aa381836dae2b784ea685b71c54c6eb6622646) update changelog.md for 1.16 release * [`3fffa67`](https://github.com/fusesource/hawtjni/commit/3fffa67c2b23f92a1c57552e3779c58382795855) fixed and improved changelog.md formatting * [`2c7134b`](https://github.com/fusesource/hawtjni/commit/2c7134b4ee612af788d8486181459580811ba1d6) Add 10.13 in OSX SDK version list ## HawtJNI 1.16, released 2018-02-02 * [`2e99592`](https://github.com/fusesource/hawtjni/commit/2e99592f7be976a935beeed7d7395d4a5787e04e) fixed site build * [`14f1d05`](https://github.com/fusesource/hawtjni/commit/14f1d0564d6e2c71c74288e537fcfa4acf7f4c18) renamed maven-hawtjni-plugin to hawtjni-maven-plugin * [`743d57b`](https://github.com/fusesource/hawtjni/commit/743d57b25337dc1e0b5dcfc7dce63b15a4433f78) switched Maven plugin from javadoc annotations to Java5 annotations * [`4a42ee6`](https://github.com/fusesource/hawtjni/commit/4a42ee611ad66c71a6d4b32d41b78ca02ca225e4) [#36](http://github.com/fusesource/hawtjni/issues/36) added info on loaded native library * [`16c5d82`](https://github.com/fusesource/hawtjni/commit/16c5d820e84864fe437ce77a33011b50b2a6f66d) Merge pull request [#37](http://github.com/fusesource/hawtjni/issues/37) from ghost/patch-1 * [`45e8a55`](https://github.com/fusesource/hawtjni/commit/45e8a557788a8dbf9fd134df6f8e99f456e3324f) [#43](http://github.com/fusesource/hawtjni/issues/43) mark HawtJNI annotations @Documented * [`f0c3b54`](https://github.com/fusesource/hawtjni/commit/f0c3b547aeecd508498871583595ab7adff54ea3) s/your/you're/ ## [HawtJNI 1.15](http://fusesource.github.io/hawtjni/blog/releases/release-1-15.html), released 2017-05-04 * [`7537b9d`](https://github.com/fusesource/hawtjni/commit/7537b9d19be9806b210674ccad4b96d90a11d50b) Update changelog * [`906cedb`](https://github.com/fusesource/hawtjni/commit/906cedb80b9661d0ea08f524fb464243610653a9) Default to extract in the users' home folder in case the temp directory is not writable * [`ed95784`](https://github.com/fusesource/hawtjni/commit/ed95784f9a4d3ed1afb0a14bd3dccc815d3e3cbe) search in library.$name.path like in META-INF/native resources * [`477c8cc`](https://github.com/fusesource/hawtjni/commit/477c8ccac78c3695ebcf6299d8b201adb3394d34) Fix some other problems with platform, especially on windows when compiling for the non native platform * [`58834e8`](https://github.com/fusesource/hawtjni/commit/58834e835c6f196f6188c6f35aa9c349db610d84) Upgrade some plugins * [`992ee3f`](https://github.com/fusesource/hawtjni/commit/992ee3fa28f30823913fe95a790fe3a08d19bdf3) Fix bad naming for the extracted file when the version contains a dot * [`6b58328`](https://github.com/fusesource/hawtjni/commit/6b58328635bd181c18048387aa7d83fda51d5be8) Do not include the extension in the windows project name, [#23](http://github.com/fusesource/hawtjni/issues/23) * [`9165154`](https://github.com/fusesource/hawtjni/commit/916515413152d2b25268d0f813c1f0f411388b3a) Merge pull request [#30](http://github.com/fusesource/hawtjni/issues/30) from felixvf/fix_lib64_bug * [`1cb6770`](https://github.com/fusesource/hawtjni/commit/1cb6770dc7348958d96b38d8d0b1f4b065f43da5) Merge pull request [#34](http://github.com/fusesource/hawtjni/issues/34) from hboutemy/master * [`4c430c6`](https://github.com/fusesource/hawtjni/commit/4c430c6d4454b37e035c1fb7ae284b8d3ac99c03) Merge pull request [#20](http://github.com/fusesource/hawtjni/issues/20) from felixvf/fix_bug_18 * [`f99972b`](https://github.com/fusesource/hawtjni/commit/f99972b7892fd621dca1442b8c8f3234edd4b02f) Better exception reporting when unable to load a library, fixes [#27](http://github.com/fusesource/hawtjni/issues/27) * [`1c5b81f`](https://github.com/fusesource/hawtjni/commit/1c5b81fb386f74e47e776f3ba2775d15003f2ae9) Allow the windows project name to be specified, fixes [#23](http://github.com/fusesource/hawtjni/issues/23) * [`ef3437c`](https://github.com/fusesource/hawtjni/commit/ef3437cde117c04793d773b25bd0627e5e260e66) Allow the -Dplatform=xxx setting to be used when doing the actual native build * [`0072848`](https://github.com/fusesource/hawtjni/commit/0072848253e100c98745725bdf5224e63103fad7) Remove explicit array creation when using var args * [`c6fb914`](https://github.com/fusesource/hawtjni/commit/c6fb9149b43292564bbc854d9942d4898a7f728d) Remove unused imports * [`145f3ee`](https://github.com/fusesource/hawtjni/commit/145f3ee50204c8b8f8ae728cc91533dd19424d7d) Fix typos in method names * [`81a35e1`](https://github.com/fusesource/hawtjni/commit/81a35e1a923bb1c7b0e6ffbdd66a08c83e119324) prepare gh-pages publication with scm-publish plugin * [`b3982d5`](https://github.com/fusesource/hawtjni/commit/b3982d573b04878918aebe5435a5f64af6a4401f) Use latest version of maven javadoc plugin * [`cb2ad85`](https://github.com/fusesource/hawtjni/commit/cb2ad85bc551e1628be25181acd6f9e97e04afab) Merge branch 'hboutemy-hawtjni-31' * [`cd20329`](https://github.com/fusesource/hawtjni/commit/cd20329a801e5d904d7a43c46d3cb150b4767b66) [#31](http://github.com/fusesource/hawtjni/issues/31) fixed API doc generation and misc other Maven-related conf * [`784a50f`](https://github.com/fusesource/hawtjni/commit/784a50f22d0abd1d4fa05f1fb720e70623092e63) Fix libdir to "/lib". Prevent any variation such as "/lib64". * [`401ce1c`](https://github.com/fusesource/hawtjni/commit/401ce1cc6f053fccae386977b695ae7a5948ef4d) Update readme.md * [`a73fc16`](https://github.com/fusesource/hawtjni/commit/a73fc165306a139e8cbb82f9dc28002c05d6d206) Merge pull request [#11](http://github.com/fusesource/hawtjni/issues/11) from OhmData/travis * [`098c501`](https://github.com/fusesource/hawtjni/commit/098c501c90feb20749105840eaca1f51fbae2559) Simplify the fallback case a bit * [`40f9f23`](https://github.com/fusesource/hawtjni/commit/40f9f23b4839941e217a8415eb9799aa539e0e36) Merge pull request [#22](http://github.com/fusesource/hawtjni/issues/22) from slaunay/use-java7-chmod-with-unix-chmod-fallback ## [HawtJNI 1.14](http://fusesource.github.io/hawtjni/blog/releases/release-1.14.html), released 2016-06-20 * [`e2522b0`](https://github.com/fusesource/hawtjni/commit/e2522b0ddd9f8975dc3a1cc99534ea458b807ddd) Merge pull request [#26](http://github.com/fusesource/hawtjni/issues/26) from michael-o/freebsd * [`6dc93fe`](https://github.com/fusesource/hawtjni/commit/6dc93fe4c3b67e68d9805b6f0cc7f2b7c36d5b06) Improve FreeBSD support * [`2d49307`](https://github.com/fusesource/hawtjni/commit/2d493076d264f6d8e2ac81ada4da4fcd78b2dabf) Deploy to sonatype. ## [HawtJNI 1.12](http://fusesource.github.io/hawtjni/blog/releases/release-1.12.html), released 2016-04-26 * [`70f24ba`](https://github.com/fusesource/hawtjni/commit/70f24ba7438a698d8e1e0de599b304774e01f5d4) Don't build the website by default. * [`ef93152`](https://github.com/fusesource/hawtjni/commit/ef931527b4ca915a53c59eb6f6ef0222f8cf3c12) Better JDK detection on OS X. * [`61ac652`](https://github.com/fusesource/hawtjni/commit/61ac6525a42117f0ea8820417d00616ef7f27452) Use Files.setPosixFilePermissions for chmod * [`57e5b32`](https://github.com/fusesource/hawtjni/commit/57e5b3262a86ac0541585f3b3a40bf3b8933561b) Define JNI64 not only in case of \_\_x86\_64\_\_ but in general for any \_LP64 platform. ## [HawtJNI 1.11](http://fusesource.github.io/hawtjni/blog/releases/release-1.11.html), released 2015-04-21 * [`e1da91a`](https://github.com/fusesource/hawtjni/commit/e1da91aec68eda9f40350b062c4fed4e75fb4cb1) Update xbean version used. * [`354e277`](https://github.com/fusesource/hawtjni/commit/354e2773cfb60008fd7500eef52ea7de8e9bb74a) Disable deployment of website since web host is not there anymore. * [`08cfdd0`](https://github.com/fusesource/hawtjni/commit/08cfdd0995bb298d88e87d559d2ce39018e6b509) Update parent pom. * [`86e97d1`](https://github.com/fusesource/hawtjni/commit/86e97d161d956009bbc92f2913dd570ece2ec3da) Merge pull request [#19](http://github.com/fusesource/hawtjni/issues/19) from jerrydlamme/master * [`1e2ee63`](https://github.com/fusesource/hawtjni/commit/1e2ee6330f6832a374e29b78a1fff2df62d4a52c) Added architecture specific native library loading path * [`d10c4b0`](https://github.com/fusesource/hawtjni/commit/d10c4b0914301810297f0f917ce3dba3e8868ff1) Merge pull request [#16](http://github.com/fusesource/hawtjni/issues/16) from NJAldwin/use-absolute-path * [`3d3aa0b`](https://github.com/fusesource/hawtjni/commit/3d3aa0be17cc8d35e251ea3594b1e684ce919d0d) Ensure absolute path is used for library * [`8c28532`](https://github.com/fusesource/hawtjni/commit/8c2853238e31b6e92f61fbdeda84314e5a529254) Merge pull request [#13](http://github.com/fusesource/hawtjni/issues/13) from batterseapower/master * [`c10adf5`](https://github.com/fusesource/hawtjni/commit/c10adf5139969f1bfa6cb6e8dd6af204d64280a9) Version bumps and markup fixes necessary for building on JDK8 * [`aed6cbd`](https://github.com/fusesource/hawtjni/commit/aed6cbd06b4579170617dae7146ec9c61b70d82c) Build a stock travis * [`efa684c`](https://github.com/fusesource/hawtjni/commit/efa684c0a87136f16b0bca67bc518ee9bf698f85) Ignore IDEA project files. * [`18cb7e5`](https://github.com/fusesource/hawtjni/commit/18cb7e5d98e0edf687ba2d02c724c36d631e9f65) prepare for next development iteration * [`f3bd38e`](https://github.com/fusesource/hawtjni/commit/f3bd38e1d83a5563c63b1bbebadf0c77c1fb54b8) Upgrade parent pom version. * [`175faf0`](https://github.com/fusesource/hawtjni/commit/175faf07fbc2ec1c42582d0b935bb05fd46fc33f) Merge pull request [#8](http://github.com/fusesource/hawtjni/issues/8) from normanmaurer/netty\_needs * [`b3f8609`](https://github.com/fusesource/hawtjni/commit/b3f8609c6682bda6d6c112c2e19c0c6cdc6dcfc6) Allow to also use generate mojo with existing native src files * [`c27b5a0`](https://github.com/fusesource/hawtjni/commit/c27b5a0c4640bce9437488275b0d8c360c45c1e6) Avoid warning. * [`c1980ef`](https://github.com/fusesource/hawtjni/commit/c1980ef32387547b0a5bba408abb00cbceaf6705) Add support for building against the Oracle JDK on OS X. ## [HawtJNI 1.10](http://fusesource.github.io/hawtjni/blog/releases/release-1.10.html), released 2014-02-12 * `efa684c` Ignore IDEA project files. * `18cb7e5` prepare for next development iteration * `f3bd38e` Upgrade parent pom version. * `175faf0` Merge pull request [#8](http://github.com/fusesource/hawtjni/issues/8) from normanmaurer/netty\_needs * `b3f8609` Allow to also use generate mojo with existing native src files * `c27b5a0` Avoid warning. * `c1980ef` Add support for building against the Oracle JDK on OS X. ## [HawtJNI 1.9](http://fusesource.github.io/hawtjni/blog/releases/release-1-9.html), released 2013-09-09 * [`1d27b2f`](https://github.com/fusesource/hawtjni/commit/1d27b2f1396920be7fce0be8b1995ac0459c69ef) Improve the generated build settings. * [`d9cd0ab`](https://github.com/fusesource/hawtjni/commit/d9cd0ab660ac5acbdc5f84c806ba14b77e197385) Should fix issue [#7](http://github.com/fusesource/hawtjni/issues/7). We now do a write barrier before setting the 'cached' field to 1 so that reader don't see this get re-ordered before all the fields are readable. ## [HawtJNI 1.8](http://fusesource.github.io/hawtjni/blog/releases/release-1-8.html), released 2013-05-13 * [`92c2661`](https://github.com/fusesource/hawtjni/commit/92c266170ce98edc200c656bd034a237098b8aa5) Simplify shared lib extraction. ## [HawtJNI 1.7](http://fusesource.github.io/hawtjni/blog/releases/release-1-7.html), released 2013-03-20 * [`3567b1d`](https://github.com/fusesource/hawtjni/commit/3567b1d89d458bddb651df252f3bb275c9076e1a) Support explicitly configuring which build tool to use on windows. * [`d566bf7`](https://github.com/fusesource/hawtjni/commit/d566bf7de5d6a67fa7c7b3e04352ca2630fb55fe) Fix for automake 1.11 ## [HawtJNI 1.6](http://fusesource.github.io/hawtjni/blog/releases/release-1-6.html), released 2012-08-09 * [`11df668`](https://github.com/fusesource/hawtjni/commit/11df668cb0d1269c0f98d9c09d80c56cf0770421) Updating hawtjni generate projects so that they work on OS X Lion. * [`f0e3ace`](https://github.com/fusesource/hawtjni/commit/f0e3ace6422e5c5413445229ac79d27f68b1485b) Fixes [#2](http://github.com/fusesource/hawtjni/issues/2) : Support passing the JNIEnv pointer to native methods. ## [HawtJNI 1.5](http://fusesource.github.io/hawtjni/blog/releases/release-1-5.html), released 2011-09-21 * [`15d5b1a`](https://github.com/fusesource/hawtjni/commit/15d5b1a4c928fb8c39eee0705316478af30704b5) Only include config.h if it's available. ## [HawtJNI 1.4](http://fusesource.github.io/hawtjni/blog/releases/release-1-4.html), released 2011-08-18 * Add more options to the maven hawtjni plugin so that you can build jars containing native libs in a different module from the one which generates the native package for the jar. ## [HawtJNI 1.3](http://fusesource.github.io/hawtjni/blog/releases/release-1-3.html), released 2011-08-08 * Add hawtjni_attach_thread and hawtjni_dettach_thread helper methods * Fully support binding against C++ source code / classes. * Support using private fields in struct bound classes. * Avoid "jump to label from here crosses initialization" compiler error message. * Provide better error messages when a user does not properly setup a C++ method binding. * Support mapping a class to a differently named structure name. * Support picking the OS X SDK version via a configure option. * Added pointer math support class to be able to do pointer math in java land without going into a JNI layer. ## [HawtJNI 1.2](http://fusesource.github.io/hawtjni/blog/releases/release-1-2.html), released 2011-06-11 * Adding bit model to the name of the extracted library to support hosts running both 32 and 64 bits JVM. * Converted website to a scalate based static website ## [HawtJNI 1.1](http://fusesource.github.io/hawtjni/blog/releases/release-1-1.html), released 2010-11-04 ---- * Generate a .vcxproj for for compatibility with the new Windows 7.1 SDK * Fixed callback failures on 32 bit platforms ## [HawtJNI 1.0](http://fusesource.github.io/hawtjni/blog/releases/2010/04/release-1-0.html), released 2010-02-24 * Initial release jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/000077500000000000000000000000001475274123300203735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/pom.xml000066400000000000000000000133741475274123300217200ustar00rootroot00000000000000 4.0.0 org.fusesource.hawtjni hawtjni-project 1.18 hawtjni-example HawtJNI Example org.fusesource.hawtjni hawtjni-runtime ${project.version} junit junit 4.13.1 test log4j log4j 1.2.17 test org.fusesource.hawtjni hawtjni-maven-plugin ${project.version} generate build package-jar package-source org.apache.maven.plugins maven-shade-plugin 3.2.3 package shade junit:junit *:* META-INF/MANIFEST.MF mac mac org.fusesource.hawtjni hawtjni-maven-plugin osname=MacOS;processor=x86-64 osname=MacOS;processor=x86 * --with-universal osx jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/000077500000000000000000000000001475274123300211625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/000077500000000000000000000000001475274123300221065ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/java/000077500000000000000000000000001475274123300230275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/java/test/000077500000000000000000000000001475274123300240065ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/java/test/Example.java000077500000000000000000000274061475274123300262600ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package test; import java.util.Arrays; import org.fusesource.hawtjni.runtime.*; import static org.fusesource.hawtjni.runtime.ArgFlag.*; import static org.fusesource.hawtjni.runtime.FieldFlag.*; import static org.fusesource.hawtjni.runtime.MethodFlag.*; /** * * @author Hiram Chirino */ @JniClass public class Example { private static final Library LIBRARY = new Library("hawtjni-example", Example.class); static { LIBRARY.load(); init(); } public static final void main(String args[]) { System.out.println("Checking Operating System Constants:"); System.out.println(" O_RDONLY: "+O_RDONLY); System.out.println(" O_WRONLY: "+O_WRONLY); System.out.println(" O_RDWR: "+O_RDWR); System.out.println(""); System.out.println("Allocating c structures on the heap..."); int COUNT = 10; // We track memory pointers with longs. long []ptrArray = new long[COUNT]; long last=0; for( int i=0; i < COUNT; i++ ) { // Allocate heap space of the structure.. ptrArray[i] = malloc(bar.SIZEOF); // Configure some data for a structure... bar f = new bar(); f.a = i; f.b = 1; byte[] src = "hello world".getBytes(); System.arraycopy(src, 0, f.c, 0, src.length); f.c5 = 0; f.prev = last; // Copy the data values into the allocated space. memmove(ptrArray[i], f, bar.SIZEOF); last = ptrArray[i]; } // Display a couple of structures... System.out.println("Dump of the first 2 structures:"); print_foo(ptrArray[0]); print_foo(ptrArray[1]); System.out.println("Passing a pointer array to a c function..."); long rc = foowork(ptrArray, COUNT); System.out.println("Function result (expecting 55): "+rc); System.out.println("freein up allocated memory."); for( int i=0; i < COUNT; i++ ) { free(ptrArray[i]); } } // Example of how to load constants. @JniMethod(flags={CONSTANT_INITIALIZER}) private static final native void init(); @JniField(flags={CONSTANT}) public static int O_RDONLY; @JniField(flags={CONSTANT}) public static int O_WRONLY; @JniField(flags={CONSTANT}) public static int O_RDWR; @JniMethod(cast="void *") public static final native long malloc( @JniArg(cast="size_t") long size); public static final native void free( @JniArg(cast="void *") long ptr); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) byte[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) char[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) short[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) int[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) long[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) float[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) double[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) byte[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) char[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) short[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) int[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) long[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) float[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) double[] dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) byte[] dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) char[] src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) int[] dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) byte[] src, @JniArg(cast="size_t") long size); @JniMethod(cast="void *") public static final native long memset ( @JniArg(cast="void *") long buffer, int c, @JniArg(cast="size_t") long num); public static final native int strlen( @JniArg(cast="char *")long s); @JniClass(name="foo", flags={ClassFlag.STRUCT}) static public class bar { static { LIBRARY.load(); init(); } @JniMethod(flags={CONSTANT_INITIALIZER}) private static final native void init(); // public static final native int foo_sizeof (); @JniField(flags={CONSTANT}, accessor="sizeof(struct foo)") public static int SIZEOF; public int a; @JniField(cast="size_t") public long b; public byte c[] = new byte[20]; @JniField(accessor="c[5]") public byte c5; @JniField(cast="struct foo *") public long prev; @JniField(getter = "get_d()", setter = "set_d()", flags = { GETTER_NONMEMBER, SETTER_NONMEMBER }) private float d; @JniField(getter = "get_sp()", setter = "set_sp()", flags={ SHARED_PTR, GETTER_NONMEMBER, SETTER_NONMEMBER }) private long CheckStr; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + (int) (b ^ (b >>> 32)); result = prime * result + Arrays.hashCode(c); result = prime * result + c5; result = prime * result + (int) (prev ^ (prev >>> 32)); result = prime * result + Float.valueOf(d).hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; bar other = (bar) obj; if (a != other.a) return false; if (b != other.b) return false; if (!Arrays.equals(c, other.c)) return false; if (c5 != other.c5) return false; if (prev != other.prev) return false; if (d != other.d) { return false; } return true; } @Override public String toString() { return "foo [a=" + a + ", b=" + b + ", c=" + Arrays.toString(c) + ", c5=" + c5 + ", prev=" + prev + ", d=" + d + "]"; } } public static final native void memmove ( @JniArg(cast="void *") long dest, @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) bar src, @JniArg(cast="size_t") long size); public static final native void memmove ( @JniArg(cast="void *", flags={NO_IN, CRITICAL}) bar dest, @JniArg(cast="const void *") long src, @JniArg(cast="size_t") long size); public static final native void print_foo(@JniArg(cast="struct foo *")long ptr); public static final native long foowork (@JniArg(cast="struct foo **") long[] foos, int count); @JniMethod(cast = "struct foo *") public static final native long foo_add(@JniArg(cast="struct foo *")long ptr, int count); @JniMethod(cast = "char *") public static final native long char_add(@JniArg(cast="char *")long ptr, int count); @JniClass(flags={ClassFlag.STRUCT, ClassFlag.TYPEDEF}) static public class point { static { LIBRARY.load(); init(); } @JniMethod(flags={CONSTANT_INITIALIZER}) private static final native void init(); @JniField(flags={CONSTANT}, accessor="sizeof(point)") public static int SIZEOF; public int x; public int y; } public static final native void callmeback( @JniArg(cast="void (*)(int)", flags = ArgFlag.POINTER_ARG) long ptr); @JniClass(flags={ClassFlag.STRUCT, ClassFlag.CPP}) static class Range { static { LIBRARY.load(); } @JniMethod(flags={MethodFlag.CPP_NEW}) public static final native long Range(); @JniMethod(flags={MethodFlag.CPP_NEW}) public static final native long Range(int start, int end); @JniMethod(flags={MethodFlag.CPP_DELETE}) public static final native void delete(long ptr); @JniMethod(flags={MethodFlag.CPP_METHOD}) public static final native void dump(long ptr); } public static final native void passingtheenv (String msg, JNIEnv env); @JniClass(flags={ClassFlag.STRUCT}) static class ClassWithAccessors { static { LIBRARY.load(); } @JniField(getter = "get_e()", setter = "set_e()") private float e; } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/java/test/ObjectiveCExample.java000066400000000000000000000055461475274123300302140ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package test; import org.fusesource.hawtjni.runtime.JniArg; import org.fusesource.hawtjni.runtime.JniClass; import org.fusesource.hawtjni.runtime.JniMethod; import org.fusesource.hawtjni.runtime.Library; import static org.fusesource.hawtjni.runtime.ArgFlag.*; import static org.fusesource.hawtjni.runtime.MethodFlag.*; /** * * @author Hiram Chirino */ @JniClass(conditional="defined(__APPLE__)") public class ObjectiveCExample { private static final Library LIBRARY = new Library("hawtjni-example", Example.class); static { LIBRARY.load(); } public static final void main(String args[]) { // Memory pool... long NSAutoreleasePool = objc_getClass("NSAutoreleasePool"); long pool = $($(NSAutoreleasePool, alloc), init); // Allocate and use a simple Objective C object long NSString = objc_getClass("NSString"); long id = $(NSString, stringWithUTF8String, "Hello"); long value = $(id, length); System.out.println("The length was: "+value); // Release the pool to release the allocations.. $(pool, release); } public static final long stringWithUTF8String = sel_registerName("stringWithUTF8String:"); public static final long release = sel_registerName("release"); public static final long alloc = sel_registerName("alloc"); public static final long init = sel_registerName("init"); public static final long length = sel_registerName("length"); @JniMethod(cast="SEL", flags={POINTER_RETURN}) public static final native long sel_registerName(String selectorName); @JniMethod(cast="id", flags={POINTER_RETURN}) public static final native long objc_getClass(String className); @JniMethod(cast="id", flags={POINTER_RETURN}, accessor="reinterpret_cast (objc_msgSend)") public static final native long $( @JniArg(cast="id", flags={POINTER_ARG})long id, @JniArg(cast="SEL", flags={POINTER_ARG})long sel ); @JniMethod(cast="id", flags={POINTER_RETURN}, accessor="reinterpret_cast (objc_msgSend)") public static final native long $( @JniArg(cast="id", flags={POINTER_ARG})long id, @JniArg(cast="SEL", flags={POINTER_ARG})long sel, String arg0); } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/native-package/000077500000000000000000000000001475274123300247655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/native-package/src/000077500000000000000000000000001475274123300255545ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/native-package/src/foo.cpp000066400000000000000000000026611475274123300270500ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ #include "foo.h" #include float get_d(struct foo *arg) { return 0.0f; } void set_d(struct foo *arg, float d) { } std::shared_ptr get_sp(long CheckStr) { return std::make_shared (CheckStr); } void set_sp(struct foo *arg, std::shared_ptr ptr) { } void print_foo(struct foo *arg) { printf("foo@%p: { a: %d, b: %d, c: \"%s\", prev: @%p, d: %f, Checkstr: %p}\n", arg, arg->a, (int)arg->b, arg->c, arg->prev, get_d(arg), get_sp(arg->CheckStr).get()); } long foowork(struct foo **arg, int count) { long rc=0; int i=0; for( i=0; i < count; i++ ) { rc = rc + (*arg)->a; rc = rc + (*arg)->b; arg++; } return rc; } void callmeback(void (*thecallback)(int number)) { thecallback(69); } struct foo * foo_add(struct foo *arg, int count) { return arg+count; } char * char_add(char *arg, int count) { return arg+count; } void passingtheenv (const char *who, JNIEnv *env) { printf("%s, the JNIEnv is at: %p\n", who, env); } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/native-package/src/foo.h000066400000000000000000000027121475274123300265120ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ #ifndef INCLUDED_FOO_H #define INCLUDED_FOO_H #include #include #include "jni.h" #ifdef __cplusplus extern "C" { #endif struct foo { int a; size_t b; char c[20]; struct foo *prev; long CheckStr; }; typedef struct _point { int x; int y; } point; struct ClassWithAccessors { float e; float (*get_e)(); void (*set_e)(float e); }; float get_d(struct foo *arg); void set_d(struct foo *arg, float d); float ClassWithAccessors_get_e(struct foo *arg); void ClassWithAccessors_set_e(struct foo *arg, float e); struct foo * foo_add(struct foo *arg, int count); char * char_add(char *arg, int count); void print_foo(struct foo *arg); long foowork(struct foo **arg, int count); void callmeback(void (*thecallback)(int number)); void passingtheenv (const char *who, JNIEnv *env); #ifdef __cplusplus } /* extern "C" */ #endif std::shared_ptr get_sp(long CheckStr); void set_sp(struct foo *arg, std::shared_ptr); #endif /* INCLUDED_FOO_H */ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/main/native-package/src/hawtjni-example.h000066400000000000000000000024331475274123300310240ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ #ifndef INCLUDED_PLATFORM_H #define INCLUDED_PLATFORM_H #ifdef HAVE_CONFIG_H /* configure based build.. we will use what it discovered about the platform */ #include "config.h" #else #ifdef WIN32 /* Windows based build */ #define HAVE_STDLIB_H 1 #define HAVE_STRINGS_H 1 #endif #endif #include #ifdef __APPLE__ #import #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STRINGS_H #include #endif #include #include "foo.h" #include "stdio.h" class Range { public: int start; int end; Range() { start = 0; end = 0; } Range(const int s, const int e) { start = s; end = e; } void dump() { printf("range: %d-%d\n", start, end); } }; #endif /* INCLUDED_PLATFORM_H */ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/test/000077500000000000000000000000001475274123300221415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/test/java/000077500000000000000000000000001475274123300230625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/test/java/test/000077500000000000000000000000001475274123300240415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-example/src/test/java/test/ExampleTest.java000066400000000000000000000050641475274123300271440ustar00rootroot00000000000000package test; import static org.junit.Assert.*; import static test.Example.*; import org.fusesource.hawtjni.runtime.Callback; import org.fusesource.hawtjni.runtime.JNIEnv; import org.junit.Test; import static org.fusesource.hawtjni.runtime.PointerMath.*; import test.Example.bar; public class ExampleTest { static private int staticCallbackResult; private int instanceCallbackResult; @Test public void testPointerMath() { long values[] = new long[]{ 0, Long.MAX_VALUE, Long.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, 0+1, Long.MAX_VALUE+1, Long.MIN_VALUE+1, Integer.MAX_VALUE+1, Integer.MIN_VALUE+1, 0-1, Long.MAX_VALUE-1, Long.MIN_VALUE-1, Integer.MAX_VALUE-1, Integer.MIN_VALUE-1}; for( long i: values ) { assertEquals(char_add(i, 1), add(i, 1) ); assertEquals(char_add(i, -1), add(i, -1) ); } } @Test public void test() { // Allocate and initialize some memory on the heap. long ptr = malloc(bar.SIZEOF); memset(ptr, 0, bar.SIZEOF); // Configure an object that can be mapped to a C structure. bar expected = new bar(); expected.a = 35; expected.b = Integer.MAX_VALUE; System.arraycopy("Hello World!".getBytes(), 0, expected.c, 0, 5); // Marshal the object to the allocated heap memory memmove(ptr, expected, bar.SIZEOF); // Unmarshal the object from the allocated heap memory. bar acutal = new bar(); memmove(acutal, ptr, bar.SIZEOF); assertEquals(expected, acutal); Callback callback = new Callback(this, "instanceCallback", 1); callmeback(callback.getAddress()); assertEquals(69, instanceCallbackResult); callback.dispose(); long r1 = Range.Range(); Range.dump(r1); long r2 = Range.Range(10,100); Range.dump(r2); Range.delete(r1); Range.delete(r2); callback = new Callback(ExampleTest.class, "staticCallback", 1); callmeback(callback.getAddress()); assertEquals(69, staticCallbackResult); callback.dispose(); // Heap memory is not GCed, we must manually free it. free(ptr); passingtheenv("Hiram", null); } public long instanceCallback(long value) { this.instanceCallbackResult = (int) value; return 0; } static public long staticCallback(long value) { staticCallbackResult = (int) value; return 0; } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/000077500000000000000000000000001475274123300207265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/pom.xml000066400000000000000000000107121475274123300222440ustar00rootroot00000000000000 4.0.0 org.fusesource.hawtjni hawtjni-project 1.18 hawtjni-generator HawtJNI Generator This module contains the JNI code generation tools. org.fusesource.hawtjni hawtjni-runtime ${project.version} xbean-finder org.apache.xbean 4.16 org.ow2.asm asm 8.0.1 org.ow2.asm asm-commons 8.0.1 commons-cli commons-cli 1.0 org.apache.maven.plugins maven-shade-plugin 3.2.3 package shade junit:junit *:* META-INF/DEPENDENCIES META-INF/LICENSE* META-INF/NOTICE META-INF/MANIFEST.MF module-info.class org.apache.xbean:xbean-finder org/apache/xbean/asm7/original/commons/AsmConstants.class org/apache/xbean/asm7/original/commons/EmptyVisitor* jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/000077500000000000000000000000001475274123300215155ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/000077500000000000000000000000001475274123300224415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/000077500000000000000000000000001475274123300233625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/000077500000000000000000000000001475274123300241515ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/000077500000000000000000000000001475274123300263345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/000077500000000000000000000000001475274123300300005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/000077500000000000000000000000001475274123300317665ustar00rootroot00000000000000CleanupClass.java000077500000000000000000000105311475274123300351320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.io.*; import java.util.*; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIMethod; /** * * @author Hiram Chirino */ public abstract class CleanupClass extends JNIGenerator { String classSourcePath; String[] sourcePath; String classSource; HashMap files; int usedCount, unusedCount; String[] getArgNames(JNIMethod method) { int n_args = method.getParameters().size(); if (n_args == 0) return new String[0]; String name = method.getName(); String params = ""; int index = 0; while (true) { index = classSource.indexOf(name, index + 1); if (!Character.isWhitespace(classSource.charAt(index - 1))) continue; if (index == -1) return null; int parantesesStart = classSource.indexOf("(", index); if (classSource.substring(index + name.length(), parantesesStart).trim().length() == 0) { int parantesesEnd = classSource.indexOf(")", parantesesStart); params = classSource.substring(parantesesStart + 1, parantesesEnd); break; } } String[] names = new String[n_args]; StringTokenizer tk = new StringTokenizer(params, ","); for (int i = 0; i < names.length; i++) { String s = tk.nextToken().trim(); StringTokenizer tk1 = new StringTokenizer(s, " "); String s1 = null; while (tk1.hasMoreTokens()) { s1 = tk1.nextToken(); } names[i] = s1.trim(); } return names; } void loadClassSource() { if (classSourcePath == null) return; File f = new File(classSourcePath); classSource = loadFile(f); } void loadFiles() { // BAD - holds on to a lot of memory if (sourcePath == null) return; files = new HashMap(); for (int i = 0; i < sourcePath.length; i++) { File file = new File(sourcePath[i]); if (file.exists()) { if (!file.isDirectory()) { if (file.getAbsolutePath().endsWith(".java")) { files.put(file, loadFile(file)); } } else { loadDirectory(file); } } } } String loadFile(File file) { try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); StringBuffer str = new StringBuffer(); char[] buffer = new char[1024]; int read; while ((read = br.read(buffer)) != -1) { str.append(buffer, 0, read); } fr.close(); return str.toString(); } catch (IOException e) { e.printStackTrace(System.out); } return ""; } void loadDirectory(File file) { String[] entries = file.list(); for (int i = 0; i < entries.length; i++) { String entry = entries[i]; File f = new File(file, entry); if (!f.isDirectory()) { if (f.getAbsolutePath().endsWith(".java")) { files.put(f, loadFile(f)); } } else { loadDirectory(f); } } } public void generate(JNIClass clazz) { loadFiles(); loadClassSource(); } public void setSourcePath(String[] sourcePath) { this.sourcePath = sourcePath; files = null; } public void setClassSourcePath(String classSourcePath) { this.classSourcePath = classSourcePath; } } CleanupConstants.java000077500000000000000000000073761475274123300360560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIField; import org.fusesource.hawtjni.generator.model.ReflectClass; /** * * @author Hiram Chirino */ public class CleanupConstants extends CleanupClass { String getFieldValue(JNIField field) { String name = field.getName(); int index = 0; while (true) { index = classSource.indexOf(name, index + 1); if (index == -1) return null; int equalsIndex = classSource.indexOf("=", index); if (classSource.substring(index + name.length(), equalsIndex).trim().length() == 0) { int semiIndex = classSource.indexOf(";", equalsIndex); return classSource.substring(equalsIndex + 1, semiIndex).trim(); } } } public void generate(JNIClass clazz) { unusedCount = usedCount = 0; super.generate(clazz); List fields = clazz.getDeclaredFields(); generate(fields); output("used=" + usedCount + " unused=" + unusedCount + " total=" + (unusedCount + usedCount)); } public void generate(List fields) { sortFields(fields); for (JNIField field : fields) { if ((field.getModifiers() & Modifier.FINAL) == 0) continue; generate(field); } } public void generate(JNIField field) { String name = field.getName(); Collection values = files.values(); for (String str : values) { if (str.indexOf(name) != -1) { int modifiers = field.getModifiers(); String modifiersStr = Modifier.toString(modifiers); output("\t"); output(modifiersStr); if (modifiersStr.length() > 0) output(" "); output(field.getType().getTypeSignature3(false)); output(" "); output(field.getName()); output(" = "); output(getFieldValue(field)); outputln(";"); usedCount++; return; } } unusedCount++; // output("NOT USED=" + field.toString() + " \n"); } public static void main(String[] args) { if (args.length < 3) { System.out.println("Usage: java CleanupConstants "); return; } try { CleanupConstants gen = new CleanupConstants(); String clazzName = args[0]; String classSource = args[1]; String[] sourcePath = new String[args.length - 2]; System.arraycopy(args, 2, sourcePath, 0, sourcePath.length); Class clazz = Class.forName(clazzName); gen.setSourcePath(sourcePath); gen.setClassSourcePath(classSource); gen.generate(new ReflectClass(clazz)); } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } } CleanupNatives.java000077500000000000000000000075121475274123300355030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.util.*; import java.io.File; import java.lang.reflect.*; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIMethod; import org.fusesource.hawtjni.generator.model.ReflectClass; /** * * @author Hiram Chirino */ public class CleanupNatives extends CleanupClass { public CleanupNatives() { } public void generate(JNIClass clazz) { unusedCount = usedCount = 0; super.generate(clazz); List methods = clazz.getDeclaredMethods(); generate(methods); output("used=" + usedCount + " unused=" + unusedCount + " total=" + (unusedCount + usedCount)); } public void generate(List methods) { sortMethods(methods); for (JNIMethod method : methods) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; generate(method); } } public void generate(JNIMethod method) { String name = method.getName(); Set keys = files.keySet(); for (File key : keys) { String str = (String) files.get(key); if (str.indexOf(name) != -1) { // int modifiers = method.getModifiers(); // Class clazz = method.getDeclaringClass(); // String modifiersStr = Modifier.toString(modifiers); // output(modifiersStr); // if (modifiersStr.length() > 0) output(" "); // output(getTypeSignature3(method.getReturnType())); // output(" " ); // output(method.getName()); // output("("); // Class[] paramTypes = method.getParameterTypes(); // String[] paramNames = getArgNames(method); // for (int i = 0; i < paramTypes.length; i++) { // Class paramType = paramTypes[i]; // if (i != 0) output(", "); // String sig = getTypeSignature3(paramType); // if (clazz.getPackage().equals(paramType.getPackage())) sig = // getClassName(paramType); // output(sig); // output(" "); // output(paramNames[i]); // } // outputln(");"); usedCount++; return; } } unusedCount++; output("NOT USED=" + method.toString() + "\n"); } public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: java CleanupNatives "); return; } try { CleanupNatives gen = new CleanupNatives(); String clazzName = args[0]; String classSource = args[1]; String[] sourcePath = new String[args.length - 2]; System.arraycopy(args, 2, sourcePath, 0, sourcePath.length); Class clazz = Class.forName(clazzName); gen.setSourcePath(sourcePath); gen.setClassSourcePath(classSource); gen.generate(new ReflectClass(clazz)); } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } } ConstantsGenerator.java000077500000000000000000000047001475274123300364010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIField; import org.fusesource.hawtjni.generator.model.JNIType; import org.fusesource.hawtjni.generator.model.ReflectClass; /** * * @author Hiram Chirino */ public class ConstantsGenerator extends JNIGenerator { public void generate(JNIClass clazz) { List fields = clazz.getDeclaredFields(); generate(fields); } public void generate(List fields) { sortFields(fields); outputln("int main() {"); for (JNIField field : fields) { if ((field.getModifiers() & Modifier.FINAL) == 0) continue; generate(field); } outputln("}"); } public void generate(JNIField field) { JNIType type = field.getType(); output("\tprintf(\"public static final "); output(field.getType().getTypeSignature3(false)); output(" "); output(field.getName()); output(" = "); if (type.isType("java.lang.String") || type.isType("[B")) output("\"%s\""); else output("0x%x"); output(";\\n\", "); output(field.getName()); outputln(");"); } public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java ConstantsGenerator "); return; } try { ConstantsGenerator gen = new ConstantsGenerator(); for (String clazzName : args) { Class clazz = Class.forName(clazzName); gen.generate(new ReflectClass(clazz)); } } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } } DOMWriter.java000077500000000000000000000076411475274123300344010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Hiram Chirino */ public class DOMWriter { static String ENCONDING = "UTF8"; PrintStream out; String[] attributeFilter; String nodeFilter; public DOMWriter(PrintStream out) { this.out = new PrintStream(out); } String nodeName(Node node) { // TODO use getLocalName()? return node.getNodeName(); } boolean filter(Attr attr) { if (attributeFilter == null) return false; String name = attr.getNodeName(); for (int i = 0; i < attributeFilter.length; i++) { if (name.matches(attributeFilter[i])) return false; } return true; } void print(String str) { out.print(str); } void println() { out.println(); } public void print(Node node) { print(node, 0); } public void print(Node node, int level) { if (node == null) return; int type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE: { print(""); println(); print(((Document) node).getDocumentElement()); break; } case Node.ELEMENT_NODE: { Attr attrs[] = sort(node.getAttributes()); String name = nodeName(node); boolean gen = name.equals("arg") || name.equals("retval"); for (int i = 0; i < attrs.length && !gen; i++) { Attr attr = attrs[i]; if (nodeName(attr).startsWith(nodeFilter)) gen = true; } if (!gen) break; for (int i = 0; i < level; i++) print("\t"); print("<"); print(name); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; if (filter(attr)) continue; print(" "); print(nodeName(attr)); print("=\""); print(normalize(attr.getNodeValue())); print("\""); } print(">"); NodeList children = node.getChildNodes(); int count = 0; if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { if (children.item(i).getNodeType() == Node.ELEMENT_NODE) count++; } if (count > 0) println(); for (int i = 0; i < len; i++) { print(children.item(i), level + 1); } if (count > 0) { for (int i = 0; i < level; i++) print("\t"); } } print(""); println(); break; } } out.flush(); } Attr[] sort(NamedNodeMap attrs) { if (attrs == null) return new Attr[0]; Attr result[] = new Attr[attrs.getLength()]; for (int i = 0; i < result.length; i++) { result[i] = (Attr) attrs.item(i); } Arrays.sort(result, new Comparator() { public int compare(Node arg0, Node arg1) { return nodeName(arg0).compareTo(nodeName(arg1)); } }); return result; } String normalize(String s) { if (s == null) return ""; StringBuffer str = new StringBuffer(); for (int i = 0, length = s.length(); i < length; i++) { char ch = s.charAt(i); switch (ch) { case '"': str.append("\""); break; case '\r': case '\n': // FALL THROUGH default: str.append(ch); } } return str.toString(); } public void setNodeFilter(String filter) { nodeFilter = filter; } public void setAttributeFilter(String[] filter) { attributeFilter = filter; } }HawtJNI.java000077500000000000000000000412371475274123300340300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.xbean.finder.ClassFinder; import org.apache.xbean.finder.UrlSet; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.ReflectClass; import org.fusesource.hawtjni.generator.util.FileSupport; import org.fusesource.hawtjni.runtime.ClassFlag; import org.fusesource.hawtjni.runtime.JniClass; import static org.fusesource.hawtjni.generator.util.OptionBuilder.*; /** * * @author Hiram Chirino */ public class HawtJNI { public static final String END_YEAR_TAG = "%END_YEAR%"; private ProgressMonitor progress; private File nativeOutput = new File("."); // private File javaOutputDir = new File("."); private List classpaths = new ArrayList(); private List packages = new ArrayList(); private String name = "hawtjni_native"; private String copyright = ""; private boolean callbacks = true; /////////////////////////////////////////////////////////////////// // Command line entry point /////////////////////////////////////////////////////////////////// public static void main(String[] args) { String jv = System.getProperty("java.version").substring(0, 3); if (jv.compareTo("1.5") < 0) { System.err.println("This application requires jdk 1.5 or higher to run, the current java version is " + System.getProperty("java.version")); System.exit(-1); return; } HawtJNI app = new HawtJNI(); System.exit(app.execute(args)); } /////////////////////////////////////////////////////////////////// // Entry point for an embedded users who want to call us with // via command line arguments. /////////////////////////////////////////////////////////////////// public int execute(String[] args) { CommandLine cli = null; try { cli = new PosixParser().parse(createOptions(), args, true); } catch (ParseException e) { System.err.println( "Unable to parse command line options: " + e.getMessage() ); displayHelp(); return 1; } if( cli.hasOption("h") ) { displayHelp(); return 0; } if( cli.hasOption("v") ) { progress = new ProgressMonitor() { public void step() { } public void setTotal(int total) { } public void setMessage(String message) { System.out.println(message); } }; } name = cli.getOptionValue("n", "hawtjni_native"); nativeOutput = new File(cli.getOptionValue("o", ".")); // javaOutputDir = new File(cli.getOptionValue("j", ".")); String[] values = cli.getOptionValues("p"); if( values!=null ) { packages = Arrays.asList(values); } values = cli.getArgs(); if( values!=null ) { classpaths = Arrays.asList(values); } try { if( classpaths.isEmpty() ) { throw new UsageException("No classpath supplied."); } generate(); } catch (UsageException e) { System.err.println("Invalid usage: "+e.getMessage()); displayHelp(); return 1; } catch (Throwable e) { System.out.flush(); System.err.println("Unexpected failure:"); e.printStackTrace(); Set exceptions = new HashSet(); exceptions.add(e); for (int i = 0; i < 10; i++) { e = e.getCause(); if (e != null && exceptions.add(e)) { System.err.println("Reason: " + e); e.printStackTrace(); } else { break; } } return 2; } return 0; } /////////////////////////////////////////////////////////////////// // Entry point for an embedded users who want use us like a pojo /////////////////////////////////////////////////////////////////// public ProgressMonitor getProgress() { return progress; } public void setProgress(ProgressMonitor progress) { this.progress = progress; } public File getNativeOutput() { return nativeOutput; } public void setNativeOutput(File nativeOutput) { this.nativeOutput = nativeOutput; } public List getClasspaths() { return classpaths; } public void setClasspaths(List classpaths) { this.classpaths = classpaths; } public List getPackages() { return packages; } public void setPackages(List packages) { this.packages = packages; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setCopyright(String copyright) { this.copyright = copyright; } public boolean isCallbacks() { return callbacks; } public void setCallbacks(boolean enableCallbacks) { this.callbacks = enableCallbacks; } public void generate() throws UsageException, IOException { progress("Analyzing classes..."); ArrayList natives = new ArrayList(); ArrayList structs = new ArrayList(); findClasses(natives, structs); if( natives.isEmpty() && structs.isEmpty() ) { throw new RuntimeException("No @JniClass or @JniStruct annotated classes found."); } if (progress != null) { int nativeCount = 0; for (JNIClass clazz : natives) { nativeCount += clazz.getNativeMethods().size(); } int total = nativeCount * 4; total += natives.size() * (3); total += structs.size() * 2; progress.setTotal(total); } File file; nativeOutput.mkdirs(); progress("Generating..."); file = nativeFile(".c"); generate(new NativesGenerator(), natives, file); file = nativeFile("_stats.h"); generate(new StatsGenerator(true), natives, file); file = nativeFile("_stats.c"); generate(new StatsGenerator(false), natives, file); file = nativeFile("_structs.h"); generate(new StructsGenerator(true), structs, file); file = nativeFile("_structs.c"); generate(new StructsGenerator(false), structs, file); file = new File(nativeOutput, "hawtjni.h"); generateFromResource("hawtjni.h", file); file = new File(nativeOutput, "hawtjni.c"); generateFromResource("hawtjni.c", file); file = new File(nativeOutput, "hawtjni-callback.c"); if( callbacks ) { generateFromResource("hawtjni-callback.c", file); } else { file.delete(); } file = new File(nativeOutput, "windows"); file.mkdirs(); file = new File(file, "stdint.h"); generateFromResource("windows/stdint.h", file); progress("Done."); } /////////////////////////////////////////////////////////////////// // Helper methods /////////////////////////////////////////////////////////////////// private void findClasses(ArrayList jni, ArrayList structs) throws UsageException { ArrayList urls = new ArrayList(); for (String classpath : classpaths) { String[] fileNames = classpath.replace(';', ':').split(":"); for (String fileName : fileNames) { try { File file = new File(fileName); if( file.isDirectory() ) { urls.add(new URL(url(file)+"/")); } else { urls.add(new URL(url(file))); } } catch (Exception e) { throw new UsageException("Invalid class path. Not a valid file: "+fileName); } } } LinkedHashSet> jniClasses = new LinkedHashSet>(); try { URLClassLoader classLoader = new URLClassLoader(array(URL.class, urls), JniClass.class.getClassLoader()); UrlSet urlSet = new UrlSet(classLoader); urlSet = urlSet.excludeJavaHome(); ClassFinder finder = new ClassFinder(classLoader, urlSet.getUrls()); collectMatchingClasses(finder, JniClass.class, jniClasses); } catch (Exception e) { throw new RuntimeException(e); } for (Class clazz : jniClasses) { ReflectClass rc = new ReflectClass(clazz); if( rc.getFlag(ClassFlag.STRUCT) ) { structs.add(rc); } if( !rc.getNativeMethods().isEmpty() ) { jni.add(rc); } } } static private Options createOptions() { Options options = new Options(); options.addOption("h", "help", false, "Display help information"); options.addOption("v", "verbose", false, "Verbose generation"); options.addOption("o", "offline", false, "Work offline"); options.addOption(ob() .id("n") .name("name") .arg("value") .description("The base name of the library, used to determine generated file names. Defaults to 'hawtjni_native'.").op()); options.addOption(ob() .id("o") .name("native-output") .arg("dir") .description("Directory where generated native source code will be stored. Defaults to the current directory.").op()); // options.addOption(ob() // .id("j") // .name("java-output") // .arg("dir") // .description("Directory where generated native source code will be stored. Defaults to the current directory.").op()); options.addOption(ob() .id("p") .name("package") .arg("package") .description("Restrict looking for JNI classes to the specified package.").op()); return options; } private void displayHelp() { System.err.flush(); String app = System.getProperty("hawtjni.application"); if( app == null ) { try { URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); String[] split = location.toString().split("/"); if( split[split.length-1].endsWith(".jar") ) { app = split[split.length-1]; } } catch (Throwable e) { } if( app == null ) { app = getClass().getSimpleName(); } } // The commented out line is 80 chars long. We have it here as a visual reference // p(" "); p(); p("Usage: "+ app +" [options] "); p(); p("Description:"); p(); pw(" "+app+" is a code generator that produces the JNI code needed to implement java native methods.", 2); p(); p("Options:"); p(); PrintWriter out = new PrintWriter(System.out); HelpFormatter formatter = new HelpFormatter(); formatter.printOptions(out, 78, createOptions(), 2, 2); out.flush(); p(); p("Examples:"); p(); pw(" "+app+" -o build foo.jar bar.jar ", 2); pw(" "+app+" -o build foo.jar:bar.jar ", 2); pw(" "+app+" -o build -p org.mypackage foo.jar;bar.jar ", 2); p(); } private void p() { System.out.println(); } private void p(String s) { System.out.println(s); } private void pw(String message, int indent) { PrintWriter out = new PrintWriter(System.out); HelpFormatter formatter = new HelpFormatter(); formatter.printWrapped(out, 78, indent, message); out.flush(); } @SuppressWarnings("unchecked") private void collectMatchingClasses(ClassFinder finder, Class annotation, LinkedHashSet> collector) { List> annotated = finder.findAnnotatedClasses(annotation); for (Class clazz : annotated) { if( packages.isEmpty() ) { collector.add(clazz); } else { if( packages.contains(clazz.getPackage().getName()) ) { collector.add(clazz); } } } } private void progress(String message) { if (progress != null) { progress.setMessage(message); } } private void generate(JNIGenerator gen, ArrayList classes, File target) throws IOException { gen.setOutputName(name); gen.setClasses(classes); gen.setCopyright(getCopyright()); gen.setProgressMonitor(progress); ByteArrayOutputStream out = new ByteArrayOutputStream(); gen.setOutput(new PrintStream(out)); gen.generate(); if (out.size() > 0) { if( target.getName().endsWith(".c") && gen.isCPP ) { target = new File(target.getParentFile(), target.getName()+"pp"); } if( FileSupport.write(out.toByteArray(), target) ) { progress("Wrote: "+target); } } } private void generateFromResource(String resource, File target) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream is = getClass().getClassLoader().getResourceAsStream(resource); FileSupport.copy(is, out); String content = new String(out.toByteArray(), "UTF-8"); String[] parts = content.split(Pattern.quote("/* == HEADER-SNIP-LOCATION == */")); if( parts.length==2 ) { content = parts[1]; } out.reset(); PrintStream ps = new PrintStream(out); ps.print(JNIGenerator.fixDelimiter(getCopyright())); ps.print(JNIGenerator.fixDelimiter(content)); ps.close(); if( FileSupport.write(out.toByteArray(), target) ) { progress("Wrote: "+target); } } @SuppressWarnings("unchecked") private T[] array(Class type, ArrayList urls) { return urls.toArray((T[])Array.newInstance(type, urls.size())); } private String url(File file) throws IOException { return "file:"+(file.getCanonicalPath().replace(" ", "%20")); } @SuppressWarnings("serial") public static class UsageException extends Exception { public UsageException(String message) { super(message); } } private File nativeFile(String suffix) { return new File(nativeOutput, name+suffix); } public String getCopyright() { if (copyright == null) return ""; int index = copyright.indexOf(END_YEAR_TAG); if (index != -1) { String temp = copyright.substring(0, index); temp += Calendar.getInstance().get(Calendar.YEAR); temp += copyright.substring(index + END_YEAR_TAG.length()); copyright = temp; } return copyright; } } JNIGenerator.java000077500000000000000000000154151475274123300350520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2006 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIField; import org.fusesource.hawtjni.generator.model.JNIMethod; import org.fusesource.hawtjni.generator.model.JNIType; import org.fusesource.hawtjni.runtime.ClassFlag; /** * * @author Hiram Chirino */ public abstract class JNIGenerator { static final String delimiter = System.getProperty("line.separator"); static final String JNI64 = "JNI64"; ArrayList classes; String copyright = ""; boolean isCPP; PrintStream output = System.out; ProgressMonitor progress; private String outputName; static String fixDelimiter(String str) { if (delimiter.equals("\n")) { return str; } return str.replaceAll("\n", delimiter); } static String getFunctionName(JNIMethod method) { return getFunctionName(method, method.getParameterTypes()); } static String getFunctionName(JNIMethod method, List paramTypes) { if ((method.getModifiers() & Modifier.NATIVE) == 0) return method.getName(); String function = toC(method.getName()); if (!method.isNativeUnique()) { StringBuffer buffer = new StringBuffer(); buffer.append(function); buffer.append("__"); for (JNIType paramType : paramTypes) { buffer.append(toC(paramType.getTypeSignature(false))); } return buffer.toString(); } return function; } static String loadFile(String file) { try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); StringBuffer str = new StringBuffer(); char[] buffer = new char[1024]; int read; while ((read = br.read(buffer)) != -1) { str.append(buffer, 0, read); } fr.close(); return str.toString(); } catch (IOException e) { throw new RuntimeException("File not found:" + file, e); } } public static void sortMethods(List methods) { Collections.sort(methods, new Comparator() { public int compare(JNIMethod mth1, JNIMethod mth2) { int result = mth1.getName().compareTo(mth2.getName()); return result != 0 ? result : getFunctionName(mth1).compareTo(getFunctionName(mth2)); } }); } static void sortFields(List fields) { Collections.sort(fields, new Comparator() { public int compare(JNIField a, JNIField b) { return a.getName().compareTo(b.getName()); } }); } static void sortClasses(ArrayList classes) { Collections.sort(classes, new Comparator() { public int compare(JNIClass a, JNIClass b) { return a.getName().compareTo(b.getName()); } }); } static String toC(String str) { int length = str.length(); StringBuffer buffer = new StringBuffer(length * 2); for (int i = 0; i < length; i++) { char c = str.charAt(i); switch (c) { case '_': buffer.append("_1"); break; case ';': buffer.append("_2"); break; case '[': buffer.append("_3"); break; case '.': buffer.append("_"); break; case '/': buffer.append("_"); break; default: if( ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ) { buffer.append(c); } else { buffer.append(String.format("_0%04x",(int)c)); } } } return buffer.toString(); } public abstract void generate(JNIClass clazz); public void generateCopyright() { } public void generateIncludes() { } public void generate() { if (classes == null) return; generateCopyright(); generateIncludes(); sortClasses(classes); for (JNIClass clazz : classes) { if (clazz.getFlag(ClassFlag.CPP)) { isCPP = true; break; } } generate(classes); output.flush(); } protected void generate(ArrayList classes) { for (JNIClass clazz : classes) { if (clazz.getGenerate()) generate(clazz); if (progress != null) progress.step(); } } public boolean getCPP() { return isCPP; } public String getDelimiter() { return delimiter; } public PrintStream getOutput() { return output; } public String getOutputName() { return outputName; } public void setOutputName(String outputName) { this.outputName = outputName; } public ProgressMonitor getProgressMonitor() { return progress; } public void output(String str) { output.print(str); } public void outputln() { output(getDelimiter()); } public void outputln(String str) { output(str); output(getDelimiter()); } public void setClasses(ArrayList classes) { this.classes = classes; } public void setOutput(PrintStream output) { this.output = output; } public void setProgressMonitor(ProgressMonitor progress) { this.progress = progress; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } } LockGenerator.java000077500000000000000000000130741475274123300353210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIMethod; import org.fusesource.hawtjni.generator.model.JNIType; import org.fusesource.hawtjni.generator.model.ReflectClass; import org.fusesource.hawtjni.generator.model.ReflectType; /** * * @author Hiram Chirino */ public class LockGenerator extends CleanupClass { public LockGenerator() { } String getParams(JNIMethod method) { int n_args = method.getParameters().size(); if (n_args == 0) return ""; String name = method.getName(); String params = ""; int index = 0; while (true) { index = classSource.indexOf(name, index + 1); if (!Character.isWhitespace(classSource.charAt(index - 1))) continue; if (index == -1) return null; int parantesesStart = classSource.indexOf("(", index); if (classSource.substring(index + name.length(), parantesesStart).trim().length() == 0) { int parantesesEnd = classSource.indexOf(")", parantesesStart); params = classSource.substring(parantesesStart + 1, parantesesEnd); break; } } return params; } String getReturn(JNIMethod method) { JNIType returnType = method.getReturnType32(); if (!returnType.isType("int")) return returnType.getTypeSignature3(false); String modifierStr = Modifier.toString(method.getModifiers()); String name = method.getName(); Pattern p = Pattern.compile(modifierStr + ".*" + name + ".*(.*)"); Matcher m = p.matcher(classSource); if (m.find()) { String methodStr = classSource.substring(m.start(), m.end()); int index = methodStr.indexOf("/*long*/"); if (index != -1 && index < methodStr.indexOf(name)) { return new ReflectType(Integer.TYPE).getTypeSignature3(false) + " /*long*/"; } } return new ReflectType(Integer.TYPE).getTypeSignature3(false); } public void generate(JNIClass clazz) { super.generate(clazz); generate(clazz.getDeclaredMethods()); } public void generate(List methods) { sortMethods(methods); for (JNIMethod method : methods) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; generate(method); } } public void generate(JNIMethod method) { int modifiers = method.getModifiers(); boolean lock = (modifiers & Modifier.SYNCHRONIZED) != 0; String returnStr = getReturn(method); String paramsStr = getParams(method); if (lock) { String modifiersStr = Modifier.toString(modifiers & ~Modifier.SYNCHRONIZED); output(modifiersStr); if (modifiersStr.length() > 0) output(" "); output(returnStr); output(" _"); output(method.getName()); output("("); output(paramsStr); outputln(");"); } String modifiersStr = Modifier.toString(modifiers & ~(Modifier.SYNCHRONIZED | (lock ? Modifier.NATIVE : 0))); output(modifiersStr); if (modifiersStr.length() > 0) output(" "); output(returnStr); output(" "); output(method.getName()); output("("); output(paramsStr); output(")"); if (lock) { outputln(" {"); outputln("\tlock.lock();"); outputln("\ttry {"); output("\t\t"); if (!method.getReturnType32().isType("void")) { output("return "); } output("_"); output(method.getName()); output("("); String[] paramNames = getArgNames(method); for (int i = 0; i < paramNames.length; i++) { if (i != 0) output(", "); output(paramNames[i]); } outputln(");"); outputln("\t} finally {"); outputln("\t\tlock.unlock();"); outputln("\t}"); outputln("}"); } else { outputln(";"); } } public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: java LockGenerator "); return; } try { LockGenerator gen = new LockGenerator(); String clazzName = args[0]; String classSource = args[1]; Class clazz = Class.forName(clazzName); gen.setClassSourcePath(classSource); gen.generate(new ReflectClass(clazz)); } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } } MacGenerator.java000077500000000000000000002076251475274123300351400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.parsers.DocumentBuilderFactory; import org.fusesource.hawtjni.generator.HawtJNI.UsageException; import org.fusesource.hawtjni.generator.util.FileSupport; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * * @author Hiram Chirino */ public class MacGenerator { String[] xmls; Document[] documents; String outputDir, mainClassName; String delimiter = System.getProperty("line.separator"); PrintStream out; public MacGenerator() { } static void list(File path, ArrayList list) { if (path == null) return; File[] frameworks = path.listFiles(); if (frameworks == null) return; for (int i = 0; i < frameworks.length; i++) { File file = frameworks[i]; String name = file.getName(); int index = name.lastIndexOf("."); if (index != -1) { String xml = file.getAbsolutePath() + "/Resources/BridgeSupport/" + name.substring(0, index) + "Full.bridgesupport"; if (new File(xml).exists()) { list.add(xml); } } } } int getLevel(Node node) { int level = 0; while (node != null) { level++; node = node.getParentNode(); } return level; } void merge(Document document, Document extraDocument) { if (extraDocument == null) return; /* Build a lookup table for extraDocument */ HashMap extras = new HashMap(); buildLookup(extraDocument, extras); /* * Merge attributes on existing elements building a lookup table for * document */ HashMap lookup = new HashMap(); merge(document, extras, lookup); /* * Merge new elements. Extras at this point contains only elements that * were not found in the document. */ ArrayList sortedNodes = Collections.list(Collections.enumeration(extras.values())); Collections.sort(sortedNodes, new Comparator() { public int compare(Node arg0, Node arg1) { int compare = getLevel(arg0) - getLevel(arg1); if (compare == 0) { return (arg0).getNodeName().compareTo((arg1).getNodeName()); } return compare; } }); String delimiter = System.getProperty("line.separator"); for (Iterator iterator = sortedNodes.iterator(); iterator.hasNext();) { Node node = iterator.next(); String name = node.getNodeName(); if ("arg".equals(name) || "retval".equals(name)) { if (!sortedNodes.contains(node.getParentNode())) continue; } Node parent = lookup.get(getKey(node.getParentNode())); Element element = document.createElement(node.getNodeName()); String text = parent.getChildNodes().getLength() == 0 ? delimiter : ""; for (int i = 0, level = getLevel(parent) - 1; i < level; i++) { text += " "; } parent.appendChild(document.createTextNode(text)); parent.appendChild(element); parent.appendChild(document.createTextNode(delimiter)); NamedNodeMap attributes = node.getAttributes(); for (int j = 0, length = attributes.getLength(); j < length; j++) { Node attr = (Node) attributes.item(j); element.setAttribute(attr.getNodeName(), attr.getNodeValue()); } lookup.put(getKey(element), element); } } public void generate(ProgressMonitor progress) throws UsageException { if (progress != null) { progress.setTotal(3); progress.setMessage("extra attributes..."); } generateExtraAttributes(); if (progress != null) { progress.step(); progress.setMessage(mainClassName); } generateMainClass(); if (progress != null) { progress.step(); progress.setMessage("classes..."); } generateClasses(); if (progress != null) { progress.step(); progress.setMessage("Done."); } } String fixDelimiter(String str) { if (delimiter.equals("\n")) return str; int index = 0, length = str.length(); StringBuffer buffer = new StringBuffer(); while (index != -1) { int start = index; index = str.indexOf('\n', start); if (index == -1) { buffer.append(str.substring(start, length)); } else { buffer.append(str.substring(start, index)); buffer.append(delimiter); index++; } } return buffer.toString(); } void generateMethods(String className, ArrayList methods) { for (Node method : methods) { NamedNodeMap mthAttributes = method.getAttributes(); String sel = mthAttributes.getNamedItem("selector").getNodeValue(); out("public "); boolean isStatic = isStatic(method); if (isStatic) out("static "); Node returnNode = getReturnNode(method.getChildNodes()); if (getType(returnNode).equals("void")) returnNode = null; String returnType = "", returnType64 = ""; if (returnNode != null) { String type = returnType = getJavaType(returnNode), type64 = returnType64 = getJavaType64(returnNode); out(type); if (!type.equals(type64)) { out(" /*"); out(type64); out("*/"); } out(" "); } else { out("void "); } String methodName = sel; if (isUnique(method, methods)) { int index = methodName.indexOf(":"); if (index != -1) methodName = methodName.substring(0, index); } else { // TODO improve this selector methodName = methodName.replaceAll(":", "_"); if (isStatic) methodName = "static_" + methodName; } out(methodName); out("("); NodeList params = method.getChildNodes(); boolean first = true; for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { NamedNodeMap paramAttributes = param.getAttributes(); if (!first) out(", "); String type = getJavaType(param), type64 = getJavaType64(param); out(type); if (!type.equals(type64)) { out(" /*"); out(type64); out("*/"); } first = false; out(" "); String paramName = paramAttributes.getNamedItem("name").getNodeValue(); if (paramName.length() == 0) paramName = "arg" + paramAttributes.getNamedItem("index").getNodeValue(); if (paramName.equals("boolean")) paramName = "b"; out(paramName); } } out(") {"); outln(); if (returnNode != null && isStruct(returnNode)) { out("\t"); out(returnType); out(" result = new "); out(returnType); out("();"); outln(); out("\tOS.objc_msgSend_stret(result, "); } else if (returnNode != null && isBoolean(returnNode)) { out("\treturn "); out("OS.objc_msgSend_bool("); } else if (returnNode != null && isFloatingPoint(returnNode)) { out("\treturn "); if (returnType.equals("float")) out("(float)"); out("OS.objc_msgSend_fpret("); } else if (returnNode != null && isObject(returnNode)) { out("\tint /*long*/ result = OS.objc_msgSend("); } else { if (returnNode != null) { out("\treturn "); if ((returnType.equals("int") && returnType64.equals("int")) || !returnType.equals("int")) { out("("); out(returnType); out(")"); } if (returnType.equals("int") && returnType64.equals("int")) { out("/*64*/"); } } else { out("\t"); } out("OS.objc_msgSend("); } if (isStatic) { out("OS.class_"); out(className); } else { out("this.id"); } out(", OS."); out(getSelConst(sel)); first = false; for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { NamedNodeMap paramAttributes = param.getAttributes(); if (!first) out(", "); first = false; String paramName = paramAttributes.getNamedItem("name").getNodeValue(); if (paramName.length() == 0) paramName = "arg" + paramAttributes.getNamedItem("index").getNodeValue(); if (paramName.equals("boolean")) paramName = "b"; if (isObject(param)) { out(paramName); out(" != null ? "); out(paramName); out(".id : 0"); } else { out(paramName); } } } out(")"); out(";"); outln(); if (returnNode != null && isObject(returnNode)) { if (!isStatic && returnType.equals(className)) { out("\treturn result == this.id ? this : (result != 0 ? new "); out(returnType); out("(result) : null);"); } else { out("\treturn result != 0 ? new "); NamedNodeMap attributes = returnNode.getAttributes(); Node hawtjni_alloc = attributes.getNamedItem("hawtjni_alloc"); if (hawtjni_alloc != null && hawtjni_alloc.getNodeValue().equals("true")) { out(className); } else { out(returnType); } out("(result) : null;"); } outln(); } else if (returnNode != null && isStruct(returnNode)) { out("\treturn result;"); outln(); } out("}"); outln(); outln(); } } void generateExtraMethods(String className) { /* Empty constructor */ out("public "); out(className); out("() {"); outln(); out("\tsuper();"); outln(); out("}"); outln(); outln(); /* pointer constructor */ out("public "); out(className); out("(int /*long*/ id) {"); outln(); out("\tsuper(id);"); outln(); out("}"); outln(); outln(); /* object constructor */ out("public "); out(className); out("(id id) {"); outln(); out("\tsuper(id);"); outln(); out("}"); outln(); outln(); /* NSObject helpers */ if (className.equals("NSObject")) { out("public NSObject alloc() {"); outln(); out("\tthis.id = OS.objc_msgSend(objc_getClass(), OS.sel_alloc);"); outln(); out("\treturn this;"); outln(); out("}"); outln(); outln(); } /* NSString helpers */ if (className.equals("NSString")) { /* Get java string */ out("public String getString() {"); outln(); out("\tchar[] buffer = new char[(int)/*64*/length()];"); outln(); out("\tgetCharacters(buffer);"); outln(); out("\treturn new String(buffer);"); outln(); out("}"); outln(); outln(); /* create NSString */ out("public NSString initWithString(String str) {"); outln(); out("\tchar[] buffer = new char[str.length()];"); outln(); out("\tstr.getChars(0, buffer.length, buffer, 0);"); outln(); out("\treturn initWithCharacters(buffer, buffer.length);"); outln(); out("}"); outln(); outln(); out("public static NSString stringWith(String str) {"); outln(); out("\tchar[] buffer = new char[str.length()];"); outln(); out("\tstr.getChars(0, buffer.length, buffer, 0);"); outln(); out("\treturn stringWithCharacters(buffer, buffer.length);"); outln(); out("}"); outln(); outln(); } } static class NodeEntry { private final Node parent; private final ArrayList children; public NodeEntry(Node parent, ArrayList children) { this.parent = parent; this.children = children; } } TreeMap getGeneratedClasses() { TreeMap classes = new TreeMap(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("class".equals(node.getNodeName()) && getGen(node)) { ArrayList methods; String name = node.getAttributes().getNamedItem("name").getNodeValue(); NodeEntry clazz = classes.get(name); if (clazz == null) { methods = new ArrayList(); classes.put(name, new NodeEntry(node, methods)); } else { methods = clazz.children; } NodeList methodList = node.getChildNodes(); for (int j = 0; j < methodList.getLength(); j++) { Node method = methodList.item(j); if ("method".equals(method.getNodeName()) && getGen(method)) { methods.add(method); } } } } } return classes; } void copyClassMethodsDown(final Map classes) { ArrayList sortedClasses = Collections.list(Collections.enumeration(classes.values())); Collections.sort(sortedClasses, new Comparator() { int getHierarchyLevel(Node node) { String superclass = getSuperclassName(node); int level = 0; while (!superclass.equals("id")) { level++; superclass = getSuperclassName(classes.get(superclass).parent); } return level; } public int compare(NodeEntry arg0, NodeEntry arg1) { return getHierarchyLevel(arg0.parent) - getHierarchyLevel(arg1.parent); } }); for (NodeEntry clazz : sortedClasses) { Node node = (Node) clazz.parent; ArrayList methods = (ArrayList) clazz.children; NodeEntry superclass = classes.get(getSuperclassName(node)); if (superclass != null) { for (Node method : superclass.children) { if (isStatic(method)) { methods.add(method); } } } } } String getSuperclassName(Node node) { NamedNodeMap attributes = node.getAttributes(); Node superclass = attributes.getNamedItem("hawtjni_superclass"); if (superclass != null) { return superclass.getNodeValue(); } else { Node name = attributes.getNamedItem("name"); if (name.getNodeValue().equals("NSObject")) { return "id"; } else { return "NSObject"; } } } void generateClasses() { TreeMap classes = getGeneratedClasses(); copyClassMethodsDown(classes); Set classNames = classes.keySet(); for (Iterator iterator = classNames.iterator(); iterator.hasNext();) { ByteArrayOutputStream out = new ByteArrayOutputStream(); this.out = new PrintStream(out); // out(fixDelimiter(metaData.getCopyright())); String className = iterator.next(); NodeEntry clazz = classes.get(className); Node node = clazz.parent; ArrayList methods = clazz.children; out("package "); String packageName = getPackageName(mainClassName); out(packageName); out(";"); outln(); outln(); out("public class "); out(className); out(" extends "); out(getSuperclassName(node)); out(" {"); outln(); outln(); generateExtraMethods(className); generateMethods(className, methods); out("}"); outln(); String fileName = outputDir + packageName.replace('.', '/') + "/" + className + ".java"; try { out.flush(); if (out.size() > 0) { FileSupport.write(out.toByteArray(), new File(fileName)); } } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } out = null; } } void generateExtraAttributes() { Document[] documents = getDocuments(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null || !getGen(document.getDocumentElement())) continue; saveExtraAttributes(xmls[x], document); } } void generateMainClass() { ByteArrayOutputStream out = new ByteArrayOutputStream(); this.out = new PrintStream(out); String header = "", footer = ""; String fileName = outputDir + mainClassName.replace('.', '/') + ".java"; FileInputStream is = null; try { InputStreamReader input = new InputStreamReader(new BufferedInputStream(is = new FileInputStream(fileName))); StringBuffer str = new StringBuffer(); char[] buffer = new char[4096]; int read; while ((read = input.read(buffer)) != -1) { str.append(buffer, 0, read); } String section = "/** This section is auto generated */"; int start = str.indexOf(section) + section.length(); int end = str.indexOf(section, start); header = str.substring(0, start); footer = str.substring(end); } catch (IOException e) { } finally { try { if (is != null) is.close(); } catch (IOException e) { } } out(header); outln(); outln(); out("/** Custom callbacks */"); outln(); generateCustomCallbacks(); outln(); out("/** Classes */"); outln(); generateClassesConst(); outln(); out("/** Protocols */"); outln(); generateProtocolsConst(); outln(); out("/** Selectors */"); outln(); generateSelectorsConst(); outln(); out("/** Constants */"); outln(); generateEnums(); outln(); out("/** Globals */"); outln(); generateConstants(); outln(); out("/** Functions */"); outln(); outln(); generateFunctions(); outln(); out("/** Super Sends */"); outln(); generateSends(true); outln(); out("/** Sends */"); outln(); generateSends(false); outln(); generateStructNatives(); outln(); out(footer); try { out.flush(); if (out.size() > 0) { FileSupport.write(out.toByteArray(), new File(fileName)); } } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } public Document[] getDocuments() { if (documents == null) { String[] xmls = getXmls(); documents = new Document[xmls.length]; for (int i = 0; i < xmls.length; i++) { String xmlPath = xmls[i]; Document document = documents[i] = getDocument(xmlPath); if (document == null) continue; if (mainClassName != null && outputDir != null) { String packageName = getPackageName(mainClassName); String extrasPath = outputDir + packageName.replace('.', '/') + "/" + getFileName(xmlPath) + ".extras"; merge(document, getDocument(extrasPath)); } } } return documents; } public String[] getXmls() { if (xmls == null || xmls.length == 0) { ArrayList array = new ArrayList(); list(new File("/System/Library/Frameworks"), array); list(new File("/System/Library/Frameworks/CoreServices.framework/Frameworks"), array); list(new File("/System/Library/Frameworks/ApplicationServices.framework/Frameworks"), array); Collections.sort(array, new Comparator() { public int compare(String o1, String o2) { return new File(o1).getName().compareTo(new File(o2).getName()); } }); xmls = array.toArray(new String[array.size()]); } return xmls; } void saveExtraAttributes(String xmlPath, Document document) { try { String packageName = getPackageName(mainClassName); String fileName = outputDir + packageName.replace('.', '/') + "/" + getFileName(xmlPath) + ".extras"; ByteArrayOutputStream out = new ByteArrayOutputStream(); DOMWriter writer = new DOMWriter(new PrintStream(out)); String[] names = getIDAttributeNames(); String[] filter = new String[names.length + 2]; filter[0] = "class_method"; filter[1] = "hawtjni_.*"; System.arraycopy(names, 0, filter, 2, names.length); writer.setAttributeFilter(filter); writer.setNodeFilter("hawtjni_"); writer.print(document); if (out.size() > 0) { FileSupport.write(out.toByteArray(), new File(fileName)); } } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } public void setOutputDir(String dir) { if (dir != null) { if (!dir.endsWith("\\") && !dir.endsWith("/")) { dir += "/"; } } this.outputDir = dir; } public void setXmls(String[] xmls) { this.xmls = xmls; this.documents = null; } public void setMainClass(String mainClassName) { this.mainClassName = mainClassName; } Document getDocument(String xmlPath) { try { InputStream is = null; if (xmlPath.indexOf(File.separatorChar) == -1) is = getClass().getResourceAsStream(xmlPath); if (is == null) is = new BufferedInputStream(new FileInputStream(xmlPath)); if (is != null) return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(is)); } catch (Exception e) { // e.printStackTrace(); } return null; } public String[] getExtraAttributeNames(Node node) { String name = node.getNodeName(); if (name.equals("method")) { return new String[] { "hawtjni_gen_super_msgSend", "hawtjni_gen_custom_callback" }; } else if (name.equals("function")) { NamedNodeMap attribs = node.getAttributes(); if (attribs != null && attribs.getNamedItem("variadic") != null) { return new String[] { "hawtjni_variadic_count", "hawtjni_variadic_java_types" }; } } else if (name.equals("class")) { return new String[] { "hawtjni_superclass" }; } else if (name.equals("retval")) { return new String[] { "hawtjni_java_type", "hawtjni_java_type64", "hawtjni_alloc" }; } else if (name.equals("arg")) { return new String[] { "hawtjni_java_type", "hawtjni_java_type64" }; } return new String[0]; } public String getFileName(String xmlPath) { File file = new File(xmlPath); return file.getName(); } String getKey(Node node) { StringBuffer buffer = new StringBuffer(); while (node != null) { if (buffer.length() > 0) buffer.append("_"); String name = node.getNodeName(); StringBuffer key = new StringBuffer(name); Node nameAttrib = getIDAttribute(node); if (nameAttrib != null) { key.append("-"); key.append(nameAttrib.getNodeValue()); } NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { boolean isStatic = attributes.getNamedItem("class_method") != null; if (isStatic) key.append("-static"); } buffer.append(key.reverse()); node = node.getParentNode(); } buffer.reverse(); return buffer.toString(); } public Node getIDAttribute(Node node) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) return null; String[] names = getIDAttributeNames(); for (int i = 0; i < names.length; i++) { Node nameAttrib = attributes.getNamedItem(names[i]); if (nameAttrib != null) return nameAttrib; } return null; } public String[] getIDAttributeNames() { return new String[] { "name", "selector", "path", }; } void merge(Node node, HashMap extras, HashMap docLookup) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node childNode = list.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { String key = getKey(childNode); if (docLookup != null && docLookup.get(key) == null) { docLookup.put(key, childNode); } Node extra = extras.remove(key); if (extra != null) { NamedNodeMap attributes = extra.getAttributes(); for (int j = 0, length = attributes.getLength(); j < length; j++) { Node attr = (Node) attributes.item(j); String name = attr.getNodeName(); if (name.startsWith("hawtjni_")) { ((Element) childNode).setAttribute(name, attr.getNodeValue()); } } } } merge(childNode, extras, docLookup); } } void out(String str) { PrintStream out = this.out; if (out == null) out = System.out; out.print(str); } void outln() { PrintStream out = this.out; if (out == null) out = System.out; out.println(); } void generateConstants() { for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("constant".equals(node.getNodeName())) { if (getGen(node)) { NamedNodeMap attributes = node.getAttributes(); String constName = attributes.getNamedItem("name").getNodeValue(); out("/** @method flags=const */"); outln(); out("public static final native "); String type = getType(node), type64 = getType64(node); out(type); if (!type.equals(type64)) { out(" /*"); out(type64); out("*/"); } out(" "); out(constName); out("();"); outln(); if (attributes.getNamedItem("declared_type").getNodeValue().equals("NSString*")) { out("public static final NSString "); out(constName); out(" = new NSString("); out(constName); out("());"); outln(); } } } } } } void generateEnums() { for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("enum".equals(node.getNodeName())) { if (getGen(node)) { NamedNodeMap attributes = node.getAttributes(); Node valueNode = attributes.getNamedItem("value"); if (valueNode != null) { String value = valueNode.getNodeValue(); out("public static final "); boolean isLong = false; if (value.indexOf('.') != -1) { out("double "); } else { try { Integer.parseInt(value); out("int "); } catch (NumberFormatException e) { isLong = true; out("long "); } } out(attributes.getNamedItem("name").getNodeValue()); out(" = "); out(value); if (isLong && !value.endsWith("L")) out("L"); out(";"); outln(); } } } } } } boolean getGen(Node node) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) return false; Node gen = attributes.getNamedItem("hawtjni_gen"); return gen != null && !gen.getNodeValue().equals("false"); } boolean getGenSuper(Node node) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) return false; Node gen = attributes.getNamedItem("hawtjni_gen_super_msgSend"); return gen != null && !gen.getNodeValue().equals("false"); } boolean getGenCallback(Node node) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) return false; Node gen = attributes.getNamedItem("hawtjni_gen_custom_callback"); return gen != null && !gen.getNodeValue().equals("false"); } boolean isStatic(Node node) { NamedNodeMap attributes = node.getAttributes(); Node isStatic = attributes.getNamedItem("class_method"); return isStatic != null && isStatic.getNodeValue().equals("true"); } boolean isStruct(Node node) { NamedNodeMap attributes = node.getAttributes(); String code = attributes.getNamedItem("type").getNodeValue(); return code.startsWith("{"); } boolean isFloatingPoint(Node node) { NamedNodeMap attributes = node.getAttributes(); String code = attributes.getNamedItem("type").getNodeValue(); return code.equals("f") || code.equals("d"); } boolean isObject(Node node) { NamedNodeMap attributes = node.getAttributes(); String code = attributes.getNamedItem("type").getNodeValue(); return code.equals("@"); } boolean isBoolean(Node node) { NamedNodeMap attributes = node.getAttributes(); String code = attributes.getNamedItem("type").getNodeValue(); return code.equals("B"); } void buildLookup(Node node, HashMap table) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node childNode = list.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { String key = getKey(childNode); if (table.get(key) == null) table.put(key, childNode); buildLookup(childNode, table); } } } boolean isUnique(Node method, ArrayList methods) { String methodName = method.getAttributes().getNamedItem("selector").getNodeValue(); String signature = ""; NodeList params = method.getChildNodes(); for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { signature += getJavaType(param); } } int index = methodName.indexOf(":"); if (index != -1) methodName = methodName.substring(0, index); for (Node node : methods) { NamedNodeMap attributes = node.getAttributes(); Node otherSel = null; if (attributes != null) otherSel = attributes.getNamedItem("selector"); if (node != method && otherSel != null) { String otherName = otherSel.getNodeValue(); index = otherName.indexOf(":"); if (index != -1) otherName = otherName.substring(0, index); if (methodName.equals(otherName)) { NodeList otherParams = node.getChildNodes(); String otherSignature = ""; for (int k = 0; k < otherParams.getLength(); k++) { Node param = otherParams.item(k); if ("arg".equals(param.getNodeName())) { otherSignature += getJavaType(param); } } if (signature.equals(otherSignature)) { return false; } } } } return true; } void generateSelectorsConst() { TreeSet set = new TreeSet(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("class".equals(node.getNodeName()) || "informal_protocol".equals(node.getNodeName())) { if (getGen(node)) { NodeList methods = node.getChildNodes(); for (int j = 0; j < methods.getLength(); j++) { Node method = methods.item(j); if (getGen(method)) { NamedNodeMap mthAttributes = method.getAttributes(); String sel = mthAttributes.getNamedItem("selector").getNodeValue(); set.add(sel); } } } } } } set.add("alloc"); for (Iterator iterator = set.iterator(); iterator.hasNext();) { String sel = iterator.next(); String selConst = getSelConst(sel); out("public static final int /*long*/ "); out(selConst); out(" = "); out("sel_registerName(\""); out(sel); out("\");"); outln(); } } void generateStructNatives() { TreeSet set = new TreeSet(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("struct".equals(node.getNodeName()) && getGen(node)) { set.add(getIDAttribute(node).getNodeValue()); } } } out("/** Sizeof natives */"); outln(); for (Iterator iterator = set.iterator(); iterator.hasNext();) { String struct = iterator.next(); out("public static final native int "); out(struct); out("_sizeof();"); outln(); } outln(); out("/** Memmove natives */"); outln(); outln(); for (Iterator iterator = set.iterator(); iterator.hasNext();) { String struct = iterator.next(); out("/**"); outln(); out(" * @param dest cast=(void *),flags=no_in critical"); outln(); out(" * @param src cast=(void *),flags=critical"); // out(" * @param src cast=(void *),flags=no_out critical"); outln(); out(" */"); outln(); out("public static final native void memmove("); out("int /*long*/ dest, "); out(struct); out(" src, int /*long*/ size);"); outln(); out("/**"); outln(); out(" * @param dest cast=(void *),flags=no_in critical"); outln(); out(" * @param src cast=(void *),flags=critical"); // out(" * @param src cast=(void *),flags=no_out critical"); outln(); out(" */"); outln(); out("public static final native void memmove("); out(struct); out(" dest, int /*long*/ src, int /*long*/ size);"); outln(); } } String buildSend(Node method, boolean tags, boolean only64, boolean superCall) { Node returnNode = getReturnNode(method.getChildNodes()); StringBuffer buffer = new StringBuffer(); buffer.append("public static final native "); if (returnNode != null && isStruct(returnNode)) { buffer.append("void "); buffer.append(superCall ? "objc_msgSendSuper_stret" : "objc_msgSend_stret"); buffer.append("("); buffer.append(getJavaType(returnNode)); buffer.append(" result, "); } else if (returnNode != null && isFloatingPoint(returnNode)) { buffer.append("double "); buffer.append(superCall ? "objc_msgSendSuper_fpret" : "objc_msgSend_fpret"); buffer.append("("); } else if (returnNode != null && isBoolean(returnNode)) { buffer.append("boolean "); buffer.append(superCall ? "objc_msgSendSuper_bool" : "objc_msgSend_bool"); buffer.append("("); } else { if (only64) { buffer.append("long"); } else { if (tags) { buffer.append("int /*long*/"); } else { buffer.append("int"); } } buffer.append(" "); buffer.append(superCall ? "objc_msgSendSuper" : "objc_msgSend"); buffer.append("("); } if (superCall) { if (only64) { buffer.append("objc_super superId, long sel"); } else { if (tags) { buffer.append("objc_super superId, int /*long*/ sel"); } else { buffer.append("objc_super superId, int sel"); } } } else { if (only64) { buffer.append("long id, long sel"); } else { if (tags) { buffer.append("int /*long*/ id, int /*long*/ sel"); } else { buffer.append("int id, int sel"); } } } NodeList params = method.getChildNodes(); boolean first = false; int count = 0; for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { if (!first) buffer.append(", "); if (isStruct(param)) { buffer.append(getJavaType(param)); } else { String type = getType(param), type64 = getType64(param); buffer.append(only64 ? type64 : type); if (!only64 && tags && !type.equals(type64)) { buffer.append(" /*"); buffer.append(type64); buffer.append("*/"); } } first = false; buffer.append(" arg"); buffer.append(String.valueOf(count++)); } } buffer.append(");"); return buffer.toString(); } String getCType(Node node) { NamedNodeMap attributes = node.getAttributes(); return attributes.getNamedItem("declared_type").getNodeValue(); } Node findNSObjectMethod(Node method) { NamedNodeMap methodAttributes = method.getAttributes(); String selector = methodAttributes.getNamedItem("selector").getNodeValue(); NodeList list = method.getParentNode().getParentNode().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node cls = list.item(i); if ("class".equals(cls.getNodeName())) { NamedNodeMap classAttributes = cls.getAttributes(); if ("NSObject".equals(classAttributes.getNamedItem("name").getNodeValue())) { NodeList methods = cls.getChildNodes(); for (int j = 0; j < methods.getLength(); j++) { Node mth = methods.item(j); if ("method".equals(mth.getNodeName())) { NamedNodeMap mthAttributes = mth.getAttributes(); if (selector.equals(mthAttributes.getNamedItem("selector").getNodeValue())) { return mth; } } } } } } return null; } void generateCustomCallbacks() { TreeMap set = new TreeMap(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (("class".equals(node.getNodeName()) || "informal_protocol".equals(node.getNodeName())) && getGen(node)) { NodeList methods = node.getChildNodes(); for (int j = 0; j < methods.getLength(); j++) { Node method = methods.item(j); if ("method".equals(method.getNodeName()) && getGen(method) && getGenCallback(method)) { NamedNodeMap mthAttributes = method.getAttributes(); String sel = mthAttributes.getNamedItem("selector").getNodeValue(); set.put(sel, method); } } } } } for (Iterator iterator = set.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); Node method = set.get(key); if ("informal_protocol".equals(method.getParentNode().getNodeName())) { method = findNSObjectMethod(method); if (method == null) continue; } String nativeMth = key.replaceAll(":", "_"); out("/** @method callback_types="); Node returnNode = getReturnNode(method.getChildNodes()); out(returnNode == null ? "void" : getCType(returnNode)); out(";id;SEL;"); NodeList params = method.getChildNodes(); for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { out(getCType(param)); out(";"); } } out(",callback_flags="); out(returnNode != null && isStruct(returnNode) ? "struct" : "none"); out(";none;none;"); for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { out(isStruct(param) ? "struct" : "none"); out(";"); } } out(" */"); outln(); out("public static final native int /*long*/ CALLBACK_"); out(nativeMth); out("(int /*long*/ func);"); outln(); } } void generateSends(boolean superCall) { TreeMap set = new TreeMap(); TreeMap set64 = new TreeMap(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("class".equals(node.getNodeName()) && getGen(node)) { NodeList methods = node.getChildNodes(); for (int j = 0; j < methods.getLength(); j++) { Node method = methods.item(j); if ("method".equals(method.getNodeName()) && getGen(method) && (!superCall || getGenSuper(method))) { String code = buildSend(method, false, false, superCall); String code64 = buildSend(method, false, true, superCall); if (set.get(code) == null) { set.put(code, method); } if (set64.get(code64) == null) { set64.put(code64, method); } } } } } } outln(); TreeMap tagsSet = new TreeMap(); for (Iterator iterator = set.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); Node method = set.get(key); String tagCode = buildSend(method, false, true, superCall); if (set64.get(tagCode) != null) { tagsSet.put(key, method); iterator.remove(); set64.remove(tagCode); } } TreeMap all = new TreeMap(); for (Iterator iterator = tagsSet.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); Node method = tagsSet.get(key); all.put(buildSend(method, true, false, superCall), method); } for (Iterator iterator = set.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); all.put(key, set.get(key)); } for (Iterator iterator = set64.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); all.put(key, set64.get(key)); } for (Iterator iterator = all.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); Node method = all.get(key); NodeList params = method.getChildNodes(); ArrayList tags = new ArrayList(); int count = 0; for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if ("arg".equals(param.getNodeName())) { if (isStruct(param)) { tags.add(" * @param arg" + count + " flags=struct"); } count++; } } out("/**"); if (tags.size() > 0) { outln(); out(" *"); } out(" @method flags=cast"); if (tags.size() > 0) outln(); for (String tag : tags) { out(tag); outln(); } out(" */"); outln(); out(key.toString()); outln(); } } String getSelConst(String sel) { return "sel_" + sel.replaceAll(":", "_"); } void generateClassesConst() { TreeSet set = new TreeSet(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("class".equals(node.getNodeName())) { if (getGen(node)) { NamedNodeMap attributes = node.getAttributes(); String name = attributes.getNamedItem("name").getNodeValue(); set.add(name); } } } } for (Iterator iterator = set.iterator(); iterator.hasNext();) { String cls = iterator.next(); String clsConst = "class_" + cls; out("public static final int /*long*/ "); out(clsConst); out(" = "); out("objc_getClass(\""); out(cls); out("\");"); outln(); } } void generateProtocolsConst() { TreeSet set = new TreeSet(); for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("informal_protocol".equals(node.getNodeName())) { if (getGen(node)) { NamedNodeMap attributes = node.getAttributes(); String name = attributes.getNamedItem("name").getNodeValue(); set.add(name); } } } } for (Iterator iterator = set.iterator(); iterator.hasNext();) { String cls = iterator.next(); String clsConst = "protocol_" + cls; out("public static final int /*long*/ "); out(clsConst); out(" = "); out("objc_getProtocol(\""); out(cls); out("\");"); outln(); } } String getPackageName(String className) { int dot = mainClassName.lastIndexOf('.'); if (dot == -1) return ""; return mainClassName.substring(0, dot); } String getClassName(String className) { int dot = mainClassName.lastIndexOf('.'); if (dot == -1) return mainClassName; return mainClassName.substring(dot + 1); } Node getReturnNode(NodeList list) { for (int j = 0; j < list.getLength(); j++) { Node node = list.item(j); if ("retval".equals(node.getNodeName())) { return node; } } return null; } String getType(Node node) { NamedNodeMap attributes = node.getAttributes(); Node javaType = attributes.getNamedItem("hawtjni_java_type"); if (javaType != null) return javaType.getNodeValue(); String code = attributes.getNamedItem("type").getNodeValue(); return getType(code, attributes, false); } String getType64(Node node) { NamedNodeMap attributes = node.getAttributes(); Node javaType = attributes.getNamedItem("hawtjni_java_type"); if (javaType != null) { Node javaType64 = attributes.getNamedItem("hawtjni_java_type64"); return javaType64 != null ? javaType64.getNodeValue() : javaType.getNodeValue(); } Node attrib = attributes.getNamedItem("type"); String code = attrib.getNodeValue(); Node attrib64 = attributes.getNamedItem("type64"); if (attrib64 != null) code = attrib64.getNodeValue(); return getType(code, attributes, true); } String getType(String code, NamedNodeMap attributes, boolean is64) { if (code.equals("c")) return "byte"; if (code.equals("i")) return "int"; if (code.equals("s")) return "short"; if (code.equals("l")) return "int"; if (code.equals("q")) return "long"; if (code.equals("C")) return "byte"; if (code.equals("I")) return "int"; if (code.equals("S")) return "short"; if (code.equals("L")) return "int"; if (code.equals("Q")) return "long"; if (code.equals("f")) return "float"; if (code.equals("d")) return "double"; if (code.equals("B")) return "boolean"; if (code.equals("v")) return "void"; if (code.equals("*")) return is64 ? "long" : "int"; if (code.equals("@")) return is64 ? "long" : "int"; if (code.equals("#")) return is64 ? "long" : "int"; if (code.equals(":")) return is64 ? "long" : "int"; if (code.startsWith("^")) return is64 ? "long" : "int"; if (code.startsWith("{")) { return attributes.getNamedItem("declared_type").getNodeValue(); } return "BAD " + code; } String getJNIType(Node node) { NamedNodeMap attributes = node.getAttributes(); String code = attributes.getNamedItem("type").getNodeValue(); if (code.equals("c")) return "B"; if (code.equals("i")) return "I"; if (code.equals("s")) return "S"; if (code.equals("l")) return "I"; if (code.equals("q")) return "J"; if (code.equals("C")) return "B"; if (code.equals("I")) return "I"; if (code.equals("S")) return "S"; if (code.equals("L")) return "I"; if (code.equals("Q")) return "J"; if (code.equals("f")) return "F"; if (code.equals("d")) return "D"; if (code.equals("B")) return "Z"; if (code.equals("v")) return "V"; if (code.equals("*")) return "I"; if (code.equals("@")) return "I"; if (code.equals("#")) return "I"; if (code.equals(":")) return "I"; if (code.startsWith("^")) return "I"; if (code.startsWith("[")) return "BAD " + code; if (code.startsWith("{")) { return "BAD " + code; } if (code.startsWith("(")) return "BAD " + code; return "BAD " + code; } String getJavaType(Node node) { NamedNodeMap attributes = node.getAttributes(); Node javaType = attributes.getNamedItem("hawtjni_java_type"); if (javaType != null) return javaType.getNodeValue().trim(); String code = attributes.getNamedItem("type").getNodeValue(); return getJavaType(code, attributes, false); } String getJavaType64(Node node) { NamedNodeMap attributes = node.getAttributes(); Node javaType = attributes.getNamedItem("hawtjni_java_type"); if (javaType != null) { Node javaType64 = attributes.getNamedItem("hawtjni_java_type64"); return javaType64 != null ? javaType64.getNodeValue() : javaType.getNodeValue(); } Node attrib = attributes.getNamedItem("type"); String code = attrib.getNodeValue(); Node attrib64 = attributes.getNamedItem("type64"); if (attrib64 != null) code = attrib64.getNodeValue(); return getJavaType(code, attributes, true); } String getJavaType(String code, NamedNodeMap attributes, boolean is64) { if (code.equals("c")) return "byte"; if (code.equals("i")) return "int"; if (code.equals("s")) return "short"; if (code.equals("l")) return "int"; if (code.equals("q")) return "long"; if (code.equals("C")) return "byte"; if (code.equals("I")) return "int"; if (code.equals("S")) return "short"; if (code.equals("L")) return "int"; if (code.equals("Q")) return "long"; if (code.equals("f")) return "float"; if (code.equals("d")) return "double"; if (code.equals("B")) return "boolean"; if (code.equals("v")) return "void"; if (code.equals("*")) return is64 ? "long" : "int"; if (code.equals("#")) return is64 ? "long" : "int"; if (code.equals(":")) return is64 ? "long" : "int"; if (code.startsWith("^")) return is64 ? "long" : "int"; if (code.equals("@")) { String type = attributes.getNamedItem("declared_type").getNodeValue(); int index = type.indexOf('*'); if (index != -1) type = type.substring(0, index); index = type.indexOf('<'); if (index != -1) type = type.substring(0, index); return type.trim(); } if (code.startsWith("{")) { return attributes.getNamedItem("declared_type").getNodeValue().trim(); } return "BAD " + code; } static String[] split(String str, String separator) { StringTokenizer tk = new StringTokenizer(str, separator); ArrayList result = new ArrayList(); while (tk.hasMoreElements()) { result.add(tk.nextElement()); } return result.toArray(new String[result.size()]); } void generateFunctions() { for (int x = 0; x < xmls.length; x++) { Document document = documents[x]; if (document == null) continue; NodeList list = document.getDocumentElement().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ("function".equals(node.getNodeName())) { if (getGen(node)) { NamedNodeMap attributes = node.getAttributes(); String name = attributes.getNamedItem("name").getNodeValue(); NodeList params = node.getChildNodes(); int count = 0; for (int j = 0; j < params.getLength(); j++) { Node param = params.item(j); if ("arg".equals(param.getNodeName())) { count++; } } if (count > 0) { out("/**"); outln(); } for (int j = 0; j < params.getLength(); j++) { Node param = params.item(j); if ("arg".equals(param.getNodeName())) { NamedNodeMap paramAttributes = param.getAttributes(); out(" * @param "); out(paramAttributes.getNamedItem("name").getNodeValue()); if (isStruct(param)) { out(" flags=struct"); } else { out(" cast="); Node declaredType = paramAttributes.getNamedItem("declared_type"); String cast = declaredType.getNodeValue(); if (!cast.startsWith("(")) out("("); out(cast); if (!cast.endsWith(")")) out(")"); } outln(); } } if (count > 0) { out(" */"); outln(); } out("public static final native "); Node returnNode = getReturnNode(node.getChildNodes()); if (returnNode != null) { String type = getType(returnNode), type64 = getType64(returnNode); out(type); if (!type.equals(type64)) { out(" /*"); out(type64); out("*/"); } out(" "); } else { out("void "); } out(name); out("("); params = node.getChildNodes(); boolean first = true; for (int j = 0; j < params.getLength(); j++) { Node param = params.item(j); if ("arg".equals(param.getNodeName())) { NamedNodeMap paramAttributes = param.getAttributes(); if (!first) out(", "); first = false; String type = getType(param), type64 = getType64(param); out(type); if (!type.equals(type64)) { out(" /*"); out(type64); out("*/"); } out(" "); out(paramAttributes.getNamedItem("name").getNodeValue()); } } generateVariadics(node); out(");"); outln(); } } } } } void generateVariadics(Node node) { NamedNodeMap attributes = node.getAttributes(); Node variadicCount = attributes.getNamedItem("hawtjni_variadic_count"); if (variadicCount != null) { Node variadicTypes = attributes.getNamedItem("hawtjni_variadic_java_types"); String[] types = null; if (variadicTypes != null) { types = split(variadicTypes.getNodeValue(), ","); } int varCount = 0; try { varCount = Integer.parseInt(variadicCount.getNodeValue()); } catch (NumberFormatException e) { } for (int j = 0; j < varCount; j++) { out(", "); if (types != null && types.length > j && !types[j].equals("*")) { out(types[j]); } else if (types != null && types[types.length - 1].equals("*")) { out(types[types.length - 2]); } else { out("int /*long*/"); } out(" varArg"); out("" + j); } } } public static void main(String[] args) { try { MacGenerator gen = new MacGenerator(); gen.setXmls(args); gen.setOutputDir("../org.eclipse.hawtjni/Eclipse SWT PI/cocoa/"); gen.setMainClass("org.eclipse.hawtjni.internal.cocoa.OS"); gen.generate(null); } catch (Throwable e) { e.printStackTrace(); } } } MozillaGenerator.java000077500000000000000000000577451475274123300360550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2003, 2006 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.io.*; import java.util.*; /** * Produces the java classes mapping to XPCOM Mozilla objects. * * @author Hiram Chirino */ public class MozillaGenerator { static boolean DEBUG = false; FileReader r = null; FileWriter w = null; int maxLines = 1000; int cntLines = 0; int n = 0; String[] b = null; String body = null; int nMethods = 0; String uuidName; String uuidValue; String className; String parentName; String[] constantNames; String[] constantValues; String[] methodNames; String[][] argTypes; String[][] argNames; String bodyOrder; TreeMap> vtbls = new TreeMap>(); // Contains the characters found before a method name // Useful to extract the method name. e.g. // NS_IMETHOD QueryInterface(const nsIID & uuid, void * *result) = 0; // NS_IMETHOD_(nsrefcnt) AddRef(void) = 0; // method name follows: QueryInterface, AddRef etc. static String[] BEFORE_METHOD_NAME = { " NS_IMETHOD ", " NS_IMETHOD_(nsrefcnt) ", " NS_IMETHOD_(void *) ", " NS_IMETHOD_(void) ", " NS_IMETHOD_(nsresult) ", " NS_SCRIPTABLE NS_IMETHOD ", " NS_SCRIPTABLE NS_IMETHOD_(nsrefcnt) ", " NS_SCRIPTABLE NS_IMETHOD_(void *) ", " NS_SCRIPTABLE NS_IMETHOD_(void) ", " NS_SCRIPTABLE NS_IMETHOD_(nsresult) ", }; static String NO_SUPER_CLASS = "SWT_NO_SUPER_CLASS"; static String[][] TYPES_C2JAVA = { { "PRBool *", "int[]" }, { "nsIID &", "nsID" }, { "nsCID &", "nsID" }, { "nsCID * *", "int /*long*/" }, // nsID[] not supported by jnigen { "* *", "int /*long*/[]" }, { "**", "int /*long*/[]" }, { "* &", "int /*long*/[]" }, { "PRUint32 *", "int[]" }, { "PRInt32 *", "int[]" }, { "PRInt64 *", "long[]" }, { "PRUnichar *", "char[]" }, { "char *", "byte[]" }, { "float *", "float[]" }, { "PRUint16 *", "short[]" }, { "nativeWindow *", "int /*long*/[]" }, { "nsWriteSegmentFun", "int /*long*/" }, { "nativeWindow", "int /*long*/" }, { "*", "int /*long*/" }, // c type containing one or more * (and any // other character, and did not match // previous patterns) is a simple pointer { "&", "int /*long*/" }, { "PRUint32", "int" }, { "PRInt32", "int" }, { "PRInt64", "long" }, { "nsresult", "int" }, { "PRBool", "int" }, { "float", "float" }, { "PRUint16", "short" }, { "size_t", "int" }, }; static String GECKO = "/bluebird/teamhawtjni/hawtjni-builddir/mozilla/1.4/linux_gtk2/mozilla/dist/include/"; static String TARGET_FOLDER = "/bluebird/teamhawtjni/chrisx/amd64/workspace/org.eclipse.hawtjni/Eclipse SWT Mozilla/common/org/eclipse/hawtjni/internal/mozilla/"; static String[] XPCOM_HEADERS = { "profile/nsIProfile.h", "widget/nsIAppShell.h", "widget/nsIBaseWindow.h", "xpcom/nsIComponentManager.h", "xpcom/nsIComponentRegistrar.h", "webbrwsr/nsIContextMenuListener.h", "docshell/nsIDocShell.h", "dom/nsIDOMEvent.h", "dom/nsIDOMMouseEvent.h", "dom/nsIDOMUIEvent.h", "dom/nsIDOMWindow.h", "uriloader/nsIDownload.h", "webbrwsr/nsIEmbeddingSiteWindow.h", "xpcom/nsIFactory.h", "xpcom/nsIFile.h", "helperAppDlg/nsIHelperAppLauncherDialog.h", "exthandler/nsIExternalHelperAppService.h", // contains // nsIHelperAppLauncher "xpcom/nsIInputStream.h", "xpcom/nsIInterfaceRequestor.h", "necko/nsIIOService.h", "xpcom/nsILocalFile.h", "xpcom/nsIMemory.h", "progressDlg/nsIProgressDialog.h", "windowwatcher/nsIPromptService.h", "xpcom/nsIServiceManager.h", "xpcom/nsISupports.h", "webbrwsr/nsITooltipListener.h", "necko/nsIURI.h", "uriloader/nsIURIContentListener.h", "xpcom/nsIWeakReference.h", "webbrwsr/nsIWebBrowser.h", "webbrwsr/nsIWebBrowserChrome.h", "webbrwsr/nsIWebBrowserChromeFocus.h", "webbrwsr/nsIWebBrowserFocus.h", "docshell/nsIWebNavigation.h", "uriloader/nsIWebProgress.h", "uriloader/nsIWebProgressListener.h", "embed_base/nsIWindowCreator.h", "windowwatcher/nsIWindowWatcher.h" }; public static void main(String[] args) { MozillaGenerator x = new MozillaGenerator(); for (int i = 0; i < XPCOM_HEADERS.length; i++) x.parse(GECKO + XPCOM_HEADERS[i], TARGET_FOLDER); x.outputVtblCall(); System.out.println("done"); } /** Write callbacks */ public void write(String data) { if (DEBUG) { System.out.print(data); return; } try { w.write(data); } catch (IOException e) { e.printStackTrace(); } } public void writeLine() { if (DEBUG) { System.out.println(); return; } write("\r\n"); } public void writeLine(String data) { if (DEBUG) { System.out.println(data); return; } write(data + "\r\n"); } public void writeCopyrights() { writeLine(COPYRIGHTS); } public void writePackageDeclaration() { writeLine(PACKAGE_DECLARATION); } public void writeClassDeclaration(String className, String parentName) { String line = "public class " + className; if (!parentName.equals(NO_SUPER_CLASS)) line += " extends " + parentName; line += " {"; writeLine(line); } public void writeLastMethodId(String parentName, int nMethods) { String line = "\tstatic final int LAST_METHOD_ID = "; if (!parentName.equals(NO_SUPER_CLASS)) line += parentName + ".LAST_METHOD_ID + " + nMethods + ";"; else line += "" + (nMethods - 1) + ";"; // zero indexed writeLine(line); } public void writeIID(String uuidName, String uuidValue) { writeLine("\tpublic static final String " + uuidName + " ="); writeLine("\t\t\"" + uuidValue + "\";"); writeLine(); String iid = uuidName.substring(0, uuidName.indexOf("_STR")); writeLine("\tpublic static final nsID " + iid + " ="); writeLine("\t\tnew nsID(" + uuidName + ");"); } public void writeAddressField() { writeLine("\tint /*long*/ address;"); } public void writeConstructor(String className, String parentName) { writeLine("\tpublic " + className + "(int /*long*/ address) {"); if (!parentName.equals(NO_SUPER_CLASS)) { writeLine("\t\tsuper(address);"); } else { writeLine("\t\tthis.address = address;"); } writeLine("\t}"); } public void writeAddressGetter() { writeLine("\tpublic int /*long*/ getAddress() {"); writeLine("\t\treturn this.address;"); writeLine("\t}"); } public void writeConstant(String name, String value) { writeLine("\tpublic static final int " + name + " = " + value + ";"); } public void writeMethod(String name, String parentName, int methodIndex, String[] argTypes, String[] argNames) { write("\tpublic int " + name + "("); for (int i = 0; i < argTypes.length; i++) { write(argTypes[i] + " " + argNames[i]); if (i < argTypes.length - 1) write(", "); } write(") {"); writeLine(); String line = "\t\treturn XPCOM.VtblCall("; if (!parentName.equals(NO_SUPER_CLASS)) line += parentName + ".LAST_METHOD_ID + " + (methodIndex + 1) + ", getAddress()"; else line += methodIndex + ", getAddress()"; // zero indexed write(line); if (argTypes.length > 0) write(", "); for (int i = 0; i < argTypes.length; i++) { write(argNames[i]); if (i < argTypes.length - 1) write(", "); } writeLine(");"); writeLine("\t}"); } public void writeClassEnd() { write("}"); } public void logVtblCall(String[] argTypes) { String vtbl = "static final native int VtblCall(int fnNumber, int /*long*/ ppVtbl"; if (argTypes.length > 0) vtbl += ", "; for (int i = 0; i < argTypes.length; i++) { vtbl += argTypes[i] + " arg" + i; if (i < argTypes.length - 1) vtbl += ", "; } vtbl += ");"; Integer key = new Integer(argTypes.length); TreeSet list = vtbls.get(key); if (list == null) { list = new TreeSet(); vtbls.put(key, list); } boolean duplicate = false; for (String s : list) { if (vtbl.equals(s)) { duplicate = true; break; } } if (!duplicate) list.add(vtbl); } public void outputVtblCall() { Collection> values = vtbls.values(); for (TreeSet elts : values) { for (String elt : elts) { System.out.println(elt); } } } /** Parsing invoking write callbacks */ /* * Convert a C header file into a Java source file matching SWT Mozilla * binding. */ public void parse(String src, String destPath) { if (DEBUG) writeLine("*** PARSING <" + src + "> to folder " + destPath); b = new String[maxLines]; cntLines = 0; try { r = new FileReader(src); BufferedReader br = new BufferedReader(r); while ((b[cntLines] = br.readLine()) != null) { cntLines++; } br.close(); } catch (IOException e) { e.printStackTrace(); return; } n = 0; boolean lookForClasses = true; while (lookForClasses) { /* parsing */ lookForClasses = parse(); String destFile = destPath + className + ".java"; try { w = new FileWriter(destFile); if (DEBUG) writeLine("** CREATED JAVA FILE <" + destFile + ">"); } catch (IOException e) { e.printStackTrace(); return; } /* writing */ writeCopyrights(); writePackageDeclaration(); writeLine(); writeClassDeclaration(className, parentName); writeLine(); writeLastMethodId(parentName, nMethods); writeLine(); writeIID(uuidName, uuidValue); writeLine(); if (parentName.equals(NO_SUPER_CLASS)) { writeAddressField(); writeLine(); } writeConstructor(className, parentName); writeLine(); if (parentName.equals(NO_SUPER_CLASS)) { writeAddressGetter(); writeLine(); } int constantIndex = 0, methodIndex = 0; for (int i = 0; i < bodyOrder.length(); i++) { if (bodyOrder.charAt(i) == 'C') { writeConstant(constantNames[constantIndex], constantValues[constantIndex]); if (i < bodyOrder.length() - 1) writeLine(); constantIndex++; } else if (bodyOrder.charAt(i) == 'M') { writeMethod(methodNames[methodIndex], parentName, methodIndex, argTypes[methodIndex], argNames[methodIndex]); if (i < bodyOrder.length() - 1) writeLine(); methodIndex++; } } writeClassEnd(); try { w.close(); } catch (IOException e) { e.printStackTrace(); } } } public String getPackages() { return "package org.eclipse.hawtjni.internal.mozilla;"; } public boolean parse() { if (!jumpToUuidDeclaration()) return false; uuidName = getUuidName(b[n]); if (DEBUG) System.out.println("UUID name: <" + uuidName + ">"); uuidValue = getUuidValue(b[n]); if (DEBUG) System.out.println("UUID value: <" + uuidValue + ">"); jumpToInterfaceDeclaration(); className = getClassName(b[n]); if (DEBUG) System.out.println("Interface name: <" + className + ">"); parentName = getParentName(b[n]); if (DEBUG) System.out.println("parentName: <" + parentName + ">"); parseBody(); return true; } boolean jumpToUuidDeclaration() { // jump to line matching: // "#define NS_IWEBBROWSERCHROME_IID_STR "ba434c60-9d52-11d3-afb0-00a024ffc08c"" while (!(b[n].startsWith("#define ") && b[n].indexOf("_IID_STR \"") != -1)) { n++; if (n >= cntLines) return false; } return true; } // assume a declaration matching: // "#define NS_IWEBBROWSERCHROME_IID_STR "ba434c60-9d52-11d3-afb0-00a024ffc08c"" // returns NS_IWEBBROWSERCHROME_IID_STR String getUuidName(String declaration) { return declaration.substring(declaration.indexOf("#define ") + "#define ".length(), declaration.indexOf(" \"")); } // assume a declaration matching: // "#define NS_IWEBBROWSERCHROME_IID_STR "ba434c60-9d52-11d3-afb0-00a024ffc08c"" // returns ba434c60-9d52-11d3-afb0-00a024ffc08c String getUuidValue(String declaration) { return declaration.substring(declaration.indexOf("_IID_STR \"") + "_IID_STR \"".length(), declaration.lastIndexOf('"')); } void jumpToInterfaceDeclaration() { // jump to line matching: // "class NS_NO_VTABLE nsIWebBrowserChrome : public nsISupports {" while (!(b[n].startsWith("class NS_NO_VTABLE "))) { n++; } } // Assume a declaration matching: // "class NS_NO_VTABLE nsIWebBrowserChrome : public nsISupports {" // or // "class NS_NO_VTABLE NS_SCRIPTABLE nsIWebBrowserChrome : public nsISupports {" // returns nsIWebBrowserChrome. // Special case for nsISupports that has no super class: class NS_NO_VTABLE // nsISupports { String getClassName(String declaration) { int endIndex = declaration.indexOf(" :"); // nsISupports special case (no super class) if (endIndex == -1) endIndex = declaration.indexOf(" {"); String searchString = "class NS_NO_VTABLE NS_SCRIPTABLE"; int startIndex = declaration.indexOf(searchString); if (startIndex == -1) { searchString = "class NS_NO_VTABLE "; startIndex = declaration.indexOf(searchString); } return declaration.substring(startIndex + searchString.length(), endIndex); } // assume a declaration matching: // "class NS_NO_VTABLE nsIWebBrowserChrome : public nsISupports {" // returns nsISupports // special case for nsISupports that has no super class: class NS_NO_VTABLE // nsISupports { String getParentName(String declaration) { if (declaration.indexOf(" :") == -1) return NO_SUPER_CLASS; return declaration.substring(declaration.indexOf(": public ") + ": public ".length(), declaration.indexOf(" {")); } // parse methods and constants declarations starting at the current index // out: // .String body - contains the corresponding java content // .n - set to the end of the interface body declaration ( line with the // enclosing "};" ) // .nMethods - set to the number of methods parsed void parseBody() { body = ""; bodyOrder = ""; int nConstants = 0; nMethods = 0; int tmp_n = n; while (true) { int type = jumpToNextConstantOrMethod(); if (type == CONSTANT) nConstants++; if (type == METHOD) nMethods++; if (type == END_BODY) break; n++; } n = tmp_n; constantNames = new String[nConstants]; constantValues = new String[nConstants]; methodNames = new String[nMethods]; argTypes = new String[nMethods][]; argNames = new String[nMethods][]; int constantIndex = 0, methodIndex = 0; while (true) { int type = jumpToNextConstantOrMethod(); if (type == CONSTANT) { parseConstant(b[n], constantIndex); bodyOrder += "C"; constantIndex++; } if (type == METHOD) { parseMethod(b[n], methodIndex); logVtblCall(argTypes[methodIndex]); bodyOrder += "M"; methodIndex++; } if (type == END_BODY) return; n++; } } static int CONSTANT = 0; static int METHOD = 1; static int END_BODY = 2; boolean isEndOfInterfaceBody() { return b[n].startsWith("};"); } int jumpToNextConstantOrMethod() { while (!isEndOfInterfaceBody()) { if (b[n].startsWith(" enum { ")) { return CONSTANT; } if (methodNameStartIndexOf(b[n]) != -1) { return METHOD; } n++; } return END_BODY; } void parseConstant(String constant, int constantIndex) { String constantName = constant.substring(constant.indexOf(" enum { ") + " enum { ".length(), constant.indexOf(" =")); if (DEBUG) writeLine("constantName <" + constantName + ">"); constantNames[constantIndex] = constantName; // most constants values have a trailing U // enum { APP_TYPE_UNKNOWN = 0U }; int endIndex = constant.indexOf("U };"); // a few others don't // enum { ENUMERATE_FORWARDS = 0 }; if (endIndex == -1) endIndex = constant.indexOf(" };"); String constantValue = constant.substring(constant.indexOf(" = ") + " = ".length(), endIndex); if (DEBUG) writeLine("constantValue <" + constantValue + ">"); constantValues[constantIndex] = constantValue; } // NS_IMETHOD SetStatus(PRUint32 statusType, const PRUnichar *status) = 0; // identify: // method name: // Nbr of arguments: 2 // Type of argument 0: PRUint32 // Name of argument 0: statusType // Type of argument 1: const PRUnichar * // Name of argument 1: status void parseMethod(String line, int methodIndex) { int start = methodNameStartIndexOf(line); int end = methodNameEndIndexOf(line); String methodName = line.substring(start, end); if (DEBUG) writeLine("method name: <" + methodName + ">"); methodNames[methodIndex] = methodName; int argStart = end + "(".length(); int argEnd = line.indexOf(")", argStart); parseArgs(line.substring(argStart, argEnd), methodIndex); } // Given a line, returns the start of the method name or -1 // if the line does not contain a method declaration. int methodNameStartIndexOf(String line) { for (int i = 0; i < BEFORE_METHOD_NAME.length; i++) { int index = line.indexOf(BEFORE_METHOD_NAME[i]); if (index != -1) return index + BEFORE_METHOD_NAME[i].length(); } return -1; } int methodNameEndIndexOf(String line) { int startIndex = methodNameStartIndexOf(line); return line.indexOf("(", startIndex); } void parseArgs(String args, int methodIndex) { int nArgs = -1; // methods with no args look like: () or (void) String[] noArgs = new String[] { "", "void" }; for (int i = 0; i < noArgs.length; i++) { if (args.equals(noArgs[i])) { nArgs = 0; break; } } if (nArgs == -1) nArgs = count(args, ", ") + 1; String[] argTypes = new String[nArgs]; this.argTypes[methodIndex] = argTypes; String[] argNames = new String[nArgs]; this.argNames[methodIndex] = argNames; int typeStart = 0; // name is separated from its type by either of the following (sorted by // decreasing size to find the most complete pattern */ String[] typeNameSep = new String[] { " * *", " **", " * & ", " * ", " *", " & ", " " }; for (int i = 0; i < nArgs; i++) { /* get the type */ int nextTypeStart = i < nArgs - 1 ? args.indexOf(", ", typeStart) + ", ".length() : args.length(); int typeNameSepIndex = 0; int separatorIndex = 0; for (; typeNameSepIndex < typeNameSep.length; typeNameSepIndex++) { separatorIndex = args.indexOf(typeNameSep[typeNameSepIndex], typeStart); if (separatorIndex != -1 && separatorIndex < nextTypeStart) break; } String separator = typeNameSep[typeNameSepIndex]; argTypes[i] = getC2JavaType(args.substring(typeStart, separatorIndex + separator.length())); if (DEBUG) writeLine("arg type" + i + ": <" + argTypes[i] + ">"); /* get the name */ int nameStart = separatorIndex + separator.length(); int nameEnd = i < nArgs - 1 ? args.indexOf(", ", nameStart) : args.length(); argNames[i] = args.substring(nameStart, nameEnd); if (DEBUG) writeLine("arg name" + i + ": <" + argNames[i] + ">"); typeStart = nextTypeStart; } } String getC2JavaType(String cType) { for (int i = 0; i < TYPES_C2JAVA.length; i++) { if (cType.indexOf(TYPES_C2JAVA[i][0]) != -1) return TYPES_C2JAVA[i][1]; } return "!ERROR UNKNOWN C TYPE <" + cType + ">!"; } // how many times part can be found in s static int count(String s, String part) { int index = -1, cnt = 0; while ((index = s.indexOf(part, index + 1)) != -1) cnt++; return cnt; } static String COPYRIGHTS = "/* ***** BEGIN LICENSE BLOCK *****\r\n" + " * Version: MPL 1.1\r\n" + " *\r\n" + " * The contents of this file are subject to the Mozilla Public License Version\r\n" + " * 1.1 (the \"License\"); you may not use this file except in compliance with\r\n" + " * the License. You may obtain a copy of the License at\r\n" + " * http://www.mozilla.org/MPL/\r\n" + " *\r\n" + " * Software distributed under the License is distributed on an \"AS IS\" basis,\r\n" + " * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\r\n" + " * for the specific language governing rights and limitations under the\r\n" + " * License.\r\n" + " *\r\n" + " * The Original Code is Mozilla Communicator client code, released March 31, 1998.\r\n" + " *\r\n" + " * The Initial Developer of the Original Code is\r\n" + " * Netscape Communications Corporation.\r\n" + " * Portions created by Netscape are Copyright (C) 1998-1999\r\n" + " * Netscape Communications Corporation. All Rights Reserved.\r\n" + " *\r\n" + " * Contributor(s):\r\n" + " *\r\n" + " * IBM\r\n" + " * - Binding to permit interfacing between Mozilla and SWT\r\n" + " * - Copyright (C) 2003, 2009 IBM Corp. All Rights Reserved.\r\n" + " *\r\n" + " * ***** END LICENSE BLOCK ***** */"; static String PACKAGE_DECLARATION = "package org.eclipse.hawtjni.internal.mozilla;"; } NativesGenerator.java000077500000000000000000001353771475274123300360550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIField; import org.fusesource.hawtjni.generator.model.JNIFieldAccessor; import org.fusesource.hawtjni.generator.model.JNIMethod; import org.fusesource.hawtjni.generator.model.JNIParameter; import org.fusesource.hawtjni.generator.model.JNIType; import org.fusesource.hawtjni.runtime.ArgFlag; import org.fusesource.hawtjni.runtime.ClassFlag; import org.fusesource.hawtjni.runtime.FieldFlag; import org.fusesource.hawtjni.runtime.MethodFlag; import static org.fusesource.hawtjni.runtime.MethodFlag.*; /** * * @author Hiram Chirino */ public class NativesGenerator extends JNIGenerator { boolean enterExitMacro; public NativesGenerator() { enterExitMacro = true; } public void generateCopyright() { outputln(fixDelimiter(getCopyright())); } public void generateIncludes() { String outputName = getOutputName(); outputln("#include \"" + outputName + ".h\""); outputln("#include \"hawtjni.h\""); outputln("#include \"" + outputName + "_structs.h\""); outputln("#include \"" + outputName + "_stats.h\""); outputln(); } public void generate(JNIClass clazz) { List methods = clazz.getNativeMethods(); if( methods.isEmpty() ) { return; } sortMethods(methods); generateNativeMacro(clazz); generate(methods); } public void generate(List methods) { sortMethods(methods); for (JNIMethod method : methods) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; generate(method); if (progress != null) progress.step(); } } boolean isStruct(ArgFlag flags[]) { for (ArgFlag flag : flags) { if (flag.equals(ArgFlag.BY_VALUE)) return true; } return false; } void generateCallback(JNIMethod method, String function, List params, JNIType returnType) { output("static jintLong "); output(function); outputln(";"); output("static "); String[] types = method.getCallbackTypes(); ArgFlag[][] flags = method.getCallbackFlags(); output(types[0]); output(" "); output("proc_"); output(function); output("("); boolean first = true; for (int i = 1; i < types.length; i++) { if (!first) output(", "); output(types[i]); output(" "); output("arg"); output(String.valueOf(i - 1)); first = false; } outputln(") {"); output("\t"); if (isStruct(flags[0])) { output(types[0]); output("* lprc = "); } else if (!types[0].equals("void")) { output("return "); } output("(("); output(types[0]); if (isStruct(flags[0])) output("*"); output(" (*)("); first = true; for (int i = 1; i < types.length; i++) { if (!first) output(", "); first = false; output(types[i]); if (isStruct(flags[i])) output("*"); } output("))"); output(function); output(")("); first = true; for (int i = 1; i < types.length; i++) { if (!first) output(", "); first = false; if (isStruct(flags[i])) output("&"); output("arg"); output(String.valueOf(i - 1)); } outputln(");"); if (isStruct(flags[0])) { output("\t"); output(types[0]); outputln(" rc;"); outputln("\tif (lprc) {"); outputln("\t\trc = *lprc;"); outputln("\t\tfree(lprc);"); outputln("\t} else {"); output("\t\tmemset(&rc, 0, sizeof("); output(types[0]); outputln("));"); outputln("\t}"); outputln("\treturn rc;"); } outputln("}"); output("static jintLong "); output(method.getName()); outputln("(jintLong func) {"); output("\t"); output(function); outputln(" = func;"); output("\treturn (jintLong)proc_"); output(function); outputln(";"); outputln("}"); } private void generateConstantsInitializer(JNIMethod method) { JNIClass clazz = method.getDeclaringClass(); ArrayList constants = getConstantFields(clazz); if( constants.isEmpty() ) { return; } if (isCPP) { output("extern \"C\" "); } outputln("JNIEXPORT void JNICALL "+clazz.getSimpleName()+"_NATIVE("+toC(method.getName())+")(JNIEnv *env, jclass that)"); outputln("{"); for (JNIField field : constants) { String conditional = field.getConditional(); if (conditional!=null) { outputln("#if "+conditional); } JNIType type = field.getType(), type64 = field.getType64(); boolean allowConversion = !type.equals(type64); String simpleName = type.getSimpleName(); JNIFieldAccessor accessor = field.getAccessor(); String fieldId = "(*env)->GetStaticFieldID(env, that, \""+field.getName()+"\", \""+type.getTypeSignature(allowConversion)+"\")"; if (isCPP) { fieldId = "env->GetStaticFieldID(that, \""+field.getName()+"\", \""+type.getTypeSignature(allowConversion)+"\")"; } if (type.isPrimitive()) { if (isCPP) { output("\tenv->SetStatic"+type.getTypeSignature1(allowConversion)+"Field(that, "+fieldId +", "); } else { output("\t(*env)->SetStatic"+type.getTypeSignature1(allowConversion)+"Field(env, that, "+fieldId +", "); } output("("+type.getTypeSignature2(allowConversion)+")"); if( field.isPointer() ) { output("(intptr_t)"); } output(accessor.getter()); output(");"); } else if (type.isArray()) { JNIType componentType = type.getComponentType(), componentType64 = type64.getComponentType(); if (componentType.isPrimitive()) { outputln("\t{"); output("\t"); output(type.getTypeSignature2(allowConversion)); output(" lpObject1 = ("); output(type.getTypeSignature2(allowConversion)); if (isCPP) { output(")env->GetStaticObjectField(that, "); } else { output(")(*env)->GetStaticObjectField(env, that, "); } output(field.getDeclaringClass().getSimpleName()); output(fieldId); outputln(");"); if (isCPP) { output("\tenv->Set"); } else { output("\t(*env)->Set"); } output(componentType.getTypeSignature1(!componentType.equals(componentType64))); if (isCPP) { output("ArrayRegion(lpObject1, 0, sizeof("); } else { output("ArrayRegion(env, lpObject1, 0, sizeof("); } output(accessor.getter()); output(")"); if (!componentType.isType("byte")) { output(" / sizeof("); output(componentType.getTypeSignature2(!componentType.equals(componentType64))); output(")"); } output(", ("); output(type.getTypeSignature4(allowConversion, false)); output(")"); output(accessor.getter()); outputln(");"); output("\t}"); } else { throw new Error("not done"); } } else { outputln("\t{"); if (isCPP) { output("\tjobject lpObject1 = env->GetStaticObjectField(that, "); } else { output("\tjobject lpObject1 = (*env)->GetStaticObjectField(env, that, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); outputln(");"); output("\tif (lpObject1 != NULL) set"); output(simpleName); output("Fields(env, lpObject1, &lpStruct->"); output(accessor.getter()); outputln(");"); output("\t}"); } outputln(); if (conditional!=null) { outputln("#endif"); } } outputln(" return;"); outputln("}"); } private ArrayList getConstantFields(JNIClass clazz) { ArrayList rc = new ArrayList(); List fields = clazz.getDeclaredFields(); for (JNIField field : fields) { int mods = field.getModifiers(); if ( (mods & Modifier.STATIC) != 0 && field.getFlag(FieldFlag.CONSTANT)) { rc.add(field); } } return rc; } public void generate(JNIMethod method) { if (method.getFlag(MethodFlag.METHOD_SKIP)) return; JNIType returnType = method.getReturnType32(), returnType64 = method.getReturnType64(); if( method.getFlag(CONSTANT_INITIALIZER)) { if( returnType.isType("void") && method.getParameters().isEmpty() ) { generateConstantsInitializer(method); } else { output("#error Warning: invalid CONSTANT_INITIALIZER tagged method. It must be void and take no arguments: "); outputln(method.toString()); } return; } if (!(returnType.isType("void") || returnType.isPrimitive() || isSystemClass(returnType) || returnType.isType("java.lang.String"))) { output("#error Warning: bad return type. :"); outputln(method.toString()); return; } String conditional = method.getConditional(); if (conditional!=null) { outputln("#if "+conditional); } List params = method.getParameters(); String function = getFunctionName(method), function64 = getFunctionName(method, method.getParameterTypes64()); boolean sameFunction = function.equals(function64); if (!sameFunction) { output("#ifndef "); output(JNI64); outputln(); } if (isCPP) { output("extern \"C\" "); generateFunctionPrototype(method, function, params, returnType, returnType64, true); outputln(";"); } if (function.startsWith("CALLBACK_")) { generateCallback(method, function, params, returnType); } generateFunctionPrototype(method, function, params, returnType, returnType64, !sameFunction); if (!function.equals(function64)) { outputln(); outputln("#else"); if (isCPP) { output("extern \"C\" "); generateFunctionPrototype(method, function64, params, returnType, returnType64, true); outputln(";"); } generateFunctionPrototype(method, function64, params, returnType, returnType64, !sameFunction); outputln(); outputln("#endif"); } generateFunctionBody(method, function, function64, params, returnType, returnType64); if (conditional!=null) { outputln("#endif"); } outputln(); } public void setEnterExitMacro(boolean enterExitMacro) { this.enterExitMacro = enterExitMacro; } void generateNativeMacro(JNIClass clazz) { output("#define "); output(clazz.getSimpleName()); output("_NATIVE(func) Java_"); output(toC(clazz.getName())); outputln("_##func"); outputln(); } boolean generateGetParameter(JNIMethod method, JNIParameter param, boolean critical, int indent) { JNIType paramType = param.getType32(), paramType64 = param.getType64(); if (paramType.isPrimitive() || isSystemClass(paramType)) return false; String iStr = String.valueOf(param.getParameter()); for (int j = 0; j < indent; j++) output("\t"); output("if (arg"); output(iStr); output(") if ((lparg"); output(iStr); output(" = "); if (paramType.isArray()) { JNIType componentType = paramType.getComponentType(); if (componentType.isPrimitive()) { if( "long".equals( componentType.getName() ) && param.isPointer() ) { // This case is special as we may need to do pointer conversions.. // if your on a 32 bit system but are keeping track of the pointers in a 64 bit long output("hawtjni_malloc_pointer_array(env, arg"); output(iStr); output(")"); } else if (critical) { if (isCPP) { output("("); output(componentType.getTypeSignature2(!paramType.equals(paramType64))); output("*)"); output("env->GetPrimitiveArrayCritical(arg"); } else { output("(*env)->GetPrimitiveArrayCritical(env, arg"); } output(iStr); output(", NULL)"); } else { if (isCPP) { output("env->Get"); } else { output("(*env)->Get"); } output(componentType.getTypeSignature1(!paramType.equals(paramType64))); if (isCPP) { output("ArrayElements(arg"); } else { output("ArrayElements(env, arg"); } output(iStr); output(", NULL)"); } } else { throw new Error("not done"); } } else if (paramType.isType("java.lang.String")) { if (param.getFlag(ArgFlag.UNICODE)) { if (isCPP) { output("env->GetStringChars(arg"); } else { output("(*env)->GetStringChars(env, arg"); } output(iStr); output(", NULL)"); } else { if (isCPP) { output("env->GetStringUTFChars(arg"); } else { output("(*env)->GetStringUTFChars(env, arg"); } output(iStr); output(", NULL)"); } } else { if (param.getFlag(ArgFlag.NO_IN)) { output("&_arg"); output(iStr); } else { output("get"); output(paramType.getSimpleName()); output("Fields(env, arg"); output(iStr); output(", &_arg"); output(iStr); output(")"); } } outputln(") == NULL) goto fail;"); return true; } void generateSetParameter(JNIParameter param, boolean critical) { JNIType paramType = param.getType32(), paramType64 = param.getType64(); if (paramType.isPrimitive() || isSystemClass(paramType)) return; String iStr = String.valueOf(param.getParameter()); if (paramType.isArray()) { output("\tif (arg"); output(iStr); output(" && lparg"); output(iStr); output(") "); JNIType componentType = paramType.getComponentType(); if (componentType.isPrimitive()) { if( "long".equals( componentType.getName() ) && param.isPointer() ) { // This case is special as we may need to do pointer conversions.. // if your on a 32 bit system but are keeping track of the pointers in a 64 bit long output("hawtjni_free_pointer_array(env, arg"); output(iStr); } else if (critical) { if (isCPP) { output("env->ReleasePrimitiveArrayCritical(arg"); } else { output("(*env)->ReleasePrimitiveArrayCritical(env, arg"); } output(iStr); } else { if (isCPP) { output("env->Release"); } else { output("(*env)->Release"); } output(componentType.getTypeSignature1(!paramType.equals(paramType64))); if (isCPP) { output("ArrayElements(arg"); } else { output("ArrayElements(env, arg"); } output(iStr); } output(", lparg"); output(iStr); output(", "); if (param.getFlag(ArgFlag.NO_OUT)) { output("JNI_ABORT"); } else { output("0"); } output(");"); } else { throw new Error("not done"); } outputln(); } else if (paramType.isType("java.lang.String")) { output("\tif (arg"); output(iStr); output(" && lparg"); output(iStr); output(") "); if (param.getFlag(ArgFlag.UNICODE)) { if (isCPP) { output("env->ReleaseStringChars(arg"); } else { output("(*env)->ReleaseStringChars(env, arg"); } } else { if (isCPP) { output("env->ReleaseStringUTFChars(arg"); } else { output("(*env)->ReleaseStringUTFChars(env, arg"); } } output(iStr); output(", lparg"); output(iStr); outputln(");"); } else { if (!param.getFlag(ArgFlag.NO_OUT)) { output("\tif (arg"); output(iStr); output(" && lparg"); output(iStr); output(") "); output("set"); output(paramType.getSimpleName()); output("Fields(env, arg"); output(iStr); output(", lparg"); output(iStr); outputln(");"); } } } void generateEnterExitMacro(JNIMethod method, String function, String function64, boolean enter) { if (!enterExitMacro) return; if (!function.equals(function64)) { output("#ifndef "); output(JNI64); outputln(); } output("\t"); output(method.getDeclaringClass().getSimpleName()); output("_NATIVE_"); output(enter ? "ENTER" : "EXIT"); output("(env, that, "); output(method.getDeclaringClass().getSimpleName()+"_"+function); outputln("_FUNC);"); if (!function.equals(function64)) { outputln("#else"); output("\t"); output(method.getDeclaringClass().getSimpleName()); output("_NATIVE_"); output(enter ? "ENTER" : "EXIT"); output("(env, that, "); output(method.getDeclaringClass().getSimpleName()+"_"+function64); outputln("_FUNC);"); outputln("#endif"); } } boolean generateLocalVars(JNIMethod method, List params, JNIType returnType, JNIType returnType64) { boolean needsReturn = enterExitMacro; for (int i = 0; i < params.size(); i++) { JNIParameter param = params.get(i); JNIType paramType = param.getType32(), paramType64 = param.getType64(); if (paramType.isPrimitive() || isSystemClass(paramType)) continue; output("\t"); if (paramType.isArray()) { JNIType componentType = paramType.getComponentType(); if( "long".equals( componentType.getName() ) && param.isPointer() ) { output("void **lparg" + i+"=NULL;"); } else if (componentType.isPrimitive()) { output(componentType.getTypeSignature2(!paramType.equals(paramType64))); output(" *lparg" + i); output("=NULL;"); } else { throw new Error("not done"); } } else if (paramType.isType("org.fusesource.hawtjni.runtime.JNIEnv")) { // no need to generate a local for this one.. } else if (paramType.isType("java.lang.String")) { if (param.getFlag(ArgFlag.UNICODE)) { output("const jchar *lparg" + i); } else { output("const char *lparg" + i); } output("= NULL;"); } else { if (param.getTypeClass().getFlag(ClassFlag.STRUCT) && !param.getTypeClass().getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(paramType.getNativeName()); output(" _arg" + i); if (param.getFlag(ArgFlag.INIT)) output("={0}"); output(", *lparg" + i); output("=NULL;"); } outputln(); needsReturn = true; } if (needsReturn) { if (!returnType.isType("void")) { output("\t"); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); outputln(" rc = 0;"); } } return needsReturn; } boolean generateGetters(JNIMethod method, List params) { boolean genFailTag = false; int criticalCount = 0; for (JNIParameter param : params) { if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (!isCritical(param)) { genFailTag |= generateGetParameter(method, param, false, 1); } else { criticalCount++; } } } if (criticalCount != 0) { outputln("#ifdef JNI_VERSION_1_2"); outputln("\tif (IS_JNI_1_2) {"); for (JNIParameter param : params) { if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (isCritical(param)) { genFailTag |= generateGetParameter(method, param, true, 2); } } } outputln("\t} else"); outputln("#endif"); outputln("\t{"); for (JNIParameter param : params) { if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (isCritical(param)) { genFailTag |= generateGetParameter(method, param, false, 2); } } } outputln("\t}"); } return genFailTag; } void generateSetters(JNIMethod method, List params) { int criticalCount = 0; for (int i = params.size() - 1; i >= 0; i--) { JNIParameter param = params.get(i); if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (isCritical(param)) { criticalCount++; } } } if (criticalCount != 0) { outputln("#ifdef JNI_VERSION_1_2"); outputln("\tif (IS_JNI_1_2) {"); for (int i = params.size() - 1; i >= 0; i--) { JNIParameter param = params.get(i); if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (isCritical(param)) { output("\t"); generateSetParameter(param, true); } } } outputln("\t} else"); outputln("#endif"); outputln("\t{"); for (int i = params.size() - 1; i >= 0; i--) { JNIParameter param = params.get(i); if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (isCritical(param)) { output("\t"); generateSetParameter(param, false); } } } outputln("\t}"); } for (int i = params.size() - 1; i >= 0; i--) { JNIParameter param = params.get(i); if( !"org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { if (!isCritical(param)) { generateSetParameter(param, false); } } } } void generateDynamicFunctionCall(JNIMethod method, List params, JNIType returnType, JNIType returnType64, boolean needsReturn) { outputln("/*"); generateFunctionCall(method, params, returnType, returnType64, needsReturn); outputln("*/"); outputln("\t{"); String name = method.getName(); if (name.startsWith("_")) name = name.substring(1); output("\t\tLOAD_FUNCTION(fp, "); output(name); outputln(")"); outputln("\t\tif (fp) {"); output("\t\t"); generateFunctionCallLeftSide(method, returnType, returnType64, needsReturn); output("(("); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); output(" (CALLING_CONVENTION*)("); for (int i = 0; i < params.size(); i++) { if (i != 0) output(", "); JNIParameter param = params.get(i); String cast = param.getCast(); if( param.isPointer() ) { output("(intptr_t)"); } boolean isStruct = param.getFlag(ArgFlag.BY_VALUE); if (cast.length() > 2) { cast = cast.substring(1, cast.length() - 1); if (isStruct) { int index = cast.lastIndexOf('*'); if (index != -1) cast = cast.substring(0, index).trim(); } output(cast); } else { JNIType paramType = param.getType32(), paramType64 = param.getType64(); output(paramType.getTypeSignature4(!paramType.equals(paramType64), isStruct)); } } output("))"); output("fp"); output(")"); generateFunctionCallRightSide(method, params, 0); output(";"); outputln(); outputln("\t\t}"); outputln("\t}"); } void generateFunctionCallLeftSide(JNIMethod method, JNIType returnType, JNIType returnType64, boolean needsReturn) { output("\t"); if (!returnType.isType("void")) { if (needsReturn) { output("rc = "); } else { output("return "); } String cast = method.getCast(); if (cast.length() != 0 && !cast.equals("()")) { if( method.isPointer() ) { output("(intptr_t)"); } output(cast); } else { if( method.getFlag(CPP_NEW)) { String[] parts = getNativeNameParts(method); String className = parts[0]; output("(intptr_t)("+className+" *)"); } else { output("("); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); output(")"); } } } if (method.getFlag(MethodFlag.ADDRESS)) { output("&"); } if (method.getFlag(MethodFlag.JNI)) { output(isCPP ? "env->" : "(*env)->"); } } void generateFunctionCallRightSide(JNIMethod method, List params, int paramStart) { if (!method.getFlag(MethodFlag.CONSTANT_GETTER)) { output("("); if (method.getFlag(MethodFlag.JNI)) { if (!isCPP) output("env, "); } for (int i = paramStart; i < params.size(); i++) { JNIParameter param = params.get(i); if (i != paramStart) output(", "); if (param.getFlag(ArgFlag.BY_VALUE)) output("*"); output(param.getCast()); if( param.isPointer() ) { output("(intptr_t)"); } if (param.getFlag(ArgFlag.CS_OBJECT)) output("TO_OBJECT("); if (i == params.size() - 1 && param.getFlag(ArgFlag.SENTINEL)) { output("NULL"); } else { if( "org.fusesource.hawtjni.runtime.JNIEnv".equals(param.getTypeClass().getName()) ) { output("env"); } else { JNIType paramType = param.getType32(); if (!paramType.isPrimitive() && !isSystemClass(paramType)) output("lp"); output("arg" + i); } } if (param.getFlag(ArgFlag.CS_OBJECT)) output(")"); } output(")"); } } static String[] getNativeNameParts(JNIMethod method) { String className = null; String methodName = null; JNIClass dc = method.getDeclaringClass(); if( dc.getFlag(ClassFlag.CPP) || dc.getFlag(ClassFlag.STRUCT) ) { className = method.getDeclaringClass().getNativeName(); } if( method.getAccessor().length() != 0 ) { methodName = method.getAccessor(); int pos = methodName.lastIndexOf("::"); if( pos >= 0 ) { className = methodName.substring(0, pos); methodName = methodName.substring(pos+2); } } else { methodName = method.getName(); if( className==null ) { int pos = methodName.indexOf("_"); if( pos > 0 ) { className = methodName.substring(0, pos); methodName = methodName.substring(pos+1); } } } if( className==null ) { throw new Error(String.format("Could not determine object type name of method '%s'", method.getDeclaringClass().getSimpleName()+"."+method.getName())); } return new String[]{className, methodName}; } void generateFunctionCall(JNIMethod method, List params, JNIType returnType, JNIType returnType64, boolean needsReturn) { String name = method.getName(); String copy = method.getCopy(); boolean makeCopy = copy.length() != 0 && isCPP && !returnType.isType("void"); if (makeCopy) { output("\t{"); output("\t\t"); output(copy); output(" temp = "); } else { generateFunctionCallLeftSide(method, returnType, returnType64, needsReturn); } int paramStart = 0; if (name.startsWith("_")) name = name.substring(1); boolean objc_struct = false; if (name.equals("objc_msgSend_stret") || name.equals("objc_msgSendSuper_stret")) objc_struct = true; if (objc_struct) { outputln("if (sizeof(_arg0) > STRUCT_SIZE_LIMIT) {"); generate_objc_msgSend_stret(method, params, name); paramStart = 1; } else if (name.equalsIgnoreCase("call")) { output("("); JNIParameter param = params.get(0); String cast = param.getCast(); if (cast.length() != 0 && !cast.equals("()")) { output(cast); if( param.isPointer() ) { output("(intptr_t)"); } } else { output("("); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); output(" (*)())"); } output("arg0)"); paramStart = 1; } else if (name.startsWith("VtblCall") || name.startsWith("_VtblCall")) { output("(("); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); output(" (STDMETHODCALLTYPE *)("); for (int i = 1; i < params.size(); i++) { if (i != 1) output(", "); JNIParameter param = params.get(i); JNIType paramType = param.getType32(), paramType64 = param.getType64(); output(paramType.getTypeSignature4(!paramType.equals(paramType64), false)); } output("))(*("); JNIType paramType = params.get(1).getType32(), paramType64 = params.get(1).getType64(); output(paramType.getTypeSignature4(!paramType.equals(paramType64), false)); output(" **)arg1)[arg0])"); paramStart = 1; } else if (method.getFlag(MethodFlag.CPP_METHOD) || method.getFlag(MethodFlag.SETTER) || method.getFlag(MethodFlag.GETTER) || method.getFlag(MethodFlag.ADDER)) { String[] parts = getNativeNameParts(method); String className = parts[0]; String methodName = parts[1]; if (method.getFlag(MethodFlag.CS_OBJECT)) { output("TO_HANDLE("); } output("("); if( params.isEmpty() ) { throw new Error(String.format("C++ bound method '%s' missing the 'this' parameter", method.getDeclaringClass().getSimpleName()+"."+method.getName())); } JNIParameter param = params.get(0); if (param.getFlag(ArgFlag.BY_VALUE)) output("*"); String cast = param.getCast(); if (cast.length() != 0 && !cast.equals("()")) { output(cast); if( param.isPointer() ) { output("(intptr_t)"); } } else { output("("+className+" *)(intptr_t)"); } if (param.getFlag(ArgFlag.CS_OBJECT)) { output("TO_OBJECT("); } output("arg0"); if (param.getFlag(ArgFlag.CS_OBJECT)) { output(")"); } output(")->"); output(methodName); paramStart = 1; } else if (method.getFlag(MethodFlag.CS_NEW)) { output("TO_HANDLE(gcnew "); String accessor = method.getAccessor(); if (accessor.length() != 0) { output(accessor); } else { JNIClass dc = method.getDeclaringClass(); if( dc.getFlag(ClassFlag.CPP) || dc.getFlag(ClassFlag.STRUCT) ) { output(dc.getNativeName()); } else { int index = -1; if ((index = name.indexOf('_')) != -1) { output(name.substring(index + 1)); } else { output(name); } } } } else if (method.getFlag(MethodFlag.CPP_NEW)) { if (method.getFlag(MethodFlag.CS_OBJECT)) { output("TO_HANDLE("); } output("new "); String accessor = method.getAccessor(); if (accessor.length() != 0) { output(accessor); } else { JNIClass dc = method.getDeclaringClass(); if( dc.getFlag(ClassFlag.CPP) ) { output(method.getDeclaringClass().getNativeName()); } else { int index = -1; if ((index = name.indexOf('_')) != -1) { output(name.substring(index+1)); } else { output(name); } } } } else if (method.getFlag(MethodFlag.CPP_DELETE)) { String[] parts = getNativeNameParts(method); String className = parts[0]; output("delete "); JNIParameter param = params.get(0); String cast = param.getCast(); if (cast.length() != 0 && !cast.equals("()")) { output(cast); if( param.isPointer() ) { output("(intptr_t)"); } } else { output("("+className+" *)(intptr_t)"); } outputln("arg0;"); return; } else { if (method.getFlag(MethodFlag.CS_OBJECT)) { output("TO_HANDLE("); } if (method.getFlag(MethodFlag.CAST)) { output("(("); String returnCast = returnType.getTypeSignature2(!returnType.equals(returnType64)); if (name.equals("objc_msgSend_bool") && returnCast.equals("jboolean")) { returnCast = "BOOL"; } output(returnCast); output(" (*)("); for (int i = 0; i < params.size(); i++) { if (i != 0) output(", "); JNIParameter param = params.get(i); String cast = param.getCast(); if (cast.length() != 0 && !cast.equals("()") ) { if (cast.startsWith("(")) cast = cast.substring(1); if (cast.endsWith(")")) cast = cast.substring(0, cast.length() - 1); output(cast); } else { JNIType paramType = param.getType32(), paramType64 = param.getType64(); if (!(paramType.isPrimitive() || paramType.isArray())) { if (param.getTypeClass().getFlag(ClassFlag.STRUCT) && !param.getTypeClass().getFlag(ClassFlag.TYPEDEF)) { output("struct "); } } output(paramType.getTypeSignature4(!paramType.equals(paramType64), param.getFlag(ArgFlag.BY_VALUE))); } } output("))"); } String accessor = method.getAccessor(); if (accessor.length() != 0) { output(accessor); } else { output(name); } if (method.getFlag(MethodFlag.CAST)) { output(")"); } } if ((method.getFlag(MethodFlag.SETTER) && params.size() == 3) || (method.getFlag(MethodFlag.GETTER) && params.size() == 2)) { output("[arg1]"); paramStart++; } if (method.getFlag(MethodFlag.SETTER)) output(" = "); if (method.getFlag(MethodFlag.ADDER)) output(" += "); if (!method.getFlag(MethodFlag.GETTER)) { generateFunctionCallRightSide(method, params, paramStart); } if (method.getFlag(MethodFlag.CS_NEW) || method.getFlag(MethodFlag.CS_OBJECT)) { output(")"); } output(";"); outputln(); if (makeCopy) { outputln("\t\t{"); output("\t\t\t"); output(copy); output("* copy = new "); output(copy); outputln("();"); outputln("\t\t\t*copy = temp;"); output("\t\t\trc = "); output("("); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); output(")"); outputln("copy;"); outputln("\t\t}"); outputln("\t}"); } if (objc_struct) { outputln("\t} else {"); generate_objc_msgSend_stret(method, params, name.substring(0, name.length() - "_stret".length())); generateFunctionCallRightSide(method, params, 1); outputln(";"); outputln("\t}"); } } void generate_objc_msgSend_stret(JNIMethod method, List params, String func) { output("\t\t*lparg0 = (*("); JNIType paramType = params.get(0).getType32(), paramType64 = params.get(0).getType64(); output(paramType.getTypeSignature4(!paramType.equals(paramType64), true)); output(" (*)("); for (int i = 1; i < params.size(); i++) { if (i != 1) output(", "); JNIParameter param = params.get(i); String cast = param.getCast(); if( param.isPointer() ) { output("(intptr_t)"); } if (cast.length() != 0 && !cast.equals("()")) { if (cast.startsWith("(")) cast = cast.substring(1); if (cast.endsWith(")")) cast = cast.substring(0, cast.length() - 1); output(cast); } else { paramType = param.getType32(); paramType64 = param.getType64(); if (!(paramType.isPrimitive() || paramType.isArray())) { if (param.getTypeClass().getFlag(ClassFlag.STRUCT) && !param.getTypeClass().getFlag(ClassFlag.TYPEDEF)) { output("struct "); } } output(paramType.getTypeSignature4(!paramType.equals(paramType64), param.getFlag(ArgFlag.BY_VALUE))); } } output("))"); output(func); output(")"); } void generateReturn(JNIMethod method, JNIType returnType, boolean needsReturn) { if (needsReturn && !returnType.isType("void")) { outputln("\treturn rc;"); } } void generateMemmove(JNIMethod method, String function, String function64, List params) { generateEnterExitMacro(method, function, function64, true); output("\t"); boolean get = params.get(0).getType32().isPrimitive(); String className = params.get(get ? 1 : 0).getType32().getSimpleName(); output(get ? "if (arg1) get" : "if (arg0) set"); output(className); output(get ? "Fields(env, arg1, (" : "Fields(env, arg0, ("); output(className); output(get ? " *)arg0)" : " *)arg1)"); outputln(";"); generateEnterExitMacro(method, function, function64, false); } void generateFunctionBody(JNIMethod method, String function, String function64, List params, JNIType returnType, JNIType returnType64) { outputln("{"); /* Custom GTK memmoves. */ String name = method.getName(); if (name.startsWith("_")) name = name.substring(1); boolean isMemove = (name.equals("memmove") || name.equals("MoveMemory")) && params.size() == 2 && returnType.isType("void"); if (isMemove) { generateMemmove(method, function, function64, params); } else { boolean needsReturn = generateLocalVars(method, params, returnType, returnType64); generateEnterExitMacro(method, function, function64, true); boolean genFailTag = generateGetters(method, params); if (method.getFlag(MethodFlag.DYNAMIC)) { generateDynamicFunctionCall(method, params, returnType, returnType64, needsReturn); } else { generateFunctionCall(method, params, returnType, returnType64, needsReturn); } if (genFailTag) outputln("fail:"); generateSetters(method, params); generateEnterExitMacro(method, function, function64, false); generateReturn(method, returnType, needsReturn); } outputln("}"); } void generateFunctionPrototype(JNIMethod method, String function, List params, JNIType returnType, JNIType returnType64, boolean singleLine) { output("JNIEXPORT "); output(returnType.getTypeSignature2(!returnType.equals(returnType64))); output(" JNICALL "); output(method.getDeclaringClass().getSimpleName()); output("_NATIVE("); output(function); if (singleLine) { output(")"); output("(JNIEnv *env, "); } else { outputln(")"); output("\t(JNIEnv *env, "); } if ((method.getModifiers() & Modifier.STATIC) != 0) { output("jclass"); } else { output("jobject"); } output(" that"); for (int i = 0; i < params.size(); i++) { output(", "); JNIType paramType = params.get(i).getType32(), paramType64 = params.get(i).getType64(); output(paramType.getTypeSignature2(!paramType.equals(paramType64))); output(" arg" + i); } output(")"); if (!singleLine) outputln(); } boolean isCritical(JNIParameter param) { JNIType paramType = param.getType32(); return paramType.isArray() && paramType.getComponentType().isPrimitive() && param.getFlag(ArgFlag.CRITICAL); } boolean isSystemClass(JNIType type) { return type.isType("java.lang.Object") || type.isType("java.lang.Class"); } } ProgressMonitor.java000077500000000000000000000013301475274123300357260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (c) 2005 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; /** * * @author Hiram Chirino */ public interface ProgressMonitor { public void setTotal(int total); public void setMessage(String message); public void step(); } SizeofGenerator.java000077500000000000000000000044761475274123300356760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIField; import org.fusesource.hawtjni.generator.model.ReflectClass; /** * * @author Hiram Chirino */ public class SizeofGenerator extends JNIGenerator { public void generate(JNIClass clazz) { String className = clazz.getSimpleName(); output("\tprintf(\""); output(className); output("=%d\\n\", sizeof("); output(className); outputln("));"); } public void generate() { outputln("int main() {"); super.generate(); outputln("}"); } public void generate(List fields) { sortFields(fields); for (JNIField field : fields) { if ((field.getModifiers() & Modifier.FINAL) == 0) continue; generate(field); } } public void generate(JNIField field) { output("\tprintf(\""); output(field.getName()); output("=%d\\n\", sizeof("); output(field.getName()); outputln("));"); } public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java SizeofGenerator "); return; } try { SizeofGenerator gen = new SizeofGenerator(); for (int i = 0; i < args.length; i++) { String clazzName = args[i]; Class clazz = Class.forName(clazzName); gen.generate(new ReflectClass(clazz)); } } catch (Exception e) { System.out.println("Problem"); e.printStackTrace(System.out); } } } StatsGenerator.java000077500000000000000000000163241475274123300355300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIMethod; /** * * @author Hiram Chirino */ public class StatsGenerator extends JNIGenerator { boolean header; public StatsGenerator(boolean header) { this.header = header; } public void generateCopyright() { outputln(fixDelimiter(getCopyright())); } public void generateIncludes() { if (!header) { outputln("#include \"hawtjni.h\""); outputln("#include \""+getOutputName()+"_stats.h\""); outputln(); } } public void generate(JNIClass clazz) { if (header) { generateHeaderFile(clazz); } else { generateSourceFile(clazz); } } void generateHeaderFile(JNIClass clazz) { generateNATIVEMacros(clazz); List methods = clazz.getDeclaredMethods(); sortMethods(methods); generateFunctionEnum(methods); } void generateNATIVEMacros(JNIClass clazz) { String className = clazz.getSimpleName(); outputln("#ifdef NATIVE_STATS"); output("extern int "); output(className); outputln("_nativeFunctionCount;"); output("extern int "); output(className); outputln("_nativeFunctionCallCount[];"); output("extern char* "); output(className); outputln("_nativeFunctionNames[];"); output("#define "); output(className); output("_NATIVE_ENTER(env, that, func) "); output(className); outputln("_nativeFunctionCallCount[func]++;"); output("#define "); output(className); outputln("_NATIVE_EXIT(env, that, func) "); outputln("#else"); output("#ifndef "); output(className); outputln("_NATIVE_ENTER"); output("#define "); output(className); outputln("_NATIVE_ENTER(env, that, func) "); outputln("#endif"); output("#ifndef "); output(className); outputln("_NATIVE_EXIT"); output("#define "); output(className); outputln("_NATIVE_EXIT(env, that, func) "); outputln("#endif"); outputln("#endif"); outputln(); } void generateSourceFile(JNIClass clazz) { outputln("#ifdef NATIVE_STATS"); outputln(); List methods = clazz.getDeclaredMethods(); int methodCount = 0; for (JNIMethod method : methods) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; methodCount++; } String className = clazz.getSimpleName(); output("int "); output(className); output("_nativeFunctionCount = "); output(String.valueOf(methodCount)); outputln(";"); output("int "); output(className); output("_nativeFunctionCallCount["); output(String.valueOf(methodCount)); outputln("];"); output("char * "); output(className); outputln("_nativeFunctionNames[] = {"); sortMethods(methods); for (JNIMethod method : methods) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; String function = getFunctionName(method), function64 = getFunctionName(method, method.getParameterTypes64()); if (!function.equals(function64)) { output("#ifndef "); output(JNI64); outputln(); } output("\t\""); output(function); outputln("\","); if (!function.equals(function64)) { outputln("#else"); output("\t\""); output(function64); outputln("\","); outputln("#endif"); } if (progress != null) progress.step(); } outputln("};"); outputln(); generateStatsNatives(className); outputln(); outputln("#endif"); } void generateStatsNatives(String className) { outputln("#define STATS_NATIVE(func) Java_org_fusesource_hawtjni_runtime_NativeStats_##func"); outputln(); output("JNIEXPORT jint JNICALL STATS_NATIVE("); output(toC(className + "_GetFunctionCount")); outputln(")"); outputln("\t(JNIEnv *env, jclass that)"); outputln("{"); output("\treturn "); output(className); outputln("_nativeFunctionCount;"); outputln("}"); outputln(); output("JNIEXPORT jstring JNICALL STATS_NATIVE("); output(toC(className + "_GetFunctionName")); outputln(")"); outputln("\t(JNIEnv *env, jclass that, jint index)"); outputln("{"); output("\treturn "); if (isCPP) { output("env->NewStringUTF("); } else { output("(*env)->NewStringUTF(env, "); } output(className); outputln("_nativeFunctionNames[index]);"); outputln("}"); outputln(); output("JNIEXPORT jint JNICALL STATS_NATIVE("); output(toC(className + "_GetFunctionCallCount")); outputln(")"); outputln("\t(JNIEnv *env, jclass that, jint index)"); outputln("{"); output("\treturn "); output(className); outputln("_nativeFunctionCallCount[index];"); outputln("}"); } void generateFunctionEnum(List methods) { if (methods.isEmpty()) return; outputln("typedef enum {"); for (JNIMethod method : methods) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; String function = getFunctionName(method), function64 = getFunctionName(method, method.getParameterTypes64()); if (!function.equals(function64)) { output("#ifndef "); output(JNI64); outputln(); } output("\t"); output(method.getDeclaringClass().getSimpleName()+"_"+function); outputln("_FUNC,"); if (!function.equals(function64)) { outputln("#else"); output("\t"); output(method.getDeclaringClass().getSimpleName()+"_"+function64); outputln("_FUNC,"); outputln("#endif"); } if (progress != null) progress.step(); } JNIClass clazz = methods.get(0).getDeclaringClass(); output("} "); output(clazz.getSimpleName()); outputln("_FUNCS;"); } } StructsGenerator.java000077500000000000000000000561001475274123300360750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2007 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.fusesource.hawtjni.generator.model.JNIClass; import org.fusesource.hawtjni.generator.model.JNIField; import org.fusesource.hawtjni.generator.model.JNIFieldAccessor; import org.fusesource.hawtjni.generator.model.JNIType; import org.fusesource.hawtjni.runtime.ClassFlag; /** * * @author Hiram Chirino */ public class StructsGenerator extends JNIGenerator { boolean header; static final boolean GLOBAL_REF = false; private HashMap> structFields = new HashMap>(); public StructsGenerator(boolean header) { this.header = header; } public void generateCopyright() { outputln(fixDelimiter(getCopyright())); } public void generateIncludes() { if (header) { outputln("#include \"" + getOutputName() + ".h\""); } else { outputln("#include \"" + getOutputName() + ".h\""); outputln("#include \"hawtjni.h\""); outputln("#include \"" + getOutputName() + "_structs.h\""); } outputln(); } public void generate(JNIClass clazz) { ArrayList fields = getStructFields(clazz); if (fields.isEmpty()) return; if (header) { generateHeaderFile(clazz); } else { generateSourceFile(clazz); } } private ArrayList getStructFields(JNIClass clazz) { if (!structFields.containsKey(clazz)) { ArrayList rc = new ArrayList(); List fields = clazz.getDeclaredFields(); for (JNIField field : fields) { int mods = field.getModifiers(); if ((mods & Modifier.STATIC) == 0 && (mods & Modifier.TRANSIENT) == 0) { rc.add(field); } } structFields.put(clazz, rc); } return structFields.get(clazz); } void generateHeaderFile(JNIClass clazz) { generateSourceStart(clazz); generatePrototypes(clazz); generateBlankMacros(clazz); generateSourceEnd(clazz); outputln(); } void generateSourceFile(JNIClass clazz) { generateSourceStart(clazz); generateFIDsStructure(clazz); outputln(); generateGlobalVar(clazz); outputln(); generateFunctions(clazz); generateSourceEnd(clazz); outputln(); } void generateSourceStart(JNIClass clazz) { String conditional = clazz.getConditional(); if (conditional != null) { outputln("#if " + conditional); } } void generateSourceEnd(JNIClass clazz) { if (clazz.getConditional() != null) { outputln("#endif"); } } void generateGlobalVar(JNIClass clazz) { String simpleName = clazz.getSimpleName(); output(simpleName); output("_FID_CACHE "); output(simpleName); outputln("Fc;"); } void generateBlankMacros(JNIClass clazz) { if (clazz.getConditional() == null) { return; } String simpleName = clazz.getSimpleName(); outputln("#else"); output("#define cache"); output(simpleName); outputln("Fields(a,b)"); output("#define get"); output(simpleName); outputln("Fields(a,b,c) NULL"); output("#define set"); output(simpleName); outputln("Fields(a,b,c)"); } void generatePrototypes(JNIClass clazz) { String clazzName = clazz.getNativeName(); String simpleName = clazz.getSimpleName(); output("void cache"); output(simpleName); outputln("Fields(JNIEnv *env, jobject lpObject);"); if (clazz.getFlag(ClassFlag.STRUCT) && !clazz.getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(clazzName); output(" *get"); output(simpleName); output("Fields(JNIEnv *env, jobject lpObject, "); if (clazz.getFlag(ClassFlag.STRUCT) && !clazz.getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(clazzName); outputln(" *lpStruct);"); output("void set"); output(simpleName); output("Fields(JNIEnv *env, jobject lpObject, "); if (clazz.getFlag(ClassFlag.STRUCT) && !clazz.getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(clazzName); outputln(" *lpStruct);"); } void generateFIDsStructure(JNIClass clazz) { String simpleName = clazz.getSimpleName(); output("typedef struct "); output(simpleName); outputln("_FID_CACHE {"); outputln("\tint cached;"); outputln("\tjclass clazz;"); List fields = clazz.getDeclaredFields(); boolean first = true; for (JNIField field : fields) { if (ignoreField(field)) continue; if (first) output("\tjfieldID "); else output(", "); output(field.getName()); first = false; } outputln(";"); output("} "); output(simpleName); outputln("_FID_CACHE;"); } void generateCacheFunction(JNIClass clazz) { String simpleName = clazz.getSimpleName(); String clazzName = clazz.getNativeName(); output("void cache"); output(simpleName); outputln("Fields(JNIEnv *env, jobject lpObject)"); outputln("{"); output("\tif ("); output(simpleName); outputln("Fc.cached) return;"); JNIClass superclazz = clazz.getSuperclass(); if (!superclazz.getName().equals("java.lang.Object") && hasNonIgnoredFields(superclazz)) { String superName = superclazz.getSimpleName(); output("\tcache"); output(superName); outputln("Fields(env, lpObject);"); } output("\t"); output(simpleName); if (isCPP) { if (GLOBAL_REF) { output("Fc.clazz = (jclass)env->NewGlobalRef(env->GetObjectClass(lpObject));"); } else { output("Fc.clazz = env->GetObjectClass(lpObject);"); } } else { if (GLOBAL_REF) { output("Fc.clazz = (*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, lpObject));"); } else { output("Fc.clazz = (*env)->GetObjectClass(env, lpObject);"); } } outputln(); List fields = clazz.getDeclaredFields(); for (JNIField field : fields) { if (ignoreField(field)) continue; output("\t"); output(simpleName); output("Fc."); output(field.getName()); if (isCPP) { output(" = env->GetFieldID("); } else { output(" = (*env)->GetFieldID(env, "); } output(simpleName); output("Fc.clazz, \""); output(field.getName()); JNIType type = field.getType(), type64 = field.getType64(); output("\", "); if (type.equals(type64)) output("\""); output(type.getTypeSignature(!type.equals(type64))); if (type.equals(type64)) output("\""); outputln(");"); } // Makes sure compiler/cpu does not reorder the following write before the previous updates are done. outputln("\thawtjni_w_barrier();"); output("\t"); output(simpleName); outputln("Fc.cached = 1;"); outputln("}"); } void generateGetFields(JNIClass clazz) { JNIClass superclazz = clazz.getSuperclass(); String clazzName = clazz.getNativeName(); String superName = superclazz.getNativeName(); String methodname; if (!superclazz.getName().equals("java.lang.Object") && hasNonIgnoredFields(superclazz)) { /* * Windows exception - cannot call get/set function of super class * in this case */ if (!(clazzName.equals(superName + "A") || clazzName.equals(superName + "W"))) { output("\tget"); output(superName); output("Fields(env, lpObject, ("); output(superName); outputln(" *)lpStruct);"); } else { generateGetFields(superclazz); } } List fields = clazz.getDeclaredFields(); int sharePtrIndex = 0; for (JNIField field : fields) { if (ignoreField(field)) continue; String conditional = field.getConditional(); if (conditional != null) { outputln("#if " + conditional); } JNIType type = field.getType(), type64 = field.getType64(); String simpleName = type.getSimpleName(); JNIFieldAccessor accessor = field.getAccessor(); boolean allowConversion = !type.equals(type64); output("\t"); if (type.isPrimitive()) { if (!accessor.isNonMemberSetter()) output("lpStruct->"); if (accessor.isMethodSetter()) { String setterStart = accessor.setter().split("\\(")[0]; output(setterStart + "("); if (accessor.isNonMemberSetter()) output("lpStruct, "); } else { output(accessor.setter()); output(" = "); } if (field.isSharedPointer()) output("std::make_shared<" + type.getTypeSignature2(allowConversion) + ">("); else output(field.getCast()); if (field.isPointer()) { output("(intptr_t)"); } if (isCPP) { output("env->Get"); } else { output("(*env)->Get"); } output(type.getTypeSignature1(!type.equals(type64))); if (isCPP) { output("Field(lpObject, "); } else { output("Field(env, lpObject, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); if (field.isSharedPointer()) output(")"); if (accessor.isMethodSetter()) output(")"); output(");"); } else if (type.isArray()) { JNIType componentType = type.getComponentType(), componentType64 = type64.getComponentType(); if (componentType.isPrimitive()) { if (field.isSharedPointer()) { output("(&"); output("lpStruct->" + accessor); output("));"); } outputln("{"); output("\t"); output(type.getTypeSignature2(!type.equals(type64))); output(" lpObject1 = ("); output(type.getTypeSignature2(!type.equals(type64))); if (isCPP) { output(")env->GetObjectField(lpObject, "); } else { output(")(*env)->GetObjectField(env, lpObject, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); outputln(");"); if (isCPP) { output("\tenv->Get"); } else { output("\t(*env)->Get"); } output(componentType.getTypeSignature1(!componentType.equals(componentType64))); if (isCPP) { output("ArrayRegion(lpObject1, 0, sizeof("); } else { output("ArrayRegion(env, lpObject1, 0, sizeof("); } if (!accessor.isNonMemberGetter()) output("lpStruct->"); output(accessor.getter()); output(")"); if (!componentType.isType("byte")) { output(" / sizeof("); output(componentType.getTypeSignature2(!componentType.equals(componentType64))); output(")"); } output(", ("); output(type.getTypeSignature4(!type.equals(type64), false)); output(")"); if (!accessor.isNonMemberGetter()) output("lpStruct->"); output(accessor.getter()); outputln(");"); output("\t}"); } else { throw new Error("not done"); } } else { outputln("\t{"); if (isCPP) { output("\tjobject lpObject1 = env->GetObjectField(lpObject, "); } else { output("\tjobject lpObject1 = (*env)->GetObjectField(env, lpObject, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); outputln(");"); output("\tif (lpObject1 != NULL) get"); output(simpleName); output("Fields(env, lpObject1, &lpStruct->"); output(accessor.getter()); outputln(");"); output("\t}"); } outputln(); if (conditional != null) { outputln("#endif"); } } } void generateGetFunction(JNIClass clazz) { String clazzName = clazz.getNativeName(); String simpleName = clazz.getSimpleName(); if (clazz.getFlag(ClassFlag.STRUCT) && !clazz.getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(clazzName); output(" *get"); output(simpleName); output("Fields(JNIEnv *env, jobject lpObject, "); if (clazz.getFlag(ClassFlag.STRUCT) && !clazz.getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(clazzName); outputln(" *lpStruct)"); outputln("{"); output("\tif (!"); output(simpleName); output("Fc.cached) cache"); output(simpleName); outputln("Fields(env, lpObject);"); if (clazz.getFlag(ClassFlag.ZERO_OUT)) { outputln("memset(lpStruct, 0, sizeof(struct " + clazzName + "));"); } generateGetFields(clazz); outputln("\treturn lpStruct;"); outputln("}"); } void generateSetFields(JNIClass clazz) { JNIClass superclazz = clazz.getSuperclass(); String clazzName = clazz.getNativeName(); String superName = superclazz.getNativeName(); if (!superclazz.getName().equals("java.lang.Object") && hasNonIgnoredFields(superclazz)) { /* * Windows exception - cannot call get/set function of super class * in this case */ if (!(clazzName.equals(superName + "A") || clazzName.equals(superName + "W"))) { output("\tset"); output(superName); output("Fields(env, lpObject, ("); output(superName); outputln(" *)lpStruct);"); } else { generateSetFields(superclazz); } } List fields = clazz.getDeclaredFields(); for (JNIField field : fields) { if (ignoreField(field)) continue; String conditional = field.getConditional(); if (conditional != null) { outputln("#if " + conditional); } JNIType type = field.getType(), type64 = field.getType64(); boolean allowConversion = !type.equals(type64); String simpleName = type.getSimpleName(); JNIFieldAccessor accessor = field.getAccessor(); if (type.isPrimitive()) { if (isCPP) { output("\tenv->Set"); } else { output("\t(*env)->Set"); } output(type.getTypeSignature1(allowConversion)); if (isCPP) { output("Field(lpObject, "); } else { output("Field(env, lpObject, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); output(", "); output("(" + type.getTypeSignature2(allowConversion) + ")"); if (field.isPointer()) { output("(intptr_t)"); } if (!accessor.isNonMemberGetter()) output("lpStruct->"); if (accessor.isMethodGetter()) { String getterStart = accessor.getter().split("\\(")[0]; output(getterStart + "("); if (accessor.isNonMemberGetter()) output("lpStruct"); if (field.isSharedPointer()) output("->" + field.getName()); output(")"); } else { output(accessor.getter()); } if (field.isSharedPointer()) { output(".get()"); } output(");"); } else if (type.isArray()) { JNIType componentType = type.getComponentType(), componentType64 = type64.getComponentType(); if (componentType.isPrimitive()) { outputln("\t{"); output("\t"); output(type.getTypeSignature2(allowConversion)); output(" lpObject1 = ("); output(type.getTypeSignature2(allowConversion)); if (isCPP) { output(")env->GetObjectField(lpObject, "); } else { output(")(*env)->GetObjectField(env, lpObject, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); outputln(");"); if (isCPP) { output("\tenv->Set"); } else { output("\t(*env)->Set"); } output(componentType.getTypeSignature1(!componentType.equals(componentType64))); if (isCPP) { output("ArrayRegion(lpObject1, 0, sizeof("); } else { output("ArrayRegion(env, lpObject1, 0, sizeof("); } if (!accessor.isNonMemberGetter()) output("lpStruct->"); if (accessor.isMethodGetter()) { String getterStart = accessor.getter().split("\\(")[0]; output(getterStart + "("); if (accessor.isNonMemberGetter()) output("lpStruct"); output(")"); } else { output(accessor.getter()); } output(")"); if (!componentType.isType("byte")) { output(" / sizeof("); output(componentType.getTypeSignature2(!componentType.equals(componentType64))); output(")"); } output(", ("); output(type.getTypeSignature4(allowConversion, false)); output(")"); if (!accessor.isNonMemberGetter()) output("lpStruct->"); output(accessor.getter()); outputln(");"); output("\t}"); } else { throw new Error("not done"); } } else { outputln("\t{"); if (isCPP) { output("\tjobject lpObject1 = env->GetObjectField(lpObject, "); } else { output("\tjobject lpObject1 = (*env)->GetObjectField(env, lpObject, "); } output(field.getDeclaringClass().getSimpleName()); output("Fc."); output(field.getName()); outputln(");"); output("\tif (lpObject1 != NULL) set"); output(simpleName); output("Fields(env, lpObject1, &lpStruct->"); output(accessor.getter()); outputln(");"); output("\t}"); } outputln(); if (conditional != null) { outputln("#endif"); } } } void generateSetFunction(JNIClass clazz) { String clazzName = clazz.getNativeName(); String simpleName = clazz.getSimpleName(); output("void set"); output(simpleName); output("Fields(JNIEnv *env, jobject lpObject, "); if (clazz.getFlag(ClassFlag.STRUCT) && !clazz.getFlag(ClassFlag.TYPEDEF)) { output("struct "); } output(clazzName); outputln(" *lpStruct)"); outputln("{"); output("\tif (!"); output(simpleName); output("Fc.cached) cache"); output(simpleName); outputln("Fields(env, lpObject);"); generateSetFields(clazz); outputln("}"); } void generateFunctions(JNIClass clazz) { generateCacheFunction(clazz); outputln(); generateGetFunction(clazz); outputln(); generateSetFunction(clazz); } boolean ignoreField(JNIField field) { int mods = field.getModifiers(); return field.ignore() || ((mods & Modifier.FINAL) != 0) || ((mods & Modifier.STATIC) != 0); } boolean hasNonIgnoredFields(JNIClass clazz) { for (JNIField field : getStructFields(clazz)) if (!ignoreField(field)) return true; return false; } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/000077500000000000000000000000001475274123300330665ustar00rootroot00000000000000JNIClass.java000077500000000000000000000021711475274123300352640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import java.util.List; import org.fusesource.hawtjni.runtime.ClassFlag; /** * * @author Hiram Chirino */ public interface JNIClass { public boolean getFlag(ClassFlag flag); public String getName(); public String getSimpleName(); public String getNativeName(); public JNIClass getSuperclass(); public List getDeclaredFields(); public List getDeclaredMethods(); public List getNativeMethods(); public boolean getGenerate(); public String getConditional(); } JNIField.java000077500000000000000000000021621475274123300352420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import org.fusesource.hawtjni.runtime.FieldFlag; /** * * @author Hiram Chirino */ public interface JNIField { public boolean getFlag(FieldFlag flag); public String getName(); public int getModifiers(); public JNIType getType(); public JNIType getType64(); public JNIClass getDeclaringClass(); public JNIFieldAccessor getAccessor(); public String getCast(); public String getConditional(); public boolean ignore(); public boolean isSharedPointer(); public boolean isPointer(); } JNIFieldAccessor.java000066400000000000000000000006031475274123300367200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/modelpackage org.fusesource.hawtjni.generator.model; /** * @author Calin Iorgulescu */ public interface JNIFieldAccessor { public String getter(); public String setter(); public boolean isNonMemberGetter(); public boolean isNonMemberSetter(); public boolean isMethodGetter(); public boolean isMethodSetter(); } JNIMethod.java000077500000000000000000000026561475274123300354470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import java.util.List; import org.fusesource.hawtjni.runtime.ArgFlag; import org.fusesource.hawtjni.runtime.MethodFlag; /** * * @author Hiram Chirino */ public interface JNIMethod { public boolean getFlag(MethodFlag flag); public String getName(); public int getModifiers(); public boolean isNativeUnique(); public JNIType getReturnType32(); public JNIType getReturnType64(); public List getParameters(); public List getParameterTypes(); public List getParameterTypes64(); public JNIClass getDeclaringClass(); public String getAccessor(); public String getConditional(); public String getCopy(); public String[] getCallbackTypes(); public ArgFlag[][] getCallbackFlags(); public String getCast(); public boolean isPointer(); } JNIParameter.java000077500000000000000000000017401475274123300361400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import org.fusesource.hawtjni.runtime.ArgFlag; /** * * @author Hiram Chirino */ public interface JNIParameter { public boolean getFlag(ArgFlag flag); public String getCast(); public boolean isPointer(); public JNIMethod getMethod(); public int getParameter(); public JNIClass getTypeClass(); public JNIType getType32(); public JNIType getType64(); } JNIType.java000077500000000000000000000022501475274123300351360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; /** * * @author Hiram Chirino */ public interface JNIType { public boolean isPrimitive(); public boolean isArray(); public JNIType getComponentType(); public boolean isType(String type); public String getName(); public String getSimpleName(); public String getNativeName(); public String getTypeSignature(boolean define); public String getTypeSignature1(boolean define); public String getTypeSignature2(boolean define); public String getTypeSignature3(boolean define); public String getTypeSignature4(boolean define, boolean struct); } ReflectClass.java000077500000000000000000000105751475274123300362370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.fusesource.hawtjni.runtime.ClassFlag; import org.fusesource.hawtjni.runtime.JniClass; /** * * @author Hiram Chirino */ public class ReflectClass implements JNIClass { private Class clazz; private ArrayList fields; private ArrayList methods; private JniClass annotation; private HashSet flags; private String nativeName; public ReflectClass(Class clazz) { this.clazz = clazz; } public String toString() { return clazz.toString(); } public int hashCode() { return clazz.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof ReflectClass)) return false; return ((ReflectClass) obj).clazz.equals(clazz); } public Class getWrapedClass() { return clazz; } /////////////////////////////////////////////////////////////////// // JNIClass interface methods /////////////////////////////////////////////////////////////////// public String getName() { return clazz.getName(); } public JNIClass getSuperclass() { return new ReflectClass(clazz.getSuperclass()); } public String getSimpleName() { return clazz.getSimpleName(); } public String getNativeName() { lazyLoad(); if( nativeName!=null ) return nativeName; else return getSimpleName(); } public List getDeclaredFields() { lazyLoad(); return new ArrayList(fields); } public List getDeclaredMethods() { lazyLoad(); return new ArrayList(methods); } public List getNativeMethods() { ArrayList rc = new ArrayList(); for (JNIMethod method : getDeclaredMethods()) { if ((method.getModifiers() & Modifier.NATIVE) == 0) continue; rc.add(method); } return rc; } public String getConditional() { lazyLoad(); return annotation == null ? null : emptyFilter(annotation.conditional()); } public boolean getGenerate() { return !getFlag(ClassFlag.CLASS_SKIP); } public boolean getFlag(ClassFlag flag) { lazyLoad(); return flags.contains(flag); } /////////////////////////////////////////////////////////////////// // Helper methods /////////////////////////////////////////////////////////////////// static public String emptyFilter(String value) { if( value==null || value.length()==0 ) return null; return value; } private void lazyLoad() { if (fields != null) return; this.annotation = this.clazz.getAnnotation(JniClass.class); this.flags = new HashSet(); if( this.annotation!=null ) { this.flags.addAll(Arrays.asList(this.annotation.flags())); if( this.annotation.name().trim().length() > 0 ) { this.nativeName = this.annotation.name().trim(); } } Field[] fields = clazz.getDeclaredFields(); this.fields = new ArrayList(fields.length); for (Field field : fields) { this.fields.add(new ReflectField(this, field)); } Method[] methods = clazz.getDeclaredMethods(); this.methods = new ArrayList(methods.length); for (Method method : methods) { this.methods.add(new ReflectMethod(this, method)); } } } ReflectField.java000077500000000000000000000115661475274123300362160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashSet; import org.apache.commons.lang.StringUtils; import org.fusesource.hawtjni.runtime.FieldFlag; import org.fusesource.hawtjni.runtime.JniField; import org.fusesource.hawtjni.runtime.T32; import static org.fusesource.hawtjni.generator.util.TextSupport.*; import static org.fusesource.hawtjni.runtime.FieldFlag.*; /** * * @author Hiram Chirino */ public class ReflectField implements JNIField { private ReflectClass parent; private Field field; private ReflectType type; private JniField annotation; private HashSet flags; private boolean allowConversion; private ReflectFieldAccessor accessor; public ReflectField(ReflectClass parent, Field field) { this.parent = parent; this.field = field; lazyLoad(); } public int hashCode() { return field.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof ReflectField)) return false; return ((ReflectField) obj).field.equals(field); } public String toString() { return field.toString(); } /////////////////////////////////////////////////////////////////// // JNIField interface methods /////////////////////////////////////////////////////////////////// public JNIClass getDeclaringClass() { return parent; } public int getModifiers() { return field.getModifiers(); } public String getName() { return field.getName(); } public JNIType getType() { return type.asType32(allowConversion); } public JNIType getType64() { return type.asType64(allowConversion); } public JNIFieldAccessor getAccessor() { return accessor; } public String getCast() { String rc = annotation == null ? "" : annotation.cast().trim(); return cast(rc); } public boolean ignore() { return getFlag(FieldFlag.FIELD_SKIP); } public boolean isPointer() { if( annotation == null ) { return false; } return getFlag(POINTER_FIELD) || ( type.getWrappedClass() == Long.TYPE && getCast().endsWith("*") ); } public boolean isSharedPointer() { if (annotation == null) { return false; } return getFlag(SHARED_PTR); } public String getConditional() { String parentConditional = getDeclaringClass().getConditional(); String myConditional = annotation == null ? null : emptyFilter(annotation.conditional()); if( parentConditional!=null ) { if( myConditional!=null ) { return parentConditional+" && "+myConditional; } else { return parentConditional; } } return myConditional; } public boolean getFlag(FieldFlag flag) { return flags.contains(flag); } /////////////////////////////////////////////////////////////////// // Helper methods /////////////////////////////////////////////////////////////////// static public String emptyFilter(String value) { if( value==null || value.length()==0 ) return null; return value; } private void lazyLoad() { this.type = new ReflectType(field.getType()); this.annotation = this.field.getAnnotation(JniField.class); this.flags = new HashSet(); this.accessor = new ReflectFieldAccessor(this.field.getName()); if( this.annotation!=null ) { this.flags.addAll(Arrays.asList(this.annotation.flags())); if (!StringUtils.isEmpty(this.annotation.accessor())) { this.accessor = new ReflectFieldAccessor(this.annotation.accessor()); } else if (!StringUtils.isEmpty(this.annotation.getter()) && !StringUtils.isEmpty(this.annotation.setter())) { this.accessor = new ReflectFieldAccessor( this.annotation.getter(), this.flags.contains(GETTER_NONMEMBER), this.annotation.setter(), this.flags.contains(SETTER_NONMEMBER)); } } allowConversion = this.field.getAnnotation(T32.class)!=null; } } ReflectFieldAccessor.java000066400000000000000000000022641475274123300376710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/modelpackage org.fusesource.hawtjni.generator.model; /** * @author Calin Iorgulescu */ public class ReflectFieldAccessor implements JNIFieldAccessor { private String getter; private String setter; private boolean nonMemberGetter; private boolean nonMemberSetter; public ReflectFieldAccessor(String value) { this.getter = this.setter = value; this.nonMemberGetter = this.nonMemberSetter = false; } public ReflectFieldAccessor(String getter, boolean nonMemberGetter, String setter, boolean nonMemberSetter) { this.getter = getter; this.nonMemberGetter = nonMemberGetter; this.setter = setter; this.nonMemberSetter = nonMemberSetter; } public String getter() { return getter; } public String setter() { return setter; } public boolean isNonMemberGetter() { return nonMemberGetter; } public boolean isNonMemberSetter() { return nonMemberSetter; } public boolean isMethodGetter() { return getter.contains("("); } public boolean isMethodSetter() { return setter.contains("("); } } ReflectMethod.java000077500000000000000000000161551475274123300364120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.fusesource.hawtjni.runtime.ArgFlag; import org.fusesource.hawtjni.runtime.JniArg; import org.fusesource.hawtjni.runtime.JniMethod; import org.fusesource.hawtjni.runtime.MethodFlag; import org.fusesource.hawtjni.runtime.T32; import static org.fusesource.hawtjni.generator.util.TextSupport.*; import static org.fusesource.hawtjni.runtime.MethodFlag.*; /** * * @author Hiram Chirino */ public class ReflectMethod implements JNIMethod { private ReflectClass declaringClass; private Method method; private List paramTypes32; private List paramTypes64; private List parameters; private boolean unique; private JniMethod annotation; private boolean allowConversion; private ReflectType returnType; private HashSet flags; public ReflectMethod(ReflectClass declaringClass, Method method) { this.declaringClass = declaringClass; this.method = method; lazyLoad(); } public int hashCode() { return method.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof ReflectMethod)) return false; return ((ReflectMethod) obj).method.equals(method); } public String toString() { return method.toString(); } public Method getWrapedMethod() { return method; } /////////////////////////////////////////////////////////////////// // JNIMethod interface methods /////////////////////////////////////////////////////////////////// public JNIClass getDeclaringClass() { return declaringClass; } public int getModifiers() { return method.getModifiers(); } public String getName() { return method.getName(); } public List getParameters() { lazyLoad(); return parameters; } public List getParameterTypes() { lazyLoad(); return paramTypes32; } public List getParameterTypes64() { lazyLoad(); return paramTypes64; } public JNIType getReturnType32() { lazyLoad(); return returnType.asType32(allowConversion); } public JNIType getReturnType64() { lazyLoad(); return returnType.asType64(allowConversion); } public boolean getFlag(MethodFlag flag) { lazyLoad(); return flags.contains(flag); } public String getCast() { lazyLoad(); String rc = annotation == null ? "" : annotation.cast(); return cast(rc); } public boolean isPointer() { lazyLoad(); if( annotation == null ) { return false; } return getFlag(POINTER_RETURN) || ( returnType.getWrappedClass() == Long.TYPE && getCast().endsWith("*)") ); } public String getCopy() { lazyLoad(); return annotation == null ? "" : annotation.copy(); } public String getAccessor() { lazyLoad(); return annotation == null ? "" : annotation.accessor(); } public String getConditional() { lazyLoad(); String parentConditional = getDeclaringClass().getConditional(); String myConditional = annotation == null ? null : emptyFilter(annotation.conditional()); if( parentConditional!=null ) { if( myConditional!=null ) { return parentConditional+" && "+myConditional; } else { return parentConditional; } } return myConditional; } public boolean isNativeUnique() { lazyLoad(); return unique; } public String[] getCallbackTypes() { lazyLoad(); if( annotation==null ) { return new String[0]; } JniArg[] callbackArgs = annotation.callbackArgs(); String[] rc = new String[callbackArgs.length]; for (int i = 0; i < rc.length; i++) { rc[i] = callbackArgs[i].cast(); } return rc; } public ArgFlag[][] getCallbackFlags() { lazyLoad(); if( annotation==null ) { return new ArgFlag[0][]; } JniArg[] callbackArgs = annotation.callbackArgs(); ArgFlag[][] rc = new ArgFlag[callbackArgs.length][]; for (int i = 0; i < rc.length; i++) { rc[i] = callbackArgs[i].flags(); } return rc; } /////////////////////////////////////////////////////////////////// // Helper methods /////////////////////////////////////////////////////////////////// static public String emptyFilter(String value) { if( value==null || value.length()==0 ) return null; return value; } private void lazyLoad() { if( flags!=null ) { return; } this.annotation = this.method.getAnnotation(JniMethod.class); this.allowConversion = method.getAnnotation(T32.class)!=null; this.flags = new HashSet(); if( this.annotation!=null ) { this.flags.addAll(Arrays.asList(this.annotation.flags())); } Class returnType = method.getReturnType(); Class[] paramTypes = method.getParameterTypes(); this.paramTypes32 = new ArrayList(paramTypes.length); this.paramTypes64 = new ArrayList(paramTypes.length); this.parameters = new ArrayList(paramTypes.length); this.returnType = new ReflectType(returnType); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < paramTypes.length; i++) { ReflectParameter parameter = new ReflectParameter(this, i, parameterAnnotations[i]); this.parameters.add(parameter); this.paramTypes32.add( parameter.getType32() ); this.paramTypes64.add( parameter.getType64() ); } unique = true; Class parent = ((ReflectClass)declaringClass).getWrapedClass(); String name = method.getName(); for (Method mth : parent.getDeclaredMethods() ) { if ( (mth.getModifiers()&Modifier.NATIVE) != 0 && method!=mth && !method.equals(mth) && name.equals(mth.getName())) { unique = false; break; } } } } ReflectParameter.java000077500000000000000000000055021475274123300371040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.HashSet; import org.fusesource.hawtjni.runtime.ArgFlag; import org.fusesource.hawtjni.runtime.JniArg; import org.fusesource.hawtjni.runtime.T32; import static org.fusesource.hawtjni.generator.util.TextSupport.*; import static org.fusesource.hawtjni.runtime.ArgFlag.*; /** * * @author Hiram Chirino */ public class ReflectParameter implements JNIParameter { private ReflectMethod method; private ReflectType type; private int parameter; private JniArg annotation; private boolean allowConversion; private HashSet flags; public ReflectParameter(ReflectMethod method, int parameter, Annotation[] annotations) { this.method = method; this.parameter = parameter; this.type = new ReflectType(method.getWrapedMethod().getParameterTypes()[parameter]); this.flags = new HashSet(); if( annotations!=null ) { for (Annotation annotation : annotations) { if( annotation instanceof JniArg ) { this.annotation = (JniArg) annotation; this.flags.addAll(Arrays.asList(this.annotation.flags())); } else if( annotation instanceof T32 ) { this.allowConversion = true; } } } } public String getCast() { String rc = annotation == null ? "" : annotation.cast(); return cast(rc); } public boolean isPointer() { if( annotation == null ) { return false; } return getFlag(POINTER_ARG) || ( type.getWrappedClass() == Long.TYPE && getCast().endsWith("*)") ); } public JNIMethod getMethod() { return method; } public boolean getFlag(ArgFlag flag) { return flags.contains(flag); } public JNIType getType32() { return type.asType32(allowConversion); } public JNIType getType64() { return type.asType64(allowConversion); } public JNIClass getTypeClass() { ReflectType type = (ReflectType) getType32(); return new ReflectClass(type.getWrappedClass()); } public int getParameter() { return parameter; } } ReflectType.java000077500000000000000000000171261475274123300361120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/model/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.model; import org.fusesource.hawtjni.runtime.JniClass; /** * * @author Hiram Chirino */ public class ReflectType implements JNIType { private Class clazz; public ReflectType(Class clazz) { this.clazz = clazz; } public int hashCode() { return clazz.hashCode(); } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof ReflectType)) return false; return ((ReflectType) obj).clazz == clazz; } public Class getWrappedClass() { return clazz; } public ReflectType asType32(boolean allowConversion) { if (allowConversion) { if (clazz == long.class) return new ReflectType(int.class); else if (clazz == long[].class) return new ReflectType(int[].class); else if (clazz == double.class) return new ReflectType(float.class); else if (clazz == double[].class) return new ReflectType(float[].class); } return this; } public ReflectType asType64(boolean allowConversion) { if (allowConversion) { if (clazz == int.class) return new ReflectType(long.class); else if (clazz == int[].class) return new ReflectType(long[].class); else if (clazz == float.class) return new ReflectType(double.class); else if (clazz == float[].class) return new ReflectType(double[].class); } return this; } public JNIType getComponentType() { return new ReflectType(clazz.getComponentType()); } public String getName() { return clazz.getName(); } public String getSimpleName() { return clazz.getSimpleName(); } public String getNativeName() { JniClass annotation = clazz.getAnnotation(JniClass.class); if( annotation==null ) { return getSimpleName(); } else { String name = annotation.name().trim(); if( name.length()==0 ) { return getSimpleName(); } else { return name; } } } public String getTypeSignature(boolean define) { if (clazz == Void.TYPE) return "V"; if (clazz == Integer.TYPE) return define ? "I_J" : "I"; if (clazz == Boolean.TYPE) return "Z"; if (clazz == Long.TYPE) return define ? "J_J" : "J"; if (clazz == Short.TYPE) return "S"; if (clazz == Character.TYPE) return "C"; if (clazz == Byte.TYPE) return "B"; if (clazz == Float.TYPE) return define ? "F_D" : "F"; if (clazz == Double.TYPE) return define ? "F_D" : "D"; if (clazz == String.class) return "Ljava/lang/String;"; if (clazz.isArray()) { if (define) return getComponentType().getTypeSignature(define) + "Array"; return "[" + getComponentType().getTypeSignature(define); } return "L" + clazz.getName().replace('.', '/') + ";"; } public String getTypeSignature1(boolean define) { if (clazz == Void.TYPE) return "Void"; if (clazz == Integer.TYPE) return define ? "IntLong" : "Int"; if (clazz == Boolean.TYPE) return "Boolean"; if (clazz == Long.TYPE) return define ? "IntLong" : "Long"; if (clazz == Short.TYPE) return "Short"; if (clazz == Character.TYPE) return "Char"; if (clazz == Byte.TYPE) return "Byte"; if (clazz == Float.TYPE) return define ? "FloatDouble" : "Float"; if (clazz == Double.TYPE) return define ? "FloatDouble" : "Double"; if (clazz == String.class) return "String"; return "Object"; } public String getTypeSignature2(boolean define) { if (clazz == Void.TYPE) return "void"; if (clazz == Integer.TYPE) return define ? "jintLong" : "jint"; if (clazz == Boolean.TYPE) return "jboolean"; if (clazz == Long.TYPE) return define ? "jintLong" : "jlong"; if (clazz == Short.TYPE) return "jshort"; if (clazz == Character.TYPE) return "jchar"; if (clazz == Byte.TYPE) return "jbyte"; if (clazz == Float.TYPE) return define ? "jfloatDouble" : "jfloat"; if (clazz == Double.TYPE) return define ? "jfloatDouble" : "jdouble"; if (clazz == String.class) return "jstring"; if (clazz == Class.class) return "jclass"; if (clazz.isArray()) { return getComponentType().getTypeSignature2(define) + "Array"; } return "jobject"; } public String getTypeSignature3(boolean define) { if (clazz == Void.TYPE) return "void"; if (clazz == Integer.TYPE) return "int"; if (clazz == Boolean.TYPE) return "boolean"; if (clazz == Long.TYPE) return "long"; if (clazz == Short.TYPE) return "short"; if (clazz == Character.TYPE) return "char"; if (clazz == Byte.TYPE) return "byte"; if (clazz == Float.TYPE) return "float"; if (clazz == Double.TYPE) return "double"; if (clazz == String.class) return "String"; if (clazz.isArray()) { return getComponentType().getTypeSignature3(define) + "[]"; } return clazz.getName(); } public String getTypeSignature4(boolean define, boolean struct) { if (clazz == Void.TYPE) return "void"; if (clazz == Integer.TYPE) return define ? "jintLong" : "jint"; if (clazz == Boolean.TYPE) return "jboolean"; if (clazz == Long.TYPE) return define ? "jintLong" : "jlong"; if (clazz == Short.TYPE) return "jshort"; if (clazz == Character.TYPE) return "jchar"; if (clazz == Byte.TYPE) return "jbyte"; if (clazz == Float.TYPE) return define ? "jfloatDouble" : "jfloat"; if (clazz == Double.TYPE) return define ? "jfloatDouble" : "jdouble"; if (clazz == String.class) return "jstring"; if (clazz.isArray()) { String sig = getComponentType().getTypeSignature4(define, struct); return struct ? sig : sig + " *"; } String sig = getNativeName(); return struct ? sig : sig + " *"; } public boolean isArray() { return clazz.isArray(); } public boolean isPrimitive() { return clazz.isPrimitive(); } public boolean isType(String type) { return clazz.getName().equals(type); } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/util/000077500000000000000000000000001475274123300327435ustar00rootroot00000000000000FileSupport.java000066400000000000000000000052661475274123300360140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/util/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.util; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * * @author Hiram Chirino */ public class FileSupport { public static boolean write(byte[] bytes, File file) throws IOException { if( !equals(bytes, file) ) { FileOutputStream out = new FileOutputStream(file); try { out.write(bytes); } finally { out.close(); } return true; } return false; } public static void copy(InputStream is, OutputStream os) throws IOException { try { byte data[] = new byte[1024*4]; int count; while( (count=is.read(data, 0, data.length))>=0 ) { os.write(data, 0, count); } } finally { close(is); close(os); } } public static boolean equals(byte[] bytes, File file) throws IOException { FileInputStream is = null; try { is = new FileInputStream(file); return equals(new ByteArrayInputStream(bytes), new BufferedInputStream(is)); } catch (FileNotFoundException e) { return false; } finally { close(is); } } public static void close(InputStream is) { try { if (is != null) is.close(); } catch (Throwable e) { } } public static void close(OutputStream ioss) { try { if (ioss != null) ioss.close(); } catch (Throwable e) { } } public static boolean equals(InputStream is1, InputStream is2) throws IOException { while (true) { int c1 = is1.read(); int c2 = is2.read(); if (c1 != c2) return false; if (c1 == -1) break; } return true; } } OptionBuilder.java000066400000000000000000000047221475274123300363130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/util/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.util; import org.apache.commons.cli.Option; /** * a better version of org.apache.commons.cli.OptionBuilder * IDE provides nicer auto complete and less compiler warnings. * * @author Hiram Chirino */ public class OptionBuilder { private String id; private String name; private String description; private boolean required; private boolean optional; private int args =-1; private String arg; private Object type; private char sperator; public static OptionBuilder ob() { return new OptionBuilder(); } public Option op() { Option option = new Option( id!=null ? id : " ", description ); option.setLongOpt(name); option.setRequired( required ); option.setOptionalArg(optional); option.setType( type ); option.setValueSeparator(sperator); if( arg !=null && args==-1 ) { args=1; } option.setArgs(args); option.setArgName(arg); return option; } public OptionBuilder arg(String argName) { this.arg = argName; return this; } public OptionBuilder args(int args) { this.args = args; return this; } public OptionBuilder description(String description) { this.description = description; return this; } public OptionBuilder name(String lname) { this.name = lname; return this; } public OptionBuilder id(String name) { this.id = name; return this; } public OptionBuilder optional(boolean optional) { this.optional = optional; return this; } public OptionBuilder required(boolean required) { this.required = required; return this; } public OptionBuilder sperator(char sperator) { this.sperator = sperator; return this; } public OptionBuilder type(Object type) { this.type = type; return this; } }TextSupport.java000066400000000000000000000015431475274123300360530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/util/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.fusesource.hawtjni.generator.util; /** * * @author Hiram Chirino */ public class TextSupport { static public String cast(String cast) { cast = cast.trim(); if (cast.length() > 0) { if (!cast.startsWith("(") || !cast.endsWith(")")) cast = "(" + cast + ")"; } return cast; } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/resources/000077500000000000000000000000001475274123300244535ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/resources/hawtjni-callback.c000077500000000000000000000537111475274123300300270ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /* == HEADER-SNIP-LOCATION == */ #include "hawtjni.h" #include #include /* define this to print out debug statements */ /* #define DEBUG_CALL_PRINTS */ /* --------------- callback globals ----------------- */ #if defined (_WIN32) || defined (_WIN32_WCE) #include "windows.h" #define RETURN_TYPE LRESULT CALLBACK #define RETURN_CAST (LRESULT) #endif #ifndef RETURN_TYPE #define RETURN_TYPE jintLong #endif #ifndef RETURN_CAST #define RETURN_CAST #endif /* * Note that only x86 assembler is supported */ #if !(defined(__i386__) || defined(_M_IX86) || defined(_X86_)) #undef USE_ASSEMBLER #endif #ifdef REDUCED_CALLBACKS #define MAX_CALLBACKS 16 #else #ifdef USE_ASSEMBLER #define MAX_CALLBACKS 256 #else #define MAX_CALLBACKS 128 #endif #endif /* REDUCED_CALLBACKS */ #define MAX_ARGS 12 typedef struct CALLBACK_DATA { jobject callback; jmethodID methodID; jobject object; jboolean isStatic; jboolean isArrayBased; jint argCount; jlong errorResult; } CALLBACK_DATA; static JavaVM *jvm = NULL; static CALLBACK_DATA callbackData[MAX_CALLBACKS]; static int callbackEnabled = 1; static int callbackEntryCount = 0; static int initialized = 0; static jint JNI_VERSION = 0; #ifdef DEBUG_CALL_PRINTS static int counter = 0; #endif #ifdef ATOMIC #include #define ATOMIC_INC(value) OSAtomicIncrement32(&value); #define ATOMIC_DEC(value) OSAtomicDecrement32(&value); #else #define ATOMIC_INC(value) value++; #define ATOMIC_DEC(value) value--; #endif jintLong callback(int index, ...); #ifdef USE_ASSEMBLER #if !(defined (_WIN32) || defined (_WIN32_WCE)) #include #endif static unsigned char *callbackCode = NULL; #define CALLBACK_THUNK_SIZE 64 #else /* ------------- Start: class Callback impl --------------- */ /* Function name from index and number of arguments */ #define FN(index, args) fn##index##_##args /** * Functions templates * * NOTE: If the maximum number of arguments changes (MAX_ARGS), the number * of function templates has to change accordingly. */ /* Function template with no arguments */ #define FN_0(index) RETURN_TYPE FN(index, 0)() { return RETURN_CAST callback(index); } /* Function template with 1 argument */ #define FN_1(index) RETURN_TYPE FN(index, 1)(jintLong p1) { return RETURN_CAST callback(index, p1); } /* Function template with 2 arguments */ #define FN_2(index) RETURN_TYPE FN(index, 2)(jintLong p1, jintLong p2) { return RETURN_CAST callback(index, p1, p2); } /* Function template with 3 arguments */ #define FN_3(index) RETURN_TYPE FN(index, 3)(jintLong p1, jintLong p2, jintLong p3) { return RETURN_CAST callback(index, p1, p2, p3); } /* Function template with 4 arguments */ #define FN_4(index) RETURN_TYPE FN(index, 4)(jintLong p1, jintLong p2, jintLong p3, jintLong p4) { return RETURN_CAST callback(index, p1, p2, p3, p4); } /* Function template with 5 arguments */ #define FN_5(index) RETURN_TYPE FN(index, 5)(jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5); } /* Function template with 6 arguments */ #define FN_6(index) RETURN_TYPE FN(index, 6)(jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6); } /* Function template with 7 arguments */ #define FN_7(index) RETURN_TYPE FN(index, 7)(jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6, jintLong p7) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6, p7); } /* Function template with 8 arguments */ #define FN_8(index) RETURN_TYPE FN(index, 8)(jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6, jintLong p7, jintLong p8) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6, p7, p8); } /* Function template with 9 arguments */ #define FN_9(index) RETURN_TYPE FN(index, 9)(jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6, jintLong p7, jintLong p8, jintLong p9) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6, p7, p8, p9); } /* Function template with 10 arguments */ #define FN_10(index) RETURN_TYPE FN(index, 10) (jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6, jintLong p7, jintLong p8, jintLong p9, jintLong p10) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } /* Function template with 11 arguments */ #define FN_11(index) RETURN_TYPE FN(index, 11) (jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6, jintLong p7, jintLong p8, jintLong p9, jintLong p10, jintLong p11) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); } /* Function template with 12 arguments */ #define FN_12(index) RETURN_TYPE FN(index, 12) (jintLong p1, jintLong p2, jintLong p3, jintLong p4, jintLong p5, jintLong p6, jintLong p7, jintLong p8, jintLong p9, jintLong p10, jintLong p11, jintLong p12) { return RETURN_CAST callback(index, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); } /** * Define all functions with the specified number of arguments. * * NOTE: If the maximum number of callbacks changes (MAX_CALLBACKS), * this macro has to be updated. */ #if MAX_CALLBACKS == 16 #define FN_BLOCK(args) \ FN_##args(0) \ FN_##args(1) \ FN_##args(2) \ FN_##args(3) \ FN_##args(4) \ FN_##args(5) \ FN_##args(6) \ FN_##args(7) \ FN_##args(8) \ FN_##args(9) \ FN_##args(10) \ FN_##args(11) \ FN_##args(12) \ FN_##args(13) \ FN_##args(14) \ FN_##args(15) #elif MAX_CALLBACKS == 128 #define FN_BLOCK(args) \ FN_##args(0) \ FN_##args(1) \ FN_##args(2) \ FN_##args(3) \ FN_##args(4) \ FN_##args(5) \ FN_##args(6) \ FN_##args(7) \ FN_##args(8) \ FN_##args(9) \ FN_##args(10) \ FN_##args(11) \ FN_##args(12) \ FN_##args(13) \ FN_##args(14) \ FN_##args(15) \ FN_##args(16) \ FN_##args(17) \ FN_##args(18) \ FN_##args(19) \ FN_##args(20) \ FN_##args(21) \ FN_##args(22) \ FN_##args(23) \ FN_##args(24) \ FN_##args(25) \ FN_##args(26) \ FN_##args(27) \ FN_##args(28) \ FN_##args(29) \ FN_##args(30) \ FN_##args(31) \ FN_##args(32) \ FN_##args(33) \ FN_##args(34) \ FN_##args(35) \ FN_##args(36) \ FN_##args(37) \ FN_##args(38) \ FN_##args(39) \ FN_##args(40) \ FN_##args(41) \ FN_##args(42) \ FN_##args(43) \ FN_##args(44) \ FN_##args(45) \ FN_##args(46) \ FN_##args(47) \ FN_##args(48) \ FN_##args(49) \ FN_##args(50) \ FN_##args(51) \ FN_##args(52) \ FN_##args(53) \ FN_##args(54) \ FN_##args(55) \ FN_##args(56) \ FN_##args(57) \ FN_##args(58) \ FN_##args(59) \ FN_##args(60) \ FN_##args(61) \ FN_##args(62) \ FN_##args(63) \ FN_##args(64) \ FN_##args(65) \ FN_##args(66) \ FN_##args(67) \ FN_##args(68) \ FN_##args(69) \ FN_##args(70) \ FN_##args(71) \ FN_##args(72) \ FN_##args(73) \ FN_##args(74) \ FN_##args(75) \ FN_##args(76) \ FN_##args(77) \ FN_##args(78) \ FN_##args(79) \ FN_##args(80) \ FN_##args(81) \ FN_##args(82) \ FN_##args(83) \ FN_##args(84) \ FN_##args(85) \ FN_##args(86) \ FN_##args(87) \ FN_##args(88) \ FN_##args(89) \ FN_##args(90) \ FN_##args(91) \ FN_##args(92) \ FN_##args(93) \ FN_##args(94) \ FN_##args(95) \ FN_##args(96) \ FN_##args(97) \ FN_##args(98) \ FN_##args(99) \ FN_##args(100) \ FN_##args(101) \ FN_##args(102) \ FN_##args(103) \ FN_##args(104) \ FN_##args(105) \ FN_##args(106) \ FN_##args(107) \ FN_##args(108) \ FN_##args(109) \ FN_##args(110) \ FN_##args(111) \ FN_##args(112) \ FN_##args(113) \ FN_##args(114) \ FN_##args(115) \ FN_##args(116) \ FN_##args(117) \ FN_##args(118) \ FN_##args(119) \ FN_##args(120) \ FN_##args(121) \ FN_##args(122) \ FN_##args(123) \ FN_##args(124) \ FN_##args(125) \ FN_##args(126) \ FN_##args(127) #else #error Invalid MAX_CALLBACKS #endif /* MAX_CALLBACKS == 16 */ /** * Define all callback functions. * * NOTE: If the maximum number of arguments changes (MAX_ARGS), the following * has to change accordinglly. */ FN_BLOCK(0) FN_BLOCK(1) FN_BLOCK(2) FN_BLOCK(3) FN_BLOCK(4) FN_BLOCK(5) FN_BLOCK(6) FN_BLOCK(7) FN_BLOCK(8) FN_BLOCK(9) FN_BLOCK(10) FN_BLOCK(11) FN_BLOCK(12) /** * Initialize the function pointers for the callback routines. * * NOTE: If MAX_ARGS or MAX_CALLBACKS changes, the following has to be updated. */ #if MAX_CALLBACKS == 16 #define FN_A_BLOCK(args) { \ (jintLong)FN(0, args), \ (jintLong)FN(1, args), \ (jintLong)FN(2, args), \ (jintLong)FN(3, args), \ (jintLong)FN(4, args), \ (jintLong)FN(5, args), \ (jintLong)FN(6, args), \ (jintLong)FN(7, args), \ (jintLong)FN(8, args), \ (jintLong)FN(9, args), \ (jintLong)FN(10, args), \ (jintLong)FN(11, args), \ (jintLong)FN(12, args), \ (jintLong)FN(13, args), \ (jintLong)FN(14, args), \ (jintLong)FN(15, args), \ }, #elif MAX_CALLBACKS == 128 #define FN_A_BLOCK(args) { \ (jintLong)FN(0, args), \ (jintLong)FN(1, args), \ (jintLong)FN(2, args), \ (jintLong)FN(3, args), \ (jintLong)FN(4, args), \ (jintLong)FN(5, args), \ (jintLong)FN(6, args), \ (jintLong)FN(7, args), \ (jintLong)FN(8, args), \ (jintLong)FN(9, args), \ (jintLong)FN(10, args), \ (jintLong)FN(11, args), \ (jintLong)FN(12, args), \ (jintLong)FN(13, args), \ (jintLong)FN(14, args), \ (jintLong)FN(15, args), \ (jintLong)FN(16, args), \ (jintLong)FN(17, args), \ (jintLong)FN(18, args), \ (jintLong)FN(19, args), \ (jintLong)FN(20, args), \ (jintLong)FN(21, args), \ (jintLong)FN(22, args), \ (jintLong)FN(23, args), \ (jintLong)FN(24, args), \ (jintLong)FN(25, args), \ (jintLong)FN(26, args), \ (jintLong)FN(27, args), \ (jintLong)FN(28, args), \ (jintLong)FN(29, args), \ (jintLong)FN(30, args), \ (jintLong)FN(31, args), \ (jintLong)FN(32, args), \ (jintLong)FN(33, args), \ (jintLong)FN(34, args), \ (jintLong)FN(35, args), \ (jintLong)FN(36, args), \ (jintLong)FN(37, args), \ (jintLong)FN(38, args), \ (jintLong)FN(39, args), \ (jintLong)FN(40, args), \ (jintLong)FN(41, args), \ (jintLong)FN(42, args), \ (jintLong)FN(43, args), \ (jintLong)FN(44, args), \ (jintLong)FN(45, args), \ (jintLong)FN(46, args), \ (jintLong)FN(47, args), \ (jintLong)FN(48, args), \ (jintLong)FN(49, args), \ (jintLong)FN(50, args), \ (jintLong)FN(51, args), \ (jintLong)FN(52, args), \ (jintLong)FN(53, args), \ (jintLong)FN(54, args), \ (jintLong)FN(55, args), \ (jintLong)FN(56, args), \ (jintLong)FN(57, args), \ (jintLong)FN(58, args), \ (jintLong)FN(59, args), \ (jintLong)FN(60, args), \ (jintLong)FN(61, args), \ (jintLong)FN(62, args), \ (jintLong)FN(63, args), \ (jintLong)FN(64, args), \ (jintLong)FN(65, args), \ (jintLong)FN(66, args), \ (jintLong)FN(67, args), \ (jintLong)FN(68, args), \ (jintLong)FN(69, args), \ (jintLong)FN(70, args), \ (jintLong)FN(71, args), \ (jintLong)FN(72, args), \ (jintLong)FN(73, args), \ (jintLong)FN(74, args), \ (jintLong)FN(75, args), \ (jintLong)FN(76, args), \ (jintLong)FN(77, args), \ (jintLong)FN(78, args), \ (jintLong)FN(79, args), \ (jintLong)FN(80, args), \ (jintLong)FN(81, args), \ (jintLong)FN(82, args), \ (jintLong)FN(83, args), \ (jintLong)FN(84, args), \ (jintLong)FN(85, args), \ (jintLong)FN(86, args), \ (jintLong)FN(87, args), \ (jintLong)FN(88, args), \ (jintLong)FN(89, args), \ (jintLong)FN(90, args), \ (jintLong)FN(91, args), \ (jintLong)FN(92, args), \ (jintLong)FN(93, args), \ (jintLong)FN(94, args), \ (jintLong)FN(95, args), \ (jintLong)FN(96, args), \ (jintLong)FN(97, args), \ (jintLong)FN(98, args), \ (jintLong)FN(99, args), \ (jintLong)FN(100, args), \ (jintLong)FN(101, args), \ (jintLong)FN(102, args), \ (jintLong)FN(103, args), \ (jintLong)FN(104, args), \ (jintLong)FN(105, args), \ (jintLong)FN(106, args), \ (jintLong)FN(107, args), \ (jintLong)FN(108, args), \ (jintLong)FN(109, args), \ (jintLong)FN(110, args), \ (jintLong)FN(111, args), \ (jintLong)FN(112, args), \ (jintLong)FN(113, args), \ (jintLong)FN(114, args), \ (jintLong)FN(115, args), \ (jintLong)FN(116, args), \ (jintLong)FN(117, args), \ (jintLong)FN(118, args), \ (jintLong)FN(119, args), \ (jintLong)FN(120, args), \ (jintLong)FN(121, args), \ (jintLong)FN(122, args), \ (jintLong)FN(123, args), \ (jintLong)FN(124, args), \ (jintLong)FN(125, args), \ (jintLong)FN(126, args), \ (jintLong)FN(127, args), \ }, #else #error Invalid MAX_CALLBACKS #endif /* MAX_CALLBACKS == 16 */ jintLong fnx_array[MAX_ARGS+1][MAX_CALLBACKS] = { FN_A_BLOCK(0) FN_A_BLOCK(1) FN_A_BLOCK(2) FN_A_BLOCK(3) FN_A_BLOCK(4) FN_A_BLOCK(5) FN_A_BLOCK(6) FN_A_BLOCK(7) FN_A_BLOCK(8) FN_A_BLOCK(9) FN_A_BLOCK(10) FN_A_BLOCK(11) FN_A_BLOCK(12) }; #endif /* USE_ASSEMBLER */ /* --------------- class Callback Native Methods --------------- */ JNIEXPORT jlong JNICALL Java_org_fusesource_hawtjni_runtime_Callback_bind (JNIEnv *env, jclass that, jobject callbackObject, jobject object, jstring method, jstring signature, jint argCount, jboolean isStatic, jboolean isArrayBased, jlong errorResult) { int i; jmethodID mid = NULL; jclass javaClass = that; const char *methodString = NULL, *sigString = NULL; if (jvm == NULL) (*env)->GetJavaVM(env, &jvm); if (JNI_VERSION == 0) JNI_VERSION = (*env)->GetVersion(env); if (!initialized) { memset(&callbackData, 0, sizeof(callbackData)); initialized = 1; } if (method) methodString = (const char *) (*env)->GetStringUTFChars(env, method, NULL); if (signature) sigString = (const char *) (*env)->GetStringUTFChars(env, signature, NULL); if (object && methodString && sigString) { if (isStatic) { mid = (*env)->GetStaticMethodID(env, object, methodString, sigString); } else { javaClass = (*env)->GetObjectClass(env, object); mid = (*env)->GetMethodID(env, javaClass, methodString, sigString); } } if (method && methodString) (*env)->ReleaseStringUTFChars(env, method, methodString); if (signature && sigString) (*env)->ReleaseStringUTFChars(env, signature, sigString); if (mid == 0) goto fail; for (i=0; iNewGlobalRef(env, callbackObject)) == NULL) goto fail; if ((callbackData[i].object = (*env)->NewGlobalRef(env, object)) == NULL) goto fail; callbackData[i].isStatic = isStatic; callbackData[i].isArrayBased = isArrayBased; callbackData[i].argCount = argCount; callbackData[i].errorResult = errorResult; callbackData[i].methodID = mid; #ifndef USE_ASSEMBLER return (jintLong) fnx_array[argCount][i]; #else { int j = 0, k; unsigned char* code; #ifdef __APPLE__ int pad = 0; #endif if (callbackCode == NULL) { #if defined (_WIN32) || defined (_WIN32_WCE) callbackCode = VirtualAlloc(NULL, CALLBACK_THUNK_SIZE * MAX_CALLBACKS, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (callbackCode == NULL) return 0; #else callbackCode = mmap(NULL, CALLBACK_THUNK_SIZE * MAX_CALLBACKS, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (callbackCode == MAP_FAILED) return 0; #endif } code = (unsigned char *)(callbackCode + (i * CALLBACK_THUNK_SIZE)); //PUSH EBP - 1 byte code[j++] = 0x55; //MOV EBP,ESP - 2 bytes code[j++] = 0x8b; code[j++] = 0xec; #ifdef __APPLE__ /* darwin calling conventions require that the stack be aligned on a 16-byte boundary. */ k = (argCount+3)*sizeof(jintLong); pad = ((k + 15) & ~15) - k; if (pad > 0) { //SUB ESP,pad - 3 bytes code[j++] = 0x83; code[j++] = 0xec; code[j++] = pad; } #endif // 3*argCount bytes for (k=(argCount + 1) * sizeof(jintLong); k >= sizeof(jintLong)*2; k -= sizeof(jintLong)) { //PUSH SS:[EBP+k] code[j++] = 0xff; code[j++] = 0x75; code[j++] = k; } if (i > 127) { //PUSH i - 5 bytes code[j++] = 0x68; code[j++] = ((i >> 0) & 0xFF); code[j++] = ((i >> 8) & 0xFF); code[j++] = ((i >> 16) & 0xFF); code[j++] = ((i >> 24) & 0xFF); } else { //PUSH i - 2 bytes code[j++] = 0x6a; code[j++] = i; } //MOV EAX callback - 1 + sizeof(jintLong) bytes code[j++] = 0xb8; ((jintLong *)&code[j])[0] = (jintLong)&callback; j += sizeof(jintLong); //CALL EAX - 2 bytes code[j++] = 0xff; code[j++] = 0xd0; //ADD ESP,(argCount + 1) * sizeof(jintLong) - 3 bytes code[j++] = 0x83; code[j++] = 0xc4; #ifdef __APPLE__ code[j++] = (unsigned char)(pad + ((argCount + 1) * sizeof(jintLong))); #else code[j++] = (unsigned char)((argCount + 1) * sizeof(jintLong)); #endif //POP EBP - 1 byte code[j++] = 0x5d; #if defined (_WIN32) || defined (_WIN32_WCE) //RETN argCount * sizeof(jintLong) - 3 bytes code[j++] = 0xc2; code[j++] = (unsigned char)(argCount * sizeof(jintLong)); code[j++] = 0x00; #else //RETN - 1 byte code[j++] = 0xc3; #endif if (j > CALLBACK_THUNK_SIZE) { jclass errorClass = (*env)->FindClass(env, "java/lang/Error"); (*env)->ThrowNew(env, errorClass, "Callback thunk overflow"); } return (jintLong)code; } #endif /* USE_ASSEMBLER */ } } fail: return 0; } JNIEXPORT void JNICALL Java_org_fusesource_hawtjni_runtime_Callback_unbind (JNIEnv *env, jclass that, jobject callback) { int i; for (i=0; iIsSameObject(env, callback, callbackData[i].callback)) { if (callbackData[i].callback != NULL) (*env)->DeleteGlobalRef(env, callbackData[i].callback); if (callbackData[i].object != NULL) (*env)->DeleteGlobalRef(env, callbackData[i].object); memset(&callbackData[i], 0, sizeof(CALLBACK_DATA)); } } } JNIEXPORT jboolean JNICALL Java_org_eclipse_swt_internal_Callback_getEnabled (JNIEnv *env, jclass that) { return (jboolean)callbackEnabled; } JNIEXPORT jint JNICALL Java_org_eclipse_swt_internal_Callback_getEntryCount (JNIEnv *env, jclass that) { return (jint)callbackEntryCount; } JNIEXPORT void JNICALL Java_org_eclipse_swt_internal_Callback_setEnabled (JNIEnv *env, jclass that, jboolean enable) { callbackEnabled = enable; } JNIEXPORT void JNICALL Java_org_eclipse_swt_internal_Callback_reset (JNIEnv *env, jclass that) { memset((void *)&callbackData, 0, sizeof(callbackData)); } jintLong callback(int index, ...) { if (!callbackEnabled) return 0; { JNIEnv *env = NULL; jmethodID mid = callbackData[index].methodID; jobject object = callbackData[index].object; jboolean isStatic = callbackData[index].isStatic; jboolean isArrayBased = callbackData[index].isArrayBased; jint argCount = callbackData[index].argCount; jlong result = callbackData[index].errorResult; int detach = 0; va_list vl; #ifdef DEBUG_CALL_PRINTS fprintf(stderr, "* callback starting %d\n", counter++); #endif #ifdef JNI_VERSION_1_2 if (IS_JNI_1_2) { (*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_2); } #endif #ifdef JNI_VERSION_1_4 if (env == NULL) { if (JNI_VERSION >= JNI_VERSION_1_4) { (*jvm)->AttachCurrentThreadAsDaemon(jvm, (void **)&env, NULL); } } #endif if (env == NULL) { (*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL); if (IS_JNI_1_2) detach = 1; } /* If the current thread is not attached to the VM, it is not possible to call into the VM */ if (env == NULL) { #ifdef DEBUG_CALL_PRINTS fprintf(stderr, "* could not get env\n"); #endif goto noEnv; } /* If an exception has occurred in previous callbacks do not call into the VM. */ if ((*env)->ExceptionOccurred(env)) { goto done; } /* Call into the VM. */ ATOMIC_INC(callbackEntryCount); va_start(vl, index); if (isArrayBased) { int i; jintLongArray argsArray = (*env)->NewIntLongArray(env, argCount); if (argsArray != NULL) { jintLong *elements = (*env)->GetIntLongArrayElements(env, argsArray, NULL); if (elements != NULL) { for (i=0; iReleaseIntLongArrayElements(env, argsArray, elements, 0); if (isStatic) { result = (*env)->CallStaticIntLongMethod(env, object, mid, argsArray); } else { result = (*env)->CallIntLongMethod(env, object, mid, argsArray); } } /* * This function may be called many times before returning to Java, * explicitly delete local references to avoid GP's in certain VMs. */ (*env)->DeleteLocalRef(env, argsArray); } } else { if (isStatic) { result = (*env)->CallStaticIntLongMethodV(env, object, mid, vl); } else { result = (*env)->CallIntLongMethodV(env, object, mid, vl); } } va_end(vl); ATOMIC_DEC(callbackEntryCount); done: /* If an exception has occurred in Java, return the error result. */ if ((*env)->ExceptionOccurred(env)) { #ifdef DEBUG_CALL_PRINTS fprintf(stderr, "* java exception occurred\n"); (*env)->ExceptionDescribe(env); #endif result = callbackData[index].errorResult; } if (detach) { (*jvm)->DetachCurrentThread(jvm); env = NULL; } noEnv: #ifdef DEBUG_CALL_PRINTS fprintf(stderr, "* callback exiting %d\n", --counter); #endif return result; } } /* ------------- END: class Callback impl --------------- */ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/resources/hawtjni.c000077500000000000000000000102201475274123300262610ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /* == HEADER-SNIP-LOCATION == */ #include "hawtjni.h" #include #include #include int IS_JNI_1_2 = 0; #ifdef HAVE_PTHREAD_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef JNI_VERSION_1_2 JavaVM *JVM; #ifdef HAVE_PTHREAD_H pthread_key_t JNI_ATTACH_THREAD_LOCAL_KEY; #endif jint hawtjni_attach_thread(JNIEnv **env, const char *thread_name) { JavaVMAttachArgs args; args.version = JNI_VERSION_1_2; args.name = (char *)thread_name; args.group = 0; #ifdef HAVE_PTHREAD_H if( JNI_ATTACH_THREAD_LOCAL_KEY ) { *env = pthread_getspecific(JNI_ATTACH_THREAD_LOCAL_KEY); if( ! *env ) { if( (*JVM)->AttachCurrentThread(JVM, (void**)env, &args)==0 ) { pthread_setspecific(JNI_ATTACH_THREAD_LOCAL_KEY, *env); } else { return -1; } } return 0; } else { return (*JVM)->AttachCurrentThread(JVM, (void**)env, &args); } #else return (*JVM)->AttachCurrentThread(JVM, (void**)env, &args); #endif } jint hawtjni_detach_thread() { #ifdef HAVE_PTHREAD_H if( JNI_ATTACH_THREAD_LOCAL_KEY ) { // Don't actually detach.. that will automatically // happen when the the thread dies. return 0; } else { return (*JVM)->DetachCurrentThread(JVM); } #else return (*JVM)->DetachCurrentThread(JVM); #endif } #ifdef HAVE_PTHREAD_H void hawtjni_thread_cleanup(void *data) { if( data ) { (*JVM)->DetachCurrentThread(JVM); pthread_setspecific(JNI_ATTACH_THREAD_LOCAL_KEY, 0); } } #endif JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { IS_JNI_1_2 = 1; JVM = vm; #ifdef HAVE_PTHREAD_H if( pthread_key_create(&JNI_ATTACH_THREAD_LOCAL_KEY, hawtjni_thread_cleanup) ) { JNI_ATTACH_THREAD_LOCAL_KEY = 0; } #endif return JNI_VERSION_1_2; } #endif void throwOutOfMemory(JNIEnv *env) { jclass clazz = (*env)->FindClass(env, "java/lang/OutOfMemoryError"); if (clazz != NULL) { (*env)->ThrowNew(env, clazz, ""); } } #ifndef JNI64 void **hawtjni_malloc_pointer_array(JNIEnv *env, jlongArray array) { int i, size; jlong *elems; void **rc; if( array==NULL ) { return NULL; } #ifdef JNI_VERSION_1_2 if (IS_JNI_1_2) { elems = (*env)->GetPrimitiveArrayCritical(env, array, NULL); } else #endif { elems = (*env)->GetLongArrayElements(env, array, NULL); } if( elems == NULL) { return NULL; } size = (*env)->GetArrayLength(env, array); rc=malloc(sizeof(void *)*(size+1)); if( rc!= NULL ) { for( i=0; i < size; i++ ) { rc[i]=(void *)(intptr_t)(elems[i]); } rc[size]=NULL; } #ifdef JNI_VERSION_1_2 if (IS_JNI_1_2) { (*env)->ReleasePrimitiveArrayCritical(env, array, elems, JNI_ABORT); } else #endif { (*env)->ReleaseLongArrayElements(env, array, elems, JNI_ABORT); } return rc; } void hawtjni_free_pointer_array(JNIEnv *env, jlongArray array, void **elems, jint mode) { // do we need to copy back the data?? if( mode != JNI_ABORT) { int i, size; jlong *tmp; size = (*env)->GetArrayLength(env, array); #ifdef JNI_VERSION_1_2 if (IS_JNI_1_2) { tmp = (*env)->GetPrimitiveArrayCritical(env, array, NULL); } else #endif { tmp = (*env)->GetLongArrayElements(env, array, NULL); } if( tmp != NULL) { for( i=0; i < size; i++ ) { tmp[i]=(intptr_t)elems[i]; } #ifdef JNI_VERSION_1_2 if (IS_JNI_1_2) { (*env)->ReleasePrimitiveArrayCritical(env, array, tmp, 0); } else #endif { (*env)->ReleaseLongArrayElements(env, array, tmp, 0); } } } /* mode != JNI_ABORTmode */ free(elems); } #endif /* JNI64 */ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/resources/hawtjni.h000077500000000000000000000133001475274123300262700ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /* == HEADER-SNIP-LOCATION == */ /** * hawtjni.h * * This file contains the global macro declarations for a hawtjni based * library. * */ #ifndef INC_HAWTJNI_H #define INC_HAWTJNI_H #define _MULTI_THREADED #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "jni.h" #include #ifdef __cplusplus extern "C" { #endif extern int IS_JNI_1_2; #ifndef JNI64 #if defined(_LP64) #define JNI64 #endif #endif /* 64 bit support */ #ifndef JNI64 /* int/long defines */ #define GetIntLongField GetIntField #define SetIntLongField SetIntField #define GetIntLongArrayElements GetIntArrayElements #define ReleaseIntLongArrayElements ReleaseIntArrayElements #define GetIntLongArrayRegion GetIntArrayRegion #define SetIntLongArrayRegion SetIntArrayRegion #define NewIntLongArray NewIntArray #define CallStaticIntLongMethod CallStaticIntMethod #define CallIntLongMethod CallIntMethod #define CallStaticIntLongMethodV CallStaticIntMethodV #define CallIntLongMethodV CallIntMethodV #define jintLongArray jintArray #define jintLong jint #define I_J "I" #define I_JArray "[I" /* float/double defines */ #define GetFloatDoubleField GetFloatField #define SetFloatDoubleField SetFloatField #define GetFloatDoubleArrayElements GetFloatArrayElements #define ReleaseFloatDoubleArrayElements ReleaseFloatArrayElements #define GetFloatDoubleArrayRegion GetFloatArrayRegion #define jfloatDoubleArray jfloatArray #define jfloatDouble jfloat #define F_D "F" #define F_DArray "[F" #else /* int/long defines */ #define GetIntLongField GetLongField #define SetIntLongField SetLongField #define GetIntLongArrayElements GetLongArrayElements #define ReleaseIntLongArrayElements ReleaseLongArrayElements #define GetIntLongArrayRegion GetLongArrayRegion #define SetIntLongArrayRegion SetLongArrayRegion #define NewIntLongArray NewLongArray #define CallStaticIntLongMethod CallStaticLongMethod #define CallIntLongMethod CallLongMethod #define CallStaticIntLongMethodV CallStaticLongMethodV #define CallIntLongMethodV CallLongMethodV #define jintLongArray jlongArray #define jintLong jlong #define I_J "J" #define I_JArray "[J" /* float/double defines */ #define GetFloatDoubleField GetDoubleField #define SetFloatDoubleField SetDoubleField #define GetFloatDoubleArrayElements GetDoubleArrayElements #define ReleaseFloatDoubleArrayElements ReleaseDoubleArrayElements #define GetFloatDoubleArrayRegion GetDoubleArrayRegion #define jfloatDoubleArray jdoubleArray #define jfloatDouble jdouble #define F_D "D" #define F_DArray "[D" #endif #ifdef __APPLE__ #define CALLING_CONVENTION #define LOAD_FUNCTION(var, name) \ static int initialized = 0; \ static void *var = NULL; \ if (!initialized) { \ CFBundleRef bundle = CFBundleGetBundleWithIdentifier(CFSTR(name##_LIB)); \ if (bundle) var = CFBundleGetFunctionPointerForName(bundle, CFSTR(#name)); \ initialized = 1; \ } #elif defined (_WIN32) || defined (_WIN32_WCE) #define CALLING_CONVENTION CALLBACK #define LOAD_FUNCTION(var, name) \ static int initialized = 0; \ static FARPROC var = NULL; \ if (!initialized) { \ HMODULE hm = LoadLibrary(name##_LIB); \ if (hm) var = GetProcAddress(hm, #name); \ initialized = 1; \ } #else #define CALLING_CONVENTION #define LOAD_FUNCTION(var, name) \ static int initialized = 0; \ static void *var = NULL; \ if (!initialized) { \ void* handle = dlopen(name##_LIB, RTLD_LAZY); \ if (handle) var = dlsym(handle, #name); \ initialized = 1; \ } #endif #ifdef JNI_VERSION_1_2 extern JavaVM *JVM; jint hawtjni_attach_thread(JNIEnv **env, const char *thread_name); jint hawtjni_detach_thread(); #endif void throwOutOfMemory(JNIEnv *env); #define CHECK_NULL_VOID(ptr) \ if ((ptr) == NULL) { \ throwOutOfMemory(env); \ return; \ } #define CHECK_NULL(ptr) \ if ((ptr) == NULL) { \ throwOutOfMemory(env); \ return 0; \ } #ifndef JNI64 void ** hawtjni_malloc_pointer_array(JNIEnv *env, jlongArray array); void hawtjni_free_pointer_array(JNIEnv *env, jlongArray array, void **elems, jint mode); #else #ifdef __cplusplus #define hawtjni_malloc_pointer_array(env, array) ( (void **)(intptr_t)env->GetLongArrayElements(array, NULL) ) #define hawtjni_free_pointer_array(env, array, elems, mode) ( env->ReleaseLongArrayElements(array, (jlong*)elems, mode) ) #else #define hawtjni_malloc_pointer_array(env, source) ( (void **)(intptr_t)(*env)->GetLongArrayElements(env, source, NULL) ) #define hawtjni_free_pointer_array(env, array, elems, mode) ( (*env)->ReleaseLongArrayElements(env, array, (jlong*)elems, mode) ) #endif #endif /* JNI64 */ #ifdef __GNUC__ #define hawtjni_w_barrier() __sync_synchronize() #elif defined(SOLARIS2) && SOLARIS2 >= 10 #include #define hawtjni_w_barrier() __machine_w_barrier() #elif defined(__APPLE__) #include #define hawtjni_w_barrier() OSMemoryBarrier() #elif defined(_WIN32) || defined(_WIN64) #include #define hawtjni_w_barrier() _mm_sfence(); _WriteBarrier() #else #pragma message ( "Don't know how to do a memory barrier on this platform" ) #define hawtjni_w_barrier() #endif void hawtjni_atomic_set(jlong *target, jlong value); jlong hawtjni_atomic_get(jlong *target); #ifdef __cplusplus } #endif #endif /* ifndef INC_HAWTJNI_H */ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/resources/windows/000077500000000000000000000000001475274123300261455ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-generator/src/main/resources/windows/stdint.h000066400000000000000000000170601475274123300276270ustar00rootroot00000000000000// ISO C9x compliant stdint.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2008 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 #pragma once #endif #include // For Visual Studio 6 in C++ mode and for many Visual Studio versions when // compiling for ARM we should wrap include with 'extern "C++" {}' // or compiler give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #ifdef __cplusplus extern "C" { #endif # include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 # define _W64 __w64 # else # define _W64 # endif #endif // 7.18.1 Integer types // 7.18.1.1 Exact-width integer types // Visual Studio 6 and Embedded Visual C++ 4 doesn't // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) #define INT8_MAX _I8_MAX #define INT16_MIN ((int16_t)_I16_MIN) #define INT16_MAX _I16_MAX #define INT32_MIN ((int32_t)_I32_MIN) #define INT32_MAX _I32_MAX #define INT64_MIN ((int64_t)_I64_MIN) #define INT64_MAX _I64_MAX #define UINT8_MAX _UI8_MAX #define UINT16_MAX _UI16_MAX #define UINT32_MAX _UI32_MAX #define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ # define INTPTR_MIN INT64_MIN # define INTPTR_MAX INT64_MAX # define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ # define INTPTR_MIN INT32_MIN # define INTPTR_MAX INT32_MAX # define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ # define PTRDIFF_MIN _I64_MIN # define PTRDIFF_MAX _I64_MAX #else // _WIN64 ][ # define PTRDIFF_MIN _I32_MIN # define PTRDIFF_MAX _I32_MAX #endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ # ifdef _WIN64 // [ # define SIZE_MAX _UI64_MAX # else // _WIN64 ][ # define SIZE_MAX _UI32_MAX # endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ # define WCHAR_MIN 0 #endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ # define WCHAR_MAX _UI16_MAX #endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants #define INTMAX_C INT64_C #define UINTMAX_C UINT64_C #endif // __STDC_CONSTANT_MACROS ] #endif // _MSC_STDINT_H_ ] jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/000077500000000000000000000000001475274123300213425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/pom.xml000066400000000000000000000133461475274123300226660ustar00rootroot00000000000000 4.0.0 org.fusesource.hawtjni hawtjni-project 1.18 hawtjni-maven-plugin maven-plugin HawtJNI Maven Plugin Use HawtJNI from a maven plugin ${mavenVersion} 3.6.3 ${project.version} org.fusesource.hawtjni hawtjni-generator ${project.version} org.apache.maven maven-plugin-api ${mavenVersion} org.apache.maven maven-project 2.0.11 org.codehaus.plexus plexus-utils 3.3.0 org.codehaus.plexus plexus-interpolation 1.26 org.apache.maven maven-artifact-manager 2.0.11 org.apache.maven maven-artifact 2.0.11 org.apache.maven maven-archiver 2.4 org.codehaus.plexus plexus-archiver 4.2.2 org.codehaus.plexus plexus-container-default org.codehaus.plexus plexus-component-api org.codehaus.plexus plexus-io 3.2.0 org.codehaus.plexus plexus-container-default org.codehaus.plexus plexus-component-api org.apache.maven.plugin-tools maven-plugin-annotations 3.6.0 provided org.apache.maven.plugins maven-plugin-plugin 3.6.0 org.apache.maven.plugins maven-plugin-plugin default-descriptor process-classes help-goal helpmojo org.apache.maven.plugins maven-plugin-plugin jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/000077500000000000000000000000001475274123300221315ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/000077500000000000000000000000001475274123300230555ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/000077500000000000000000000000001475274123300237765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/000077500000000000000000000000001475274123300245655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/000077500000000000000000000000001475274123300267505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/000077500000000000000000000000001475274123300304145ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/maven/000077500000000000000000000000001475274123300315225ustar00rootroot00000000000000BuildMojo.java000066400000000000000000000420451475274123300341770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/maven/** * Copyright (C) 2009-2011 FuseSource Corp. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.hawtjni.maven; import java.io.*; import java.net.URL; import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.model.Dependency; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.cli.CommandLineException; import org.fusesource.hawtjni.runtime.Library; /** * This goal builds the JNI module which was previously * generated with the generate goal. It adds the JNI module * to the test resource path so that unit tests can load * the freshly built JNI library. * * @author Hiram Chirino */ @Mojo(name = "build", defaultPhase = LifecyclePhase.GENERATE_TEST_RESOURCES) public class BuildMojo extends AbstractMojo { /** * The maven project. */ @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; /** * Remote repositories */ @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true) protected List remoteArtifactRepositories; /** * Local maven repository. */ @Parameter(defaultValue = "${localRepository}", readonly = true) protected ArtifactRepository localRepository; /** * Artifact factory, needed to download the package source file */ @Component protected ArtifactFactory artifactFactory; /** * Artifact resolver, needed to download the package source file */ @Component protected ArtifactResolver artifactResolver; /** */ @Component private ArchiverManager archiverManager; /** * The base name of the library, used to determine generated file names. */ @Parameter(defaultValue = "${project.artifactId}") private String name; /** * Where the unpacked build package is located. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/hawtjni/native-package") private File packageDirectory; /** * The output directory where the built JNI library will placed. This directory will be added * to as a test resource path so that unit tests can verify the built JNI library. * * The library will placed under the META-INF/native/${platform} directory that the HawtJNI * Library uses to find JNI libraries as classpath resources. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/hawtjni/lib") private File libDirectory; /** * The directory where the build will be produced. It creates a native-build and native-dist directory * under the specified directory. */ @Parameter(defaultValue = "${project.build.directory}") private File buildDirectory; /** * Should we skip executing the autogen.sh file. */ @Parameter(defaultValue = "${skip-autogen}") private boolean skipAutogen; /** * Should we force executing the autogen.sh file. */ @Parameter(defaultValue = "${force-autogen}") private boolean forceAutogen; /** * Extra arguments you want to pass to the autogen.sh command. */ @Parameter private List autogenArgs; /** * Should we skip executing the configure command. */ @Parameter(defaultValue = "${skip-configure}") private boolean skipConfigure; /** * Should we force executing the configure command. */ @Parameter(defaultValue = "${force-configure}") private boolean forceConfigure; /** * Should we display all the native build output? */ @Parameter(defaultValue = "${hawtjni-verbose}") private boolean verbose; /** * Extra arguments you want to pass to the configure command. */ @Parameter private List configureArgs; /** * The platform identifier of this build. If not specified, * it will be automatically detected. */ @Parameter private String platform; /** * The classifier of the package archive that will be created. */ @Parameter(defaultValue = "native-src") private String sourceClassifier; /** * If the source build could not be fully generated, perhaps the autotools * were not available on this platform, should we attempt to download * a previously deployed source package and build that? */ @Parameter(defaultValue = "true") private boolean downloadSourcePackage = true; /** * The dependency to download to get the native sources. */ @Parameter private Dependency nativeSrcDependency; /** * URL to where we can down the source package */ @Parameter(defaultValue = "${native-src-url}") private String nativeSrcUrl; /** * The build tool to use on Windows systems. Set * to 'msbuild', 'vcbuild', or 'detect' */ @Parameter(defaultValue = "detect") private String windowsBuildTool; /** * The name of the msbuild/vcbuild project to use. * Defaults to 'vs2010' for 'msbuild' * and 'vs2008' for 'vcbuild'. */ @Parameter private String windowsProjectName; private final CLI cli = new CLI(); public void execute() throws MojoExecutionException { cli.verbose = verbose; cli.log = getLog(); try { File buildDir = new File(buildDirectory, "native-build"); buildDir.mkdirs(); if ( CLI.IS_WINDOWS ) { vsBasedBuild(buildDir); } else { configureBasedBuild(buildDir); } getLog().info("Adding test resource root: "+libDirectory.getAbsolutePath()); Resource testResource = new Resource(); testResource.setDirectory(libDirectory.getAbsolutePath()); this.project.addTestResource(testResource); //(); } catch (Exception e) { throw new MojoExecutionException("build failed: "+e, e); } } private void vsBasedBuild(File buildDir) throws CommandLineException, MojoExecutionException, IOException { FileUtils.copyDirectoryStructureIfModified(packageDirectory, buildDir); Library library = new Library(name); String libPlatform = this.platform != null ? this.platform : Library.getPlatform(); String platform; String configuration="release"; if( "windows32".equals(libPlatform) ) { platform = "Win32"; } else if( "windows64".equals(libPlatform) ) { platform = "x64"; } else { throw new MojoExecutionException("Unsupported platform: "+libPlatform); } boolean useMSBuild = false; String tool = windowsBuildTool.toLowerCase().trim(); if( "detect".equals(tool) ) { String toolset = System.getenv("PlatformToolset"); if( "Windows7.1SDK".equals(toolset) ) { useMSBuild = true; } else { String vcinstalldir = System.getenv("VCINSTALLDIR"); if( vcinstalldir!=null ) { if( vcinstalldir.contains("Microsoft Visual Studio 10") || vcinstalldir.contains("Microsoft Visual Studio 11") || vcinstalldir.contains("Microsoft Visual Studio 12") || vcinstalldir.contains("Microsoft Visual Studio 14") || vcinstalldir.contains("Microsoft Visual Studio\\2017") ) { useMSBuild = true; } } } } else if( "msbuild".equals(tool) ) { useMSBuild = true; } else if( "vcbuild".equals(tool) ) { useMSBuild = false; } else { throw new MojoExecutionException("Invalid setting for windowsBuildTool: "+windowsBuildTool); } if( useMSBuild ) { // vcbuild was removed.. use the msbuild tool instead. int rc = cli.system(buildDir, new String[]{"msbuild", (windowsProjectName != null ? windowsProjectName : "vs2010") + ".vcxproj", "/property:Platform="+platform, "/property:Configuration="+configuration}); if( rc != 0 ) { throw new MojoExecutionException("vcbuild failed with exit code: "+rc); } } else { // try to use a vcbuild.. int rc = cli.system(buildDir, new String[]{"vcbuild", "/platform:"+platform, (windowsProjectName != null ? windowsProjectName : "vs2008") + ".vcproj", configuration}); if( rc != 0 ) { throw new MojoExecutionException("vcbuild failed with exit code: "+rc); } } File libFile=FileUtils.resolveFile(buildDir, "target/"+platform+"-"+configuration+"/lib/"+library.getLibraryFileName()); if( !libFile.exists() ) { throw new MojoExecutionException("vcbuild did not generate: "+libFile); } File target=FileUtils.resolveFile(libDirectory, library.getPlatformSpecificResourcePath(libPlatform)); FileUtils.copyFile(libFile, target); } private void configureBasedBuild(File buildDir) throws IOException, MojoExecutionException, CommandLineException { File configure = new File(packageDirectory, "configure"); if( configure.exists() ) { FileUtils.copyDirectoryStructureIfModified(packageDirectory, buildDir); } else if (downloadSourcePackage) { downloadNativeSourcePackage(buildDir); } else { if( !buildDir.exists() ) { throw new MojoExecutionException("The configure script is missing from the generated native source package and downloadSourcePackage is disabled: "+configure); } } configure = new File(buildDir, "configure"); File autogen = new File(buildDir, "autogen.sh"); File makefile = new File(buildDir, "Makefile"); File distDirectory = new File(buildDir, "target"); File distLibDirectory = new File(distDirectory, "lib"); distLibDirectory.mkdirs(); if( autogen.exists() && !skipAutogen ) { if( (!configure.exists() && !CLI.IS_WINDOWS) || forceAutogen ) { cli.setExecutable(autogen); int rc = cli.system(buildDir, new String[] {"./autogen.sh"}, autogenArgs); if( rc != 0 ) { throw new MojoExecutionException("./autogen.sh failed with exit code: "+rc); } } } if( configure.exists() && !skipConfigure ) { if( !makefile.exists() || forceConfigure ) { File autotools = new File(buildDir, "autotools"); File[] listFiles = autotools.listFiles(); if( listFiles!=null ) { for (File file : listFiles) { cli.setExecutable(file); } } cli.setExecutable(configure); int rc = cli.system(buildDir, new String[]{"./configure", "--disable-ccache", "--prefix="+distDirectory.getCanonicalPath(), "--libdir="+distDirectory.getCanonicalPath()+"/lib"}, configureArgs); if( rc != 0 ) { throw new MojoExecutionException("./configure failed with exit code: "+rc); } } } int rc = cli.system(buildDir, new String[]{"make", "install"}); if( rc != 0 ) { throw new MojoExecutionException("make based build failed with exit code: "+rc); } Library library = new Library(name); File libFile = new File(distLibDirectory, library.getLibraryFileName()); if( !libFile.exists() ) { throw new MojoExecutionException("Make based build did not generate: "+libFile); } if( platform == null ) { platform = library.getPlatform(); } File target=FileUtils.resolveFile(libDirectory, library.getPlatformSpecificResourcePath(platform)); FileUtils.copyFile(libFile, target); } public void downloadNativeSourcePackage(File buildDir) throws MojoExecutionException { File packageZipFile; if( nativeSrcUrl ==null || nativeSrcUrl.trim().length()==0 ) { Artifact artifact=null; if( nativeSrcDependency==null ) { artifact = artifactFactory.createArtifactWithClassifier(project.getGroupId(), project.getArtifactId(), project.getVersion(), "zip", sourceClassifier); } else { artifact = artifactFactory.createArtifactWithClassifier(nativeSrcDependency.getGroupId(), nativeSrcDependency.getArtifactId(), nativeSrcDependency.getVersion(), nativeSrcDependency.getType(), nativeSrcDependency.getClassifier()); } try { artifactResolver.resolveAlways(artifact, remoteArtifactRepositories, localRepository); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Error downloading.", e); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException("Requested download does not exist.", e); } packageZipFile = artifact.getFile(); if( packageZipFile.isDirectory() ) { // Yep. looks like we are running on mvn 3, seem like // mvn 3 does not actually download the artifact. it just points us // to our own build. throw new MojoExecutionException("Add a '-Dnative-src-url=file:...' to have maven download the native package"); } } else { try { packageZipFile = new File(buildDirectory, "native-build.zip"); URL url = new URL(nativeSrcUrl.trim()); InputStream is = url.openStream(); try { FileOutputStream os = new FileOutputStream(packageZipFile); try { IOUtil.copy(is, os); } finally { IOUtil.close(is); } } finally { IOUtil.close(is); } } catch (Exception e) { throw new MojoExecutionException("Error downloading: "+ nativeSrcUrl, e); } } try { File dest = new File(buildDirectory, "native-build-extracted"); getLog().info("Extracting "+packageZipFile+" to "+dest); UnArchiver unArchiver = archiverManager.getUnArchiver("zip"); unArchiver.setSourceFile(packageZipFile); unArchiver.extract("", dest); File source = findSourceRoot(dest); if( source==null ) { throw new MojoExecutionException("Extracted package did not look like it contained a native source build."); } FileUtils.copyDirectoryStructureIfModified(source, buildDir); } catch (MojoExecutionException e) { throw e; } catch (Throwable e) { throw new MojoExecutionException("Could not extract the native source package.", e); } } private File findSourceRoot(File dest) { if(dest.isDirectory()) { if( new File(dest, "configure").exists() ) { return dest; } else { for (File file : dest.listFiles()) { File root = findSourceRoot(file); if( root!=null ) { return root; } } return null; } } else { return null; } } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/maven/CLI.java000077500000000000000000000064431475274123300330060ustar00rootroot00000000000000package org.fusesource.hawtjni.maven; import java.io.File; import java.util.List; import java.util.regex.Pattern; import org.apache.maven.plugin.logging.Log; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.cli.StreamConsumer; import org.codehaus.plexus.util.cli.CommandLineUtils.StringStreamConsumer; public class CLI { public static final boolean IS_WINDOWS = isWindows(); static private boolean isWindows() { String name = System.getProperty("os.name").toLowerCase().trim(); return name.startsWith("win"); } public boolean verbose; public Log log; public void setExecutable(File path) { if( IS_WINDOWS ) { return; } try { // These are Java 1.6 Methods.. if( !path.canExecute() ) { path.setExecutable(true); } } catch (NoSuchMethodError e1) { // Do it the old fasioned way... try { system(path.getParentFile(), new String[] { "chmod", "a+x", path.getCanonicalPath() }); } catch (Throwable e2) { } } } public int system(File wd, String[] command) throws CommandLineException { return system(wd, command, null); } public int system(File wd, String[] command, List args) throws CommandLineException { Commandline cli = new Commandline(); cli.setWorkingDirectory(wd); for (String c : command) { cli.createArg().setValue(c); } if( args!=null ) { for (String arg : args) { cli.createArg().setValue(arg); } } log.info("executing: "+cli); StreamConsumer consumer = new StreamConsumer() { public void consumeLine(String line) { log.info(line); } }; if( !verbose ) { consumer = new StringStreamConsumer(); } int rc = CommandLineUtils.executeCommandLine(cli, null, consumer, consumer); if( rc!=0 ) { if( !verbose ) { // We only display output if the command fails.. String output = ((StringStreamConsumer)consumer).getOutput(); if( output.length()>0 ) { String nl = System.getProperty( "line.separator"); String[] lines = output.split(Pattern.quote(nl)); for (String line : lines) { log.info(line); } } } log.info("rc: "+rc); } else { if( !verbose ) { String output = ((StringStreamConsumer)consumer).getOutput(); if( output.length()>0 ) { String nl = System.getProperty( "line.separator"); String[] lines = output.split(Pattern.quote(nl)); for (String line : lines) { log.debug(line); } } } log.debug("rc: "+rc); } return rc; } } GenerateMojo.java000066400000000000000000000372071475274123300346760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/maven/** * Copyright (C) 2009-2011 FuseSource Corp. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.hawtjni.maven; import java.io.File; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.interpolation.InterpolatorFilterReader; import org.codehaus.plexus.interpolation.MapBasedValueSource; import org.codehaus.plexus.interpolation.StringSearchInterpolator; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.FileUtils.FilterWrapper; import org.fusesource.hawtjni.generator.HawtJNI; import org.fusesource.hawtjni.generator.ProgressMonitor; /** * This goal generates the native source code and a * autoconf/msbuild based build system needed to * build a JNI library for any HawtJNI annotated * classes in your maven project. * * @author Hiram Chirino */ @Mojo(name = "generate", defaultPhase = LifecyclePhase.PROCESS_CLASSES) public class GenerateMojo extends AbstractMojo { /** * The maven project. */ @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; /** * The directory where the native source files are located. */ @Parameter private File nativeSourceDirectory; /** * The directory where the generated native source files are located. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/hawtjni/native-src") private File generatedNativeSourceDirectory; /** * The base name of the library, used to determine generated file names. */ @Parameter(defaultValue = "${project.artifactId}") private String name; /** * The copyright header template that will be added to the generated source files. * Use the '%END_YEAR%' token to have it replaced with the current year. */ @Parameter(defaultValue = "") private String copyright; /** * Restrict looking for JNI classes to the specified package. */ @Parameter private List packages = new ArrayList(); /** * The directory where the java classes files are located. */ @Parameter(defaultValue = "${project.build.outputDirectory}") private File classesDirectory; /** * The directory where the generated build package is located.. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/hawtjni/native-package") private File packageDirectory; /** * The list of additional files to be included in the package will be * placed. */ @Parameter(defaultValue = "${basedir}/src/main/native-package") private File customPackageDirectory; /** * The text encoding of the files. */ @Parameter(defaultValue = "UTF-8") private String encoding; /** * Should we skip executing the autogen.sh file. */ @Parameter(defaultValue = "${skip-autogen}") private boolean skipAutogen; /** * Should we force executing the autogen.sh file. */ @Parameter(defaultValue = "${force-autogen}") private boolean forceAutogen; /** * Should we display all the native build output? */ @Parameter(defaultValue = "${hawtjni-verbose}") private boolean verbose; /** * Extra arguments you want to pass to the autogen.sh command. */ @Parameter private List autogenArgs; /** * Set this value to false to disable the callback support in HawtJNI. * Disabling callback support can substantially reduce the size * of the generated native library. */ @Parameter(defaultValue = "true") private boolean callbacks; /** * The build tool to use on Windows systems. Set * to 'msbuild', 'vcbuild', or 'detect' or 'none' */ @Parameter(defaultValue = "detect") private String windowsBuildTool; /** * The name of the msbuild/vcbuild project to use. * Defaults to 'vs2010' for 'msbuild' * and 'vs2008' for 'vcbuild'. */ @Parameter private String windowsProjectName; /** * Set this value to true to include the import of a custom properties file in your vcxproj (not applicable * to vs2008). This greatly simplifies the configurability of your project. */ @Parameter(defaultValue = "false") private boolean windowsCustomProps; /** * The tools version used in the header of your vcxproj (not applicable to vs2008). */ @Parameter(defaultValue = "4.0") private String windowsToolsVersion; /** * The target platform version used in your vcxproj (not applicable to vs2008). * Not supplied by default. */ @Parameter private String windowsTargetPlatformVersion; /** * The platform toolset version used in your vcxproj (not applicable to vs2008). * Not supplied by default. */ @Parameter private String windowsPlatformToolset; private File targetSrcDir; private CLI cli = new CLI(); public void execute() throws MojoExecutionException { cli.verbose = verbose; cli.log = getLog(); if (nativeSourceDirectory == null) { generateNativeSourceFiles(); } else { copyNativeSourceFiles(); } generateBuildSystem(); } private void copyNativeSourceFiles() throws MojoExecutionException { try { FileUtils.copyDirectory(nativeSourceDirectory, generatedNativeSourceDirectory); } catch (Exception e) { throw new MojoExecutionException("Copy of Native source failed: "+e, e); } } private void generateNativeSourceFiles() throws MojoExecutionException { HawtJNI generator = new HawtJNI(); generator.setClasspaths(getClasspath()); generator.setName(name); generator.setCopyright(copyright); generator.setNativeOutput(generatedNativeSourceDirectory); generator.setPackages(packages); generator.setCallbacks(callbacks); generator.setProgress(new ProgressMonitor() { public void step() { } public void setTotal(int total) { } public void setMessage(String message) { getLog().info(message); } }); try { generator.generate(); } catch (Exception e) { throw new MojoExecutionException("Native source code generation failed: "+e, e); } } private void generateBuildSystem() throws MojoExecutionException { try { packageDirectory.mkdirs(); new File(packageDirectory, "m4").mkdirs(); targetSrcDir = new File(packageDirectory, "src"); targetSrcDir.mkdirs(); if( customPackageDirectory!=null && customPackageDirectory.isDirectory() ) { FileUtils.copyDirectoryStructureIfModified(customPackageDirectory, packageDirectory); } if( generatedNativeSourceDirectory!=null && generatedNativeSourceDirectory.isDirectory() ) { FileUtils.copyDirectoryStructureIfModified(generatedNativeSourceDirectory, targetSrcDir); } copyTemplateResource("readme.md", false); copyTemplateResource("configure.ac", true); copyTemplateResource("Makefile.am", true); copyTemplateResource("m4/custom.m4", false); copyTemplateResource("m4/jni.m4", false); copyTemplateResource("m4/osx-universal.m4", false); // To support windows based builds.. String tool = windowsBuildTool.toLowerCase().trim(); if( "detect".equals(tool) ) { copyTemplateResource("vs2008.vcproj", (windowsProjectName != null ? windowsProjectName : "vs2008") + ".vcproj", true); copyTemplateResource("vs2010.vcxproj", (windowsProjectName != null ? windowsProjectName : "vs2010") + ".vcxproj", true); if (windowsCustomProps) { copyTemplateResource("vs2010.custom.props", (windowsProjectName != null ? windowsProjectName : "vs2010") + ".custom.props", true); } } else if( "msbuild".equals(tool) ) { copyTemplateResource("vs2010.vcxproj", (windowsProjectName != null ? windowsProjectName : "vs2010") + ".vcxproj", true); if (windowsCustomProps) { copyTemplateResource("vs2010.custom.props", (windowsProjectName != null ? windowsProjectName : "vs2010") + ".custom.props", true); } } else if( "vcbuild".equals(tool) ) { copyTemplateResource("vs2008.vcproj", (windowsProjectName != null ? windowsProjectName : "vs2008") + ".vcproj", true); } else if( "none".equals(tool) ) { } else { throw new MojoExecutionException("Invalid setting for windowsBuildTool: "+windowsBuildTool); } File autogen = new File(packageDirectory, "autogen.sh"); File configure = new File(packageDirectory, "configure"); if( !autogen.exists() ) { copyTemplateResource("autogen.sh", false); cli.setExecutable(autogen); } if( !skipAutogen ) { if( (!configure.exists() && !CLI.IS_WINDOWS) || forceAutogen ) { try { cli.system(packageDirectory, new String[] {"./autogen.sh"}, autogenArgs); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { throw new MojoExecutionException("Native build system generation failed: "+e, e); } } @SuppressWarnings("unchecked") private ArrayList getClasspath() throws MojoExecutionException { ArrayList artifacts = new ArrayList(); try { artifacts.add(classesDirectory.getCanonicalPath()); for (Artifact artifact : (Set) project.getArtifacts()) { File file = artifact.getFile(); getLog().debug("Including: " + file); artifacts.add(file.getCanonicalPath()); } } catch (IOException e) { throw new MojoExecutionException("Could not determine project classath.", e); } return artifacts; } private void copyTemplateResource(String file, boolean filter) throws MojoExecutionException { copyTemplateResource(file, file, filter); } private void copyTemplateResource(String file, String output, boolean filter) throws MojoExecutionException { try { File target = FileUtils.resolveFile(packageDirectory, output); if( target.isFile() && target.canRead() ) { return; } URL source = getClass().getClassLoader().getResource("project-template/" + file); File tmp = FileUtils.createTempFile("tmp", "txt", new File(project.getBuild().getDirectory())); try { FileUtils.copyURLToFile(source, tmp); FileUtils.copyFile(tmp, target, encoding, filters(filter), true); } finally { tmp.delete(); } } catch (IOException e) { throw new MojoExecutionException("Could not extract template resource: "+file, e); } } @SuppressWarnings("unchecked") private FilterWrapper[] filters(boolean filter) throws IOException { if( !filter ) { return new FilterWrapper[0]; } final String startExp = "@"; final String endExp = "@"; final String escapeString = "\\"; final Map values = new HashMap(); values.put("PROJECT_NAME", name); values.put("PROJECT_NAME_UNDER_SCORE", name.replaceAll("\\W", "_")); values.put("VERSION", project.getVersion()); List cpp_files = new ArrayList(); cpp_files.addAll(FileUtils.getFileNames(targetSrcDir, "**/*.cpp", null, false)); cpp_files.addAll(FileUtils.getFileNames(targetSrcDir, "**/*.cxx", null, false)); List files = new ArrayList(); files.addAll(cpp_files); files.addAll(FileUtils.getFileNames(targetSrcDir, "**/*.c", null, false)); files.addAll(FileUtils.getFileNames(targetSrcDir, "**/*.m", null, false)); String sources = ""; String xml_sources = ""; String vs10_sources = ""; boolean first = true; for (String f : files) { if( !first ) { sources += "\\\n"; } else { values.put("FIRST_SOURCE_FILE", "src/"+f.replace('\\', '/')); first=false; } sources += " src/"+f; xml_sources+=" \n"; vs10_sources+=" \n"; //VS adds trailing space and eases compares } if( cpp_files.isEmpty() ) { values.put("AC_PROG_CHECKS", "AC_PROG_CC"); } else { values.put("AC_PROG_CHECKS", "AC_PROG_CXX"); } values.put("PROJECT_SOURCES", sources); values.put("PROJECT_XML_SOURCES", xml_sources); values.put("PROJECT_VS10_SOURCES", vs10_sources); values.put("CUSTOM_PROPS", windowsCustomProps ? "" : ""); values.put("TOOLS_VERSION", windowsToolsVersion); values.put("TARGET_PLATFORM_VERSION", windowsTargetPlatformVersion != null ? "" + windowsTargetPlatformVersion + "" : ""); values.put("PLATFORM_TOOLSET", windowsPlatformToolset != null ? "" + windowsPlatformToolset + "" : ""); FileUtils.FilterWrapper wrapper = new FileUtils.FilterWrapper() { public Reader getReader(Reader reader) { StringSearchInterpolator propertiesInterpolator = new StringSearchInterpolator(startExp, endExp); propertiesInterpolator.addValueSource(new MapBasedValueSource(values)); propertiesInterpolator.setEscapeString(escapeString); InterpolatorFilterReader interpolatorFilterReader = new InterpolatorFilterReader(reader, propertiesInterpolator, startExp, endExp); interpolatorFilterReader.setInterpolateWithPrefixPattern(false); return interpolatorFilterReader; } }; return new FilterWrapper[] { wrapper }; } } PackageJarMojo.java000066400000000000000000000210171475274123300351240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/maven/** * Copyright (C) 2009-2011 FuseSource Corp. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.hawtjni.maven; import java.io.File; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.codehaus.plexus.archiver.jar.JarArchiver; import org.codehaus.plexus.archiver.jar.Manifest; import org.codehaus.plexus.archiver.jar.Manifest.Attribute; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.fusesource.hawtjni.runtime.Library; /** * This goal allows allows you to package the JNI library created by build goal * in a JAR which the HawtJNI runtime can unpack when the library needs to be * loaded. * * This platform specific jar is attached with a classifier which matches the * current platform. * * @author Hiram Chirino */ @Mojo(name = "package-jar", defaultPhase = LifecyclePhase.PREPARE_PACKAGE) public class PackageJarMojo extends AbstractMojo { /** * The maven project. */ @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; /** * The base name of the library, used to determine generated file names. */ @Parameter(defaultValue = "${project.artifactId}") private String name; /** */ @Component private ArchiverManager archiverManager; /** */ @Component private MavenProjectHelper projectHelper; /** * The output directory where the built JNI library will placed. This * directory will be added to as a test resource path so that unit tests can * verify the built JNI library. * * The library will placed under the META-INF/native/${platform} directory * that the HawtJNI Library uses to find JNI libraries as classpath * resources. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/hawtjni/lib") private File libDirectory; /** * The platform identifier of this build. If not specified, * it will be automatically detected. * * @parameter */ @Parameter private String platform; /** * Should a classifier of the native jar be set * to match the platform? */ @Parameter(defaultValue = "true") private boolean classified; /** * The osgi platforms that the library match for. Example value: * osname=MacOS;processor=x86-64 */ @Parameter private List osgiPlatforms; public void execute() throws MojoExecutionException { try { Library library = new Library(name); if (platform == null) { platform = Library.getPlatform(); } String classifier = null; if( classified ) { classifier = platform; String packageName = project.getArtifactId() + "-" + project.getVersion() + "-" + platform; JarArchiver archiver = (JarArchiver) archiverManager.getArchiver("jar"); File packageFile = new File(new File(project.getBuild().getDirectory()), packageName + ".jar"); archiver.setDestFile(packageFile); archiver.setIncludeEmptyDirs(true); archiver.addDirectory(libDirectory); Manifest manifest = new Manifest(); manifest.addConfiguredAttribute(new Attribute("Bundle-SymbolicName", project.getArtifactId() + "-" + platform)); manifest.addConfiguredAttribute(new Attribute("Bundle-Name", name + " for " + platform)); manifest.addConfiguredAttribute(new Attribute("Bundle-NativeCode", getNativeCodeValue(library))); manifest.addConfiguredAttribute(new Attribute("Bundle-Version", project.getVersion())); manifest.addConfiguredAttribute(new Attribute("Bundle-ManifestVersion", "2")); manifest.addConfiguredAttribute(new Attribute("Bundle-Description", project.getDescription())); archiver.addConfiguredManifest(manifest); archiver.createArchive(); projectHelper.attachArtifact(project, "jar", classifier, packageFile); } else { projectHelper.addResource(project, libDirectory.getCanonicalPath(), null, null); } } catch (Exception e) { throw new MojoExecutionException("packaging failed: " + e, e); } } public String getNativeCodeValue(Library library) { if (osgiPlatforms == null || osgiPlatforms.isEmpty() ) { return library.getPlatformSpecificResourcePath(platform) + ";" +"osname=" + getOsgiOSName() + ";processor=" + getOsgiProcessor()+ ",*"; } boolean first=true; String rc = ""; for (String s : osgiPlatforms) { if( !first ) { rc += ","; } first = false; if( "*".equals(s) ) { rc += s; } else { rc += library.getPlatformSpecificResourcePath(platform) + ";"+s; } } return rc; } public String getOsgiOSName() { String name = System.getProperty("os.name"); String trimmed = name.toLowerCase().trim(); if (trimmed.startsWith("win")) { return "Win32"; } else if (trimmed.startsWith("linux")) { return "Linux"; } else if (trimmed.startsWith("macos") || trimmed.startsWith("mac os")) { return "MacOS"; } else if (trimmed.startsWith("aix")) { return "AIX"; } else if (trimmed.startsWith("hpux")) { return "HPUX"; } else if (trimmed.startsWith("irix")) { return "IRIX"; } else if (trimmed.startsWith("netware")) { return "Netware"; } else if (trimmed.startsWith("openbsd")) { return "OpenBSD"; } else if (trimmed.startsWith("netbsd")) { return "NetBSD"; } else if (trimmed.startsWith("os2") || trimmed.startsWith("os/2")) { return "OS2"; } else if (trimmed.startsWith("qnx") || trimmed.startsWith("procnto")) { return "QNX"; } else if (trimmed.startsWith("solaris")) { return "Solaris"; } else if (trimmed.startsWith("sunos")) { return "SunOS"; } else if (trimmed.startsWith("vxworks")) { return "VxWorks"; } return name; } public String getOsgiProcessor() { String name = System.getProperty("os.arch"); String trimmed = name.toLowerCase().trim(); if (trimmed.startsWith("x86-64") || trimmed.startsWith("amd64") || trimmed.startsWith("em64") || trimmed.startsWith("x86_64")) { return "x86-64"; } else if (trimmed.startsWith("x86") || trimmed.startsWith("pentium") || trimmed.startsWith("i386") || trimmed.startsWith("i486") || trimmed.startsWith("i586") || trimmed.startsWith("i686")) { return "x86"; } else if (trimmed.startsWith("68k")) { return "68k"; } else if (trimmed.startsWith("arm")) { return "ARM"; } else if (trimmed.startsWith("alpha")) { return "Alpha"; } else if (trimmed.startsWith("ignite") || trimmed.startsWith("psc1k")) { return "Ignite"; } else if (trimmed.startsWith("mips")) { return "Mips"; } else if (trimmed.startsWith("parisc")) { return "PArisc"; } else if (trimmed.startsWith("powerpc") || trimmed.startsWith("power") || trimmed.startsWith("ppc")) { return "PowerPC"; } else if (trimmed.startsWith("sparc")) { return "Sparc"; } return name; } } PackageSourceMojo.java000066400000000000000000000077321475274123300356600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/java/org/fusesource/hawtjni/maven/** * Copyright (C) 2009-2011 FuseSource Corp. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.hawtjni.maven; import java.io.File; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.manager.ArchiverManager; /** * This goal creates a source zip file of the native build * module and attaches it to the build so that it can get * deployed. * * @author Hiram Chirino */ @Mojo(name = "package-source", defaultPhase = LifecyclePhase.PACKAGE) public class PackageSourceMojo extends AbstractMojo { /** * The maven project. */ @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; /** */ @Component private ArchiverManager archiverManager; /** */ @Component private MavenProjectHelper projectHelper; /** * The directory where the generated native files are located.. */ @Parameter(defaultValue = "${project.build.directory}/generated-sources/hawtjni/native-package") private File packageDirectory; /** * The classifier of the package archive that will be created. */ @Parameter(defaultValue = "native-src") private String sourceClassifier; /** * Should we skip executing the autogen.sh file. */ @Parameter(defaultValue = "${skip-autogen}") private boolean skipAutogen; public void execute() throws MojoExecutionException { try { String packageName = project.getArtifactId()+"-"+project.getVersion()+"-"+sourceClassifier; File packageFile = new File(new File(project.getBuild().getDirectory()), packageName+".zip"); // Verify the the configure script got generated before packaging. File configure = new File(packageDirectory, "configure"); if( !skipAutogen && !configure.exists() ) { // Looks like this platform could not generate the // configure script. So don't install deploy // partially created source package. getLog().info(""); getLog().warn("Will NOT package the native sources to: "+packageFile); getLog().info(" Native source build directory did not contain a 'configure' script."); getLog().info(" To ignore this warning and package it up anyways, configure the plugin with: true"); getLog().info(""); return; } Archiver archiver = archiverManager.getArchiver( "zip" ); archiver.setDestFile( packageFile); archiver.setIncludeEmptyDirs(true); archiver.addDirectory(packageDirectory, packageName+"/"); archiver.createArchive(); projectHelper.attachArtifact( project, "zip", sourceClassifier, packageFile ); } catch (Exception e) { throw new MojoExecutionException("packageing failed: "+e, e); } } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/000077500000000000000000000000001475274123300250675ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/000077500000000000000000000000001475274123300303465ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/Makefile.am000066400000000000000000000022331475274123300324020ustar00rootroot00000000000000# --------------------------------------------------------------------------- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --------------------------------------------------------------------------- ACLOCAL_AMFLAGS = -I m4 AM_CXXFLAGS = -std=gnu++11 lib_LTLIBRARIES = lib@PROJECT_NAME@.la # lib@PROJECT_NAME_UNDER_SCORE@_la_CFLAGS = #lib@PROJECT_NAME_UNDER_SCORE@_la_LDFLAGS = lib@PROJECT_NAME_UNDER_SCORE@_la_SOURCES =@PROJECT_SOURCES@ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/autogen.sh000077500000000000000000000030061475274123300323460ustar00rootroot00000000000000#!/bin/sh # --------------------------------------------------------------------------- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --------------------------------------------------------------------------- auto_clean() { AUTO_FILES=" configure config.log config.status autom4te.cache autotools aclocal.m4 libtool m4/libtool.m4 m4/ltoptions.m4 m4/ltsugar.m4 m4/ltversion.m4 m4/lt~obsolete.m4 Makefile.in Makefile src/Makefile src/Makefile.in src/config.in src/config.h src/config.h.in* src/stamp-h1 " for f in "$AUTO_FILES" ; do rm -Rf $f done } auto_reconf() { autoreconf --force --install -I m4 } case "$1" in clean) echo "auto clean..." auto_clean ;; *) echo "auto reconf..." auto_clean auto_reconf ;; esac jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/configure.ac000066400000000000000000000043531475274123300326410ustar00rootroot00000000000000# --------------------------------------------------------------------------- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --------------------------------------------------------------------------- ## -------------------------------- ## Initialization macros. ## -------------------------------- AC_PREREQ([2.61]) AC_INIT([@PROJECT_NAME@], [@VERSION@]) AC_CONFIG_AUX_DIR([autotools]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_SRCDIR([@FIRST_SOURCE_FILE@]) AC_CONFIG_HEADERS([src/config.h]) AC_CANONICAL_HOST AC_CANONICAL_SYSTEM ## ----------------------------------------------- ## Application Checks ## ----------------------------------------------- @AC_PROG_CHECKS@ AC_PROG_INSTALL # Make AM_PROG_AR work before automake 1.12 m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) AC_PROG_LIBTOOL([disable-static]) ## ----------------------------------------------- ## API Checks ## ----------------------------------------------- WITH_JNI_JDK CUSTOM_M4_SETUP WITH_OSX_UNIVERSAL CFLAGS="$CFLAGS $JNI_EXTRA_CFLAGS" AC_SUBST(CFLAGS) CXXFLAGS="$CXXFLAGS $JNI_EXTRA_CFLAGS" AC_SUBST(CXXFLAGS) LDFLAGS="$LDFLAGS $JNI_EXTRA_LDFLAGS -release @VERSION@" AC_SUBST(LDFLAGS) ## ----------------------------------------------------- ## Generate the files ## ----------------------------------------------------- AM_INIT_AUTOMAKE([subdir-objects no-dependencies -Wall -Werror foreign]) AC_CONFIG_FILES([Makefile]) AC_OUTPUT echo " ($PACKAGE_NAME) version $PACKAGE_VERSION Prefix.........: $prefix C Compiler.....: $CC $CFLAGS Linker.........: $LD $LDFLAGS $LIBS " jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/m4/000077500000000000000000000000001475274123300306665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/m4/custom.m4000066400000000000000000000022221475274123300324400ustar00rootroot00000000000000dnl --------------------------------------------------------------------------- dnl Copyright (C) 2009-2011 FuseSource Corp. dnl http://fusesource.com dnl dnl Licensed under the Apache License, Version 2.0 (the "License"); dnl you may not use this file except in compliance with the License. dnl You may obtain a copy of the License at dnl dnl http://www.apache.org/licenses/LICENSE-2.0 dnl dnl Unless required by applicable law or agreed to in writing, software dnl distributed under the License is distributed on an "AS IS" BASIS, dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. dnl See the License for the specific language governing permissions and dnl limitations under the License. dnl --------------------------------------------------------------------------- AC_DEFUN([CUSTOM_M4_SETUP], [ # # This is just a stub. If you wish to customize your configure.ac # just copy this file to src/main/native-package/m4/custom.m4 # then replace add your configure.ac statements here. # AC_CHECK_HEADER([pthread.h],[AC_DEFINE([HAVE_PTHREAD_H], [1], [Define to 1 if you have the header file.])]) ])jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/m4/jni.m4000066400000000000000000000132721475274123300317150ustar00rootroot00000000000000dnl --------------------------------------------------------------------------- dnl Copyright (C) 2009-2011 FuseSource Corp. dnl http://fusesource.com dnl dnl Licensed under the Apache License, Version 2.0 (the "License"); dnl you may not use this file except in compliance with the License. dnl You may obtain a copy of the License at dnl dnl http://www.apache.org/licenses/LICENSE-2.0 dnl dnl Unless required by applicable law or agreed to in writing, software dnl distributed under the License is distributed on an "AS IS" BASIS, dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. dnl See the License for the specific language governing permissions and dnl limitations under the License. dnl --------------------------------------------------------------------------- dnl --------------------------------------------------------------------------- dnl SYNOPSIS: dnl dnl WITH_JNI_JDK() dnl dnl Adds the --with-jni-jdk=PATH option. If not provided, it searches dnl for the JDK in the default OS locations. dnl dnl This macro calls: dnl AC_SUBST(JNI_JDK) dnl AC_SUBST(JNI_EXTRA_CFLAGS) dnl AC_SUBST(JNI_EXTRA_LDFLAGS) dnl dnl AUTHOR: Hiram Chrino dnl --------------------------------------------------------------------------- AC_DEFUN([WITH_JNI_JDK], [ AC_PREREQ([2.61]) AC_ARG_WITH(jni-jdk, [AS_HELP_STRING([--with-jni-jdk=PATH], [Location of the Java Development Kit. Defaults to your JAVA_HOME setting and falls back to where it is typically installed on your OS])], [ if test "$withval" = "no" || test "$withval" = "yes"; then AC_MSG_ERROR([--with-jni-jdk: PATH to JDK not supplied]) fi CHECK_JNI_JDK([$withval], [], [AC_MSG_ERROR([JDK not found. Invalid --with-jni-jdk PATH])]) ],[ if test -n "$JAVA_HOME" ; then AC_MSG_NOTICE([JAVA_HOME was set, checking to see if it's a JDK we can use...]) CHECK_JNI_JDK([$JAVA_HOME], [], []) fi __JNI_GUESS=`which javac` AS_IF(test -z "$JNI_JDK" && test -n "$__JNI_GUESS", [ AC_MSG_NOTICE([javac was on your path, checking to see if it's part of a JDK we can use...]) # transitively resolve the symbolic links to javac while file -h "$__JNI_GUESS" 2>/dev/null | grep " symbolic link to " >/dev/null; do __JNI_LINK=$( file -h $__JNI_GUESS | sed 's/.*symbolic link to //' | sed "s/'$//" | sed 's/^`//' ) __JNI_GUESS=$(cd $(dirname $__JNI_GUESS); cd $(dirname $__JNI_LINK); echo "$(pwd)/$(basename $__JNI_LINK)") done # move 2 dirs up to the home dir... __JNI_GUESS=$(dirname $(dirname $__JNI_GUESS)) CHECK_JNI_JDK([$__JNI_GUESS], [], [],[]) ],[]) AS_IF(test -z "$JNI_JDK", [ case "$host_os" in darwin*) __JNI_GUESS="/System/Library/Frameworks/JavaVM.framework";; freebsd*) __JNI_GUESS=$(env JAVAVM_DRYRUN=yes /usr/local/bin/java | grep '^JAVA_HOME' | cut -c11-);; *) __JNI_GUESS="/usr";; esac AC_MSG_NOTICE([Taking a guess as to where your OS installs the JDK by default...]) CHECK_JNI_JDK([$__JNI_GUESS], [], [AC_MSG_ERROR([JDK not found. Please use the --with-jni-jdk option])]) ],[]) ]) ]) dnl --------------------------------------------------------------------------- dnl dnl JNI_CHECK_JDK_HOME(PATH, [ACTION-SUCCESS], [ACTION-FAILURE]) dnl dnl Tests to see if the given path is a valid JDK home location with dnl with a JNI headers and library that can be compiled against. dnl dnl This macro calls: dnl dnl AC_SUBST(JNI_JDK) dnl AC_SUBST(JNI_EXTRA_CFLAGS) dnl AC_SUBST(JNI_EXTRA_LDFLAGS) dnl dnl AUTHOR: Hiram Chrino dnl --------------------------------------------------------------------------- AC_DEFUN([CHECK_JNI_JDK],[ AC_PREREQ([2.61]) __JNI_JDK_HOME="$1" AC_MSG_CHECKING(if '$__JNI_JDK_HOME' is a JDK) __JNI_INCLUDE="$__JNI_JDK_HOME/include" # OSX had to be a little different. case "$host_os" in darwin*) AS_IF(test -r "$__JNI_JDK_HOME/Headers/jni.h",[ __JNI_INCLUDE="$__JNI_JDK_HOME/Headers"; ]) esac AS_IF(test -r "$__JNI_INCLUDE/jni.h",[ # Also include the os specific include dirs in the JNI_CFLAGS __JNI_CFLAGS="-I$__JNI_INCLUDE" case "$host_os" in darwin*) __JNI_INCLUDE_EXTRAS="darwin";; freebsd*) __JNI_INCLUDE_EXTRAS="freebsd";; linux*) __JNI_INCLUDE_EXTRAS="linux genunix";; openbsd*) __JNI_INCLUDE_EXTRAS="openbsd";; osf*) __JNI_INCLUDE_EXTRAS="alpha";; solaris*) __JNI_INCLUDE_EXTRAS="solaris";; mingw*) __JNI_INCLUDE_EXTRAS="win32";; cygwin*) __JNI_INCLUDE_EXTRAS="win32";; *) __JNI_INCLUDE_EXTRAS="genunix";; esac for f in $__JNI_INCLUDE_EXTRAS ; do if test -d "$__JNI_INCLUDE/$f"; then __JNI_CFLAGS="$__JNI_CFLAGS -I$__JNI_INCLUDE/$f" fi done saved_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $__JNI_CFLAGS" JNI_VERSION="1_2" AC_LANG_PUSH(C) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([[@%:@include ]],[[ #ifndef JNI_VERSION_$JNI_VERSION # error JNI version $JNI_VERSION is not supported. #endif ]]) ],[ JNI_JDK=$"$__JNI_JDK_HOME" JNI_EXTRA_CFLAGS="$__JNI_CFLAGS" AC_SUBST(JNI_JDK) AC_SUBST(JNI_EXTRA_CFLAGS) case $host_os in darwin*) JNI_EXTRA_LDFLAGS="-shrext .jnilib -dynamiclib" ;; esac AC_SUBST(JNI_EXTRA_LDFLAGS) AC_MSG_RESULT([yes]) $2 ],[ AC_MSG_RESULT([no]) $3 ]) AC_LANG_POP() CPPFLAGS="$saved_CPPFLAGS" ],[ AC_MSG_RESULT([no]) $3 ]) ]) osx-universal.m4000066400000000000000000000076341475274123300337020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/m4dnl --------------------------------------------------------------------------- dnl Copyright (C) 2009-2011 FuseSource Corp. dnl http://fusesource.com dnl dnl Licensed under the Apache License, Version 2.0 (the "License"); dnl you may not use this file except in compliance with the License. dnl You may obtain a copy of the License at dnl dnl http://www.apache.org/licenses/LICENSE-2.0 dnl dnl Unless required by applicable law or agreed to in writing, software dnl distributed under the License is distributed on an "AS IS" BASIS, dnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. dnl See the License for the specific language governing permissions and dnl limitations under the License. dnl --------------------------------------------------------------------------- dnl --------------------------------------------------------------------------- dnl SYNOPSIS: dnl dnl WITH_OSX_UNIVERSAL() dnl dnl Allows creating universal binaries on the dnl dnl Adds the --with-universal=ARCH option. This will will dnl set -isysroot option to the location of the MacOSX${OSX_VERSION}.sdk. dnl if OSX_VERSION is not defined, it will set it to the latest version dnl of the SDK installed on your system. dnl dnl You must use the no-dependencies option when automake is initialized. dnl for example: AM_INIT_AUTOMAKE([no-dependencies]) dnl dnl This macro calls: dnl AC_SUBST(CFLAGS) dnl AC_SUBST(CXXFLAGS) dnl AC_SUBST(LDFLAGS) dnl AC_SUBST(OSX_VERSION) dnl dnl AUTHOR: Hiram Chrino dnl --------------------------------------------------------------------------- AC_DEFUN([WITH_OSX_UNIVERSAL], [ AC_PREREQ([2.61]) case "$host_os" in darwin*) AC_MSG_CHECKING(OS X SDK version) AC_ARG_WITH([osxsdk], [AS_HELP_STRING([--with-osxsdk@<:@=VERSION@:>@], [OS X SDK version to build against. Example: --with-osxsdk=10.6])], [ OSX_UNIVERSAL="$withval" ],[ OSX_SDKS_DIR="" OSX_VERSION="" for v in 10.0 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 10.13 10.14 10.15; do for location in "/Developer/SDKs" "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs" ; do if test -z "${OSX_VERSION}" && test -d "${location}/MacOSX${v}.sdk" ; then OSX_SDKS_DIR="${location}" OSX_VERSION="${v}" fi done done ]) AC_MSG_RESULT([$OSX_VERSION]) AC_SUBST(OSX_SDKS_DIR) AC_SUBST(OSX_VERSION) AC_MSG_CHECKING(whether to build universal binaries) AC_ARG_WITH([universal], [AS_HELP_STRING([--with-universal@<:@=ARCH@:>@], [Build a universal binary. Set to a space separated architecture list. Pick from: i386, x86_64, ppc, and/or ppc64. @<:@default="i386 x86_64"@:>@])], [ AS_IF(test "$withval" = "no", [ OSX_UNIVERSAL="" AC_MSG_RESULT([no]) ], test "$withval" = "yes", [ OSX_UNIVERSAL="i386 x86_64" AC_MSG_RESULT([yes, archs: $OSX_UNIVERSAL]) ],[ OSX_UNIVERSAL="$withval" AC_MSG_RESULT([yes, archs: $OSX_UNIVERSAL]) ]) ],[ OSX_UNIVERSAL="" AC_MSG_RESULT([no]) ]) AS_IF(test -n "$OSX_UNIVERSAL", [ for i in $OSX_UNIVERSAL ; do CFLAGS="-arch $i $CFLAGS" CXXFLAGS="-arch $i $CXXFLAGS" LDFLAGS="-arch $i $LDFLAGS" done for f in $__JNI_INCLUDE_EXTRAS ; do if test -d "$__JNI_INCLUDE/$f"; then __JNI_CFLAGS="$__JNI_CFLAGS -I$__JNI_INCLUDE/$f" fi done CFLAGS="-isysroot ${OSX_SDKS_DIR}/MacOSX${OSX_VERSION}.sdk $CFLAGS" CXXFLAGS="-isysroot ${OSX_SDKS_DIR}/MacOSX${OSX_VERSION}.sdk $CXXFLAGS" LDFLAGS="-syslibroot,${OSX_SDKS_DIR}/MacOSX${OSX_VERSION}.sdk $LDFLAGS" AC_SUBST(CFLAGS) AC_SUBST(CXXFLAGS) AC_SUBST(LDFLAGS) ]) ;; esac ]) jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/readme.md000066400000000000000000000030111475274123300321200ustar00rootroot00000000000000Building on Unix/Linux/OS X --------------------------- The configure script will customize the way the software is built and installed into your system along with detecting the available libraries that have been installed. To use the default configuration just run: ./configure For more help on how to customize the build configuration, run: ./configure --help Once the configure script has run successfully, you are ready to build. Run: make This will build all of the core ActiveMQ CPP source code. To build and install the code into the system directories, run: make install You will have to become the superuser in order to be able to install the JNI libraries. ### OS X Lion requirements Install brew. It will depends on XCode being installed along with the command line tools. Then use brew to install autoconf, automake, and libtool. brew install autoconf automake libtool Building on Windows ------------------- Download and install the free [Microsoft Windows SDK][1]. The SDK includes all the headers, libraries, and build tools needed to compile the JNI library. Set the `JAVA_HOME` environment variable to the location where your JDK is installed. Use the installed command window and change to the directory that this file is located in and then run: For recent SDK Versions: msbuild vs2010.vcxproj (or ) For legacy SDK Versions: vcbuild vs2008.vcproj The dll files will be located under the target directory. [1]: https://developer.microsoft.com/en-us/windows/downloadsjtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/vs2008.vcproj000077500000000000000000000164161475274123300325500ustar00rootroot00000000000000 @PROJECT_XML_SOURCES@ vs2010.custom.props000066400000000000000000000012531475274123300336210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-maven-plugin/src/main/resources/project-template/vs2010.vcxproj000077500000000000000000000242171475274123300327270ustar00rootroot00000000000000 debug Win32 debug x64 release Win32 release x64 @PROJECT_NAME@ @PROJECT_NAME@ @TARGET_PLATFORM_VERSION@ DynamicLibrary Unicode @PLATFORM_TOOLSET@ DynamicLibrary Unicode @PLATFORM_TOOLSET@ true DynamicLibrary @PLATFORM_TOOLSET@ Unicode DynamicLibrary Unicode @PLATFORM_TOOLSET@ true <_ProjectFileVersion>10.0.30319.1 $(ProjectDir)/target/$(Platform)-$(Configuration)/lib\ $(ProjectDir)/target/$(Platform)-$(Configuration)/obj\ false $(ProjectDir)/target/$(Platform)-$(Configuration)/lib\ $(ProjectDir)/target/$(Platform)-$(Configuration)/obj\ false $(ProjectDir)/target/$(Platform)-$(Configuration)/lib\ $(ProjectDir)/target/$(Platform)-$(Configuration)/obj\ true $(ProjectDir)/target/$(Platform)-$(Configuration)/lib\ $(ProjectDir)/target/$(Platform)-$(Configuration)/obj\ true @CUSTOM_PROPS@ $(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;$(ProjectDir)\src\windows;%(AdditionalIncludeDirectories) MaxSpeed true Speed WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) MultiThreadedDLL true false Level3 ProgramDatabase StdCall true Windows true true MachineX86 $(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;$(ProjectDir)\src\windows;%(AdditionalIncludeDirectories) MaxSpeed true Speed WIN64;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) MultiThreadedDLL true false Level3 ProgramDatabase StdCall true Windows true true MachineX64 $(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;$(ProjectDir)\src\windows;%(AdditionalIncludeDirectories) Disabled Speed WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL false Level3 EditAndContinue StdCall true Windows MachineX86 $(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;$(ProjectDir)\src\windows;%(AdditionalIncludeDirectories) Disabled Speed WIN64;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL false Level3 EditAndContinue StdCall true Windows MachineX64 @PROJECT_VS10_SOURCES@ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/000077500000000000000000000000001475274123300204235ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/pom.xml000066400000000000000000000042731475274123300217460ustar00rootroot00000000000000 4.0.0 org.fusesource.hawtjni hawtjni-project 1.18 hawtjni-runtime HawtJNI Runtime The API that projects using HawtJNI should build against. org.apache.maven.plugins maven-jar-plugin org.fusesource.hawtjni.runtime org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/000077500000000000000000000000001475274123300212125ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/000077500000000000000000000000001475274123300221365ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/000077500000000000000000000000001475274123300230575ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/000077500000000000000000000000001475274123300236465ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/000077500000000000000000000000001475274123300260315ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/000077500000000000000000000000001475274123300274755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/000077500000000000000000000000001475274123300311605ustar00rootroot00000000000000ArgFlag.java000066400000000000000000000052341475274123300332530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * * @author Hiram Chirino */ public enum ArgFlag { /** * Indicate that a native method parameter is an out only variable. * This only makes sense if the parameter is a structure or an array * of primitives. It is an optimization to avoid copying the java * memory to C memory on the way in. */ NO_IN, /** * Indicate that a native method parameter is an in only variable. * This only makes sense if the parameter is a structure or an array * of primitives. It is an optimization to avoid copying the C memory * from java memory on the way out. */ NO_OUT, /** * Indicate that GetPrimitiveArrayCritical() should be used instead * of Get<PrimitiveType>ArrayElements() when transferring array of * primitives from/to C. This is an optimization to avoid copying * memory and must be used carefully. It is ok to be used in * MoveMemory() and memmove() natives. */ CRITICAL, /** * Indicate that the associated C local variable for a native method * parameter should be initialized with zeros. */ INIT, /** * Indicate that the parameter is a pointer. */ POINTER_ARG, /** * Indicate that a structure parameter should be passed by value * instead of by reference. This dereferences the parameter by * prepending *. The parameter must not be NULL. */ BY_VALUE, /** * Indicate that GetStringChars()should be used instead of * GetStringUTFChars() to get the characters of a java.lang.String * passed as a parameter to native methods. */ UNICODE, /** * Indicate that the parameter of a native method is the sentinel * (last parameter of a variable argument C function). The generated * code is always the literal NULL. Some compilers expect the sentinel * to be the literal NULL and output a warning if otherwise. */ SENTINEL, /** * Indicate that the native parameter is a C# managed object. */ CS_OBJECT, }Callback.java000077500000000000000000000224011475274123300334420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * Instances of this class represent entry points into Java which can be invoked * from operating system level callback routines. *

* IMPORTANT: A callback is only valid when invoked on the thread which created * it. The results are undefined (and typically bad) when a callback is passed * out to the operating system (or other code) in such a way that the callback * is called from a different thread. */ public class Callback { Object object; String method, signature; int argCount; long /* int */ address, errorResult; boolean isStatic, isArrayBased; static final String PTR_SIGNATURE = "J"; /* C.PTR_SIZEOF == 4 ? "I" : "J"; */ static final String SIGNATURE_0 = getSignature(0); static final String SIGNATURE_1 = getSignature(1); static final String SIGNATURE_2 = getSignature(2); static final String SIGNATURE_3 = getSignature(3); static final String SIGNATURE_4 = getSignature(4); static final String SIGNATURE_N = "([" + PTR_SIGNATURE + ")" + PTR_SIGNATURE; /** * Constructs a new instance of this class given an object to send the * message to, a string naming the method to invoke and an argument count. * Note that, if the object is an instance of Class it is * assumed that the method is a static method on that class. * * @param object * the object to send the message to * @param method * the name of the method to invoke * @param argCount * the number of arguments that the method takes */ public Callback(Object object, String method, int argCount) { this(object, method, argCount, false); } /** * Constructs a new instance of this class given an object to send the * message to, a string naming the method to invoke, an argument count and a * flag indicating whether or not the arguments will be passed in an array. * Note that, if the object is an instance of Class it is * assumed that the method is a static method on that class. * * @param object * the object to send the message to * @param method * the name of the method to invoke * @param argCount * the number of arguments that the method takes * @param isArrayBased * true if the arguments should be passed in an * array and false otherwise */ public Callback(Object object, String method, int argCount, boolean isArrayBased) { this(object, method, argCount, isArrayBased, 0); } /** * Constructs a new instance of this class given an object to send the * message to, a string naming the method to invoke, an argument count, a * flag indicating whether or not the arguments will be passed in an array * and a value to return when an exception happens. Note that, if the object * is an instance of Class it is assumed that the method is a * static method on that class. * * @param object * the object to send the message to * @param method * the name of the method to invoke * @param argCount * the number of arguments that the method takes * @param isArrayBased * true if the arguments should be passed in an * array and false otherwise * @param errorResult * the return value if the java code throws an exception */ public Callback(Object object, String method, int argCount, boolean isArrayBased, long /* int */errorResult) { /* Set the callback fields */ this.object = object; this.method = method; this.argCount = argCount; this.isStatic = object instanceof Class; this.isArrayBased = isArrayBased; this.errorResult = errorResult; /* Inline the common cases */ if (isArrayBased) { signature = SIGNATURE_N; } else { switch (argCount) { case 0: signature = SIGNATURE_0; break; //$NON-NLS-1$ case 1: signature = SIGNATURE_1; break; //$NON-NLS-1$ case 2: signature = SIGNATURE_2; break; //$NON-NLS-1$ case 3: signature = SIGNATURE_3; break; //$NON-NLS-1$ case 4: signature = SIGNATURE_4; break; //$NON-NLS-1$ default: signature = getSignature(argCount); } } /* Bind the address */ address = bind(this, object, method, signature, argCount, isStatic, isArrayBased, errorResult); } /** * Allocates the native level resources associated with the callback. This * method is only invoked from within the constructor for the argument. * * @param callback * the callback to bind * @param object * the callback's object * @param method * the callback's method * @param signature * the callback's method signature * @param argCount * the callback's method argument count * @param isStatic * whether the callback's method is static * @param isArrayBased * whether the callback's method is array based * @param errorResult * the callback's error result */ static native synchronized long /* int */ bind(Callback callback, Object object, String method, String signature, int argCount, boolean isStatic, boolean isArrayBased, long /* int */errorResult); /** * Releases the native level resources associated with the callback, and * removes all references between the callback and other objects. This helps * to prevent (bad) application code from accidentally holding onto * extraneous garbage. */ public void dispose() { if (object == null) return; unbind(this); object = method = signature = null; address = 0; } /** * Returns the address of a block of machine code which will invoke the * callback represented by the receiver. * * @return the callback address */ public long /* int */getAddress() { return address; } /** * Returns the SWT platform name. * * @return the platform name of the currently running SWT */ public static native String getPlatform(); /** * Returns the number of times the system has been recursively entered * through a callback. *

* Note: This should not be called by application code. *

* * @return the entry count * * @since 2.1 */ public static native int getEntryCount(); static String getSignature(int argCount) { String signature = "("; //$NON-NLS-1$ for (int i = 0; i < argCount; i++) signature += PTR_SIGNATURE; signature += ")" + PTR_SIGNATURE; //$NON-NLS-1$ return signature; } /** * Indicates whether or not callbacks which are triggered at the native * level should cause the messages described by the matching * Callback objects to be invoked. This method is used to * safely shut down SWT when it is run within environments which can * generate spurious events. *

* Note: This should not be called by application code. *

* * @param enable * true if callbacks should be invoked */ public static final native synchronized void setEnabled(boolean enable); /** * Returns whether or not callbacks which are triggered at the native level * should cause the messages described by the matching Callback * objects to be invoked. This method is used to safely shut down SWT when * it is run within environments which can generate spurious events. *

* Note: This should not be called by application code. *

* * @return true if callbacks should not be invoked */ public static final native synchronized boolean getEnabled(); /** * Immediately wipes out all native level state associated with all * callbacks. *

* WARNING: This operation is extremely dangerous, and * should never be performed by application code. *

*/ public static final native synchronized void reset(); /** * Releases the native level resources associated with the callback. * * @see #dispose */ static final native synchronized void unbind(Callback callback); } ClassFlag.java000066400000000000000000000025601475274123300336060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * * @author Hiram Chirino */ public enum ClassFlag { /** * Indicate that the item should not be generated. For example, * custom natives are coded by hand. */ CLASS_SKIP, /** * Indicate that the platform source is in C++ */ CPP, /** * Indicate that this class will define a structure */ STRUCT, /** * Indicate that structure name is a typedef (It should * not be prefixed with 'struct' to reference it.) */ TYPEDEF, /** * Indicate that the struct should get zeroed out before * setting any of it's fields. Comes in handy when * you don't map all the struct fields to java fields but * still want the fields that are not mapped initialized. */ ZERO_OUT, }FieldFlag.java000066400000000000000000000032011475274123300335550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * * @author Hiram Chirino */ public enum FieldFlag { /** * Indicate that the item should not be generated. For example, * custom natives are coded by hand. */ FIELD_SKIP, /** * Indicate that the field represents a constant or global * variable. It is expected that the java field will be declared * static. */ CONSTANT, /** * Indicate that the field is a pointer. */ POINTER_FIELD, /** * Indicate that the field is a shared pointer. */ SHARED_PTR, /** * Indicate that the getter method used is not part of * the structure. Useful for using wrappers to access * certain structure fields. * * Only useful when the getter is declared explicitly. */ GETTER_NONMEMBER, /** * Indicate that the setter method used is not part of * the structure. Useful for using wrappers to access * certain structure fields. * * Only useful when the setter is declared explicitly. */ SETTER_NONMEMBER, } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/JNIEnv.java000066400000000000000000000007151475274123300331170ustar00rootroot00000000000000/** * Copyright (C) 2010, FuseSource Corp. All rights reserved. */ package org.fusesource.hawtjni.runtime; /** *

* This is a marker class. Methods that take this as an argument * will receive that actual native 'JNIEnv *' value. Since this * class cannot be instantiated, Java callers must pass null * for the value. *

* * @author Hiram Chirino */ public class JNIEnv { private JNIEnv() {} } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/JniArg.java000066400000000000000000000015731475274123300332030ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * */ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; @Documented @Target({PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface JniArg { ArgFlag[] flags() default {}; String cast() default ""; } JniClass.java000066400000000000000000000016401475274123300334530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * */ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; @Documented @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface JniClass { ClassFlag[] flags() default {}; String conditional() default ""; String name() default ""; } JniField.java000066400000000000000000000020751475274123300334340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; /** * * @author Hiram Chirino */ @Documented @Target({FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface JniField { String cast() default ""; String accessor() default ""; String getter() default ""; String setter() default ""; String conditional() default ""; FieldFlag[] flags() default {}; } JniMethod.java000066400000000000000000000022131475274123300336230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; /** * * @author Hiram Chirino */ @Documented @Target({METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface JniMethod { String cast() default ""; // Pointer pointer() default Pointer.DETERMINE_FROM_CAST; String accessor() default ""; MethodFlag[] flags() default {}; String copy() default ""; String conditional() default ""; JniArg[] callbackArgs() default {}; } Library.java000077500000000000000000000512501475274123300333560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2000, 2009 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; /** * Used to find and load a JNI library, eventually after having extracted it. * * It will search for the library in order at the following locations: *
    *
  1. in the custom library path: If the "library.${name}.path" System property is set to a directory, * subdirectories are searched: *
      *
    1. "${platform}/${arch}" *
    2. "${platform}" *
    3. "${os}" *
    * for 2 namings of the library: *
      *
    1. as "${name}-${version}" library name if the version can be determined. *
    2. as "${name}" library name *
    *
  2. system library path: This is where the JVM looks for JNI libraries by default. *
      *
    1. as "${name}${bit-model}-${version}" library name if the version can be determined. *
    2. as "${name}-${version}" library name if the version can be determined. *
    3. as "${name}" library name *
    *
  3. classpath path: If the JNI library can be found on the classpath, it will get extracted * and then loaded. This way you can embed your JNI libraries into your packaged JAR files. * They are looked up as resources in this order: *
      *
    1. "META-INF/native/${platform}/${arch}/${library[-version]}": Store your library here if you want to embed * more than one platform JNI library on different processor archs in the jar. *
    2. "META-INF/native/${platform}/${library[-version]}": Store your library here if you want to embed more * than one platform JNI library in the jar. *
    3. "META-INF/native/${os}/${library[-version]}": Store your library here if you want to embed more * than one platform JNI library in the jar but don't want to take bit model into account. *
    4. "META-INF/native/${library[-version]}": Store your library here if your JAR is only going to embedding one * platform library. *
    * The file extraction is attempted until it succeeds in the following directories. *
      *
    1. The directory pointed to by the "library.${name}.path" System property (if set) *
    2. a temporary directory (uses the "java.io.tmpdir" System property) *
    *
* * where: *
    *
  • "${name}" is the name of library *
  • "${version}" is the value of "library.${name}.version" System property if set. * Otherwise it is set to the ImplementationVersion property of the JAR's Manifest
  • *
  • "${os}" is your operating system, for example "osx", "linux", or "windows"
  • *
  • "${bit-model}" is "64" if the JVM process is a 64 bit process, otherwise it's "32" if the * JVM is a 32 bit process
  • *
  • "${arch}" is the architecture for the processor, for example "amd64" or "sparcv9"
  • *
  • "${platform}" is "${os}${bit-model}", for example "linux32" or "osx64"
  • *
  • "${library[-version]}": is the normal jni library name for the platform (eventually with -${version}) suffix. * For example "${name}.dll" on * windows, "lib${name}.jnilib" on OS X, and "lib${name}.so" on linux
  • *
* * @author Hiram Chirino * @see System#mapLibraryName(String) */ public class Library { public static final String STRATEGY_PROPERTY = "hawtjni.strategy"; public static final String STRATEGY_SHA1 = "sha1"; public static final String STRATEGY_TEMP = "temp"; static final String SLASH = System.getProperty("file.separator"); static final String STRATEGY = System.getProperty(STRATEGY_PROPERTY, "windows".equals(getOperatingSystem()) ? STRATEGY_SHA1 : STRATEGY_TEMP); final private String name; final private String version; final private ClassLoader classLoader; private boolean loaded; private String nativeLibraryPath; private URL nativeLibrarySourceUrl; public Library(String name) { this(name, null, null); } public Library(String name, Class clazz) { this(name, version(clazz), clazz.getClassLoader()); } public Library(String name, String version) { this(name, version, null); } public Library(String name, String version, ClassLoader classLoader) { if( name == null ) { throw new IllegalArgumentException("name cannot be null"); } this.name = name; this.version = version; this.classLoader= classLoader; } private static String version(Class clazz) { try { return clazz.getPackage().getImplementationVersion(); } catch (Throwable e) { } return null; } /** * Get the path to the native library loaded. * @return the path (should not be null once the library is loaded) * @since 1.16 */ public String getNativeLibraryPath() { return nativeLibraryPath; } /** * Get the URL to the native library source that has been extracted (if it was extracted). * @return the url to the source (in classpath) * @since 1.16 */ public URL getNativeLibrarySourceUrl() { return nativeLibrarySourceUrl; } public static String getOperatingSystem() { String name = System.getProperty("os.name").toLowerCase().trim(); if( name.startsWith("linux") ) { return "linux"; } if( name.startsWith("mac os x") ) { return "osx"; } if( name.startsWith("win") ) { return "windows"; } return name.replaceAll("\\W+", "_"); } public static String getPlatform() { return getOperatingSystem()+getBitModel(); } public static int getBitModel() { String prop = System.getProperty("sun.arch.data.model"); if (prop == null) { prop = System.getProperty("com.ibm.vm.bitmode"); } if( prop!=null ) { return Integer.parseInt(prop); } // GraalVM support, see https://github.com/fusesource/jansi/issues/162 String arch = System.getProperty("os.arch"); if (arch.endsWith("64") && "Substrate VM".equals(System.getProperty("java.vm.name"))) { return 64; } return -1; // we don't know.. } /** * Load the native library. */ synchronized public void load() { if( loaded ) { return; } doLoad(); loaded = true; } private void doLoad() { /* Perhaps a custom version is specified */ String version = System.getProperty("library."+name+".version"); if (version == null) { version = this.version; } ArrayList errors = new ArrayList(); String[] specificDirs = getSpecificSearchDirs(); String libFilename = map(name); String versionlibFilename = (version == null) ? null : map(name + "-" + version); /* Try loading library from a custom library path */ String customPath = System.getProperty("library."+name+".path"); if (customPath != null) { for ( String dir: specificDirs ) { if( version!=null && load(errors, file(customPath, dir, versionlibFilename)) ) return; if( load(errors, file(customPath, dir, libFilename)) ) return; } } /* Try loading library from java library path */ if( version!=null && loadLibrary(errors, name + getBitModel() + "-" + version) ) return; if( version!=null && loadLibrary(errors, name + "-" + version) ) return; if( loadLibrary(errors, name) ) return; /* Try extracting the library from the jar */ if( classLoader!=null ) { String targetLibName = version != null ? versionlibFilename : libFilename; for ( String dir: specificDirs ) { if( version!=null && extractAndLoad(errors, customPath, dir, versionlibFilename, targetLibName) ) return; if( extractAndLoad(errors, customPath, dir, libFilename, targetLibName) ) return; } } /* Failed to find the library */ UnsatisfiedLinkError e = new UnsatisfiedLinkError("Could not load library. Reasons: " + errors.toString()); try { Method method = Throwable.class.getMethod("addSuppressed", Throwable.class); for (Throwable t : errors) { method.invoke(e, t); } } catch (Throwable ignore) { } throw e; } @Deprecated final public String getArchSpecifcResourcePath() { return getArchSpecificResourcePath(); } final public String getArchSpecificResourcePath() { return "META-INF/native/"+ getPlatform() + "/" + System.getProperty("os.arch") + "/" +map(name); } @Deprecated final public String getOperatingSystemSpecifcResourcePath() { return getOperatingSystemSpecificResourcePath(); } final public String getOperatingSystemSpecificResourcePath() { return getPlatformSpecificResourcePath(getOperatingSystem()); } @Deprecated final public String getPlatformSpecifcResourcePath() { return getPlatformSpecificResourcePath(); } final public String getPlatformSpecificResourcePath() { return getPlatformSpecificResourcePath(getPlatform()); } @Deprecated final public String getPlatformSpecifcResourcePath(String platform) { return getPlatformSpecificResourcePath(platform); } final public String getPlatformSpecificResourcePath(String platform) { return "META-INF/native/"+platform+"/"+map(name); } @Deprecated final public String getResorucePath() { return getResourcePath(); } final public String getResourcePath() { return "META-INF/native/"+map(name); } final public String getLibraryFileName() { return map(name); } /** * Search directories for library:
    *
  • ${platform}/${arch} to enable platform JNI library for different processor archs
  • *
  • ${platform} to enable platform JNI library
  • *
  • ${os} to enable OS JNI library
  • *
  • no directory
  • *
* @return the list * @since 1.15 */ final public String[] getSpecificSearchDirs() { return new String[] { getPlatform() + "/" + System.getProperty("os.arch"), getPlatform(), getOperatingSystem(), "." }; } private boolean extractAndLoad(ArrayList errors, String customPath, String dir, String libName, String targetLibName) { String resourcePath = "META-INF/native/" + ( dir == null ? "" : (dir + '/')) + libName; URL resource = classLoader.getResource(resourcePath); if( resource !=null ) { int idx = targetLibName.lastIndexOf('.'); String prefix = targetLibName.substring(0, idx)+"-"; String suffix = targetLibName.substring(idx); // Use the user provided path, // then fallback to the java temp directory, // and last, use the user home folder for (File path : Arrays.asList( customPath != null ? file(customPath) : null, file(System.getProperty("java.io.tmpdir")), file(System.getProperty("user.home"), ".hawtjni", name))) { if( path!=null ) { // Try to extract it to the custom path... File target; if (STRATEGY_SHA1.equals(STRATEGY)) { target = extractSha1(errors, resource, prefix, suffix, path); } else { target = extractTemp(errors, resource, prefix, suffix, path); } if( target!=null ) { if( load(errors, target) ) { nativeLibrarySourceUrl = resource; return true; } } } } } return false; } private File file(String ...paths) { File rc = null ; for (String path : paths) { if( rc == null ) { rc = new File(path); } else if( path != null ) { rc = new File(rc, path); } } return rc; } private String map(String libName) { /* * libraries in the Macintosh use the extension .jnilib but the some * VMs map to .dylib. */ libName = System.mapLibraryName(libName); String ext = ".dylib"; if (libName.endsWith(ext)) { libName = libName.substring(0, libName.length() - ext.length()) + ".jnilib"; } return libName; } private File extractSha1(ArrayList errors, URL source, String prefix, String suffix, File directory) { File target = null; directory = directory.getAbsoluteFile(); if (!directory.exists()) { if (!directory.mkdirs()) { errors.add(new IOException("Unable to create directory: " + directory)); return null; } } try { String sha1 = computeSha1(source.openStream()); String sha1f = ""; target = new File(directory, prefix + sha1 + suffix); if (target.isFile() && target.canRead()) { sha1f = computeSha1(new FileInputStream(target)); } if (sha1f.equals(sha1)) { return target; } FileOutputStream os = null; InputStream is = null; try { is = source.openStream(); if (is != null) { byte[] buffer = new byte[4096]; os = new FileOutputStream(target); int read; while ((read = is.read(buffer)) != -1) { os.write(buffer, 0, read); } chmod755(target); } return target; } finally { close(os); close(is); } } catch (Throwable e) { IOException io; if (target != null) { target.delete(); io = new IOException("Unable to extract library from " + source + " to " + target); } else { io = new IOException("Unable to create temporary file in " + directory); } io.initCause(e); errors.add(io); } return null; } private String computeSha1(InputStream is) throws NoSuchAlgorithmException, IOException { String sha1; try { MessageDigest mDigest = MessageDigest.getInstance("SHA1"); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) != -1) { mDigest.update(buffer, 0, read); } byte[] result = mDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : result) { sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } sha1 = sb.toString(); } finally { close(is); } return sha1; } private File extractTemp(ArrayList errors, URL source, String prefix, String suffix, File directory) { File target = null; directory = directory.getAbsoluteFile(); if (!directory.exists()) { if (!directory.mkdirs()) { errors.add(new IOException("Unable to create directory: " + directory)); return null; } } try { FileOutputStream os = null; InputStream is = null; try { target = File.createTempFile(prefix, suffix, directory); is = source.openStream(); if (is != null) { byte[] buffer = new byte[4096]; os = new FileOutputStream(target); int read; while ((read = is.read(buffer)) != -1) { os.write(buffer, 0, read); } chmod755(target); } target.deleteOnExit(); return target; } finally { close(os); close(is); } } catch (Throwable e) { IOException io; if (target != null) { target.delete(); io = new IOException("Unable to extract library from " + source + " to " + target); } else { io = new IOException("Unable to create temporary file in " + directory); } io.initCause(e); errors.add(io); } return null; } static private void close(Closeable file) { if (file != null) { try { file.close(); } catch (Exception ignore) { } } } private void chmod755(File file) { if (getPlatform().startsWith("windows")) return; // Use Files.setPosixFilePermissions if we are running Java 7+ to avoid forking the JVM for executing chmod try { ClassLoader classLoader = getClass().getClassLoader(); // Check if the PosixFilePermissions exists in the JVM, if not this will throw a ClassNotFoundException Class posixFilePermissionsClass = classLoader.loadClass("java.nio.file.attribute.PosixFilePermissions"); // Set permissionSet = PosixFilePermissions.fromString("rwxr-xr-x") Method fromStringMethod = posixFilePermissionsClass.getMethod("fromString", String.class); Object permissionSet = fromStringMethod.invoke(null, "rwxr-xr-x"); // Path path = file.toPath() Object path = file.getClass().getMethod("toPath").invoke(file); // Files.setPosixFilePermissions(path, permissionSet) Class pathClass = classLoader.loadClass("java.nio.file.Path"); Class filesClass = classLoader.loadClass("java.nio.file.Files"); Method setPosixFilePermissionsMethod = filesClass.getMethod("setPosixFilePermissions", pathClass, Set.class); setPosixFilePermissionsMethod.invoke(null, path, permissionSet); } catch (Throwable ignored) { // Fallback to starting a new process try { Runtime.getRuntime().exec(new String[]{"chmod", "755", file.getCanonicalPath()}).waitFor(); } catch (Throwable e) { } } } private boolean load(ArrayList errors, File lib) { try { System.load(lib.getPath()); nativeLibraryPath = lib.getPath(); return true; } catch (UnsatisfiedLinkError e) { LinkageError le = new LinkageError("Unable to load library from " + lib); le.initCause(e); errors.add(le); } return false; } private boolean loadLibrary(ArrayList errors, String lib) { try { System.loadLibrary(lib); nativeLibraryPath = "java.library.path,sun.boot.library.pathlib:" + lib; return true; } catch (UnsatisfiedLinkError e) { LinkageError le = new LinkageError("Unable to load library " + lib); le.initCause(e); errors.add(le); } return false; } } MethodFlag.java000066400000000000000000000063311475274123300337610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2000, 2008 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * * @author Hiram Chirino */ public enum MethodFlag { /** * Indicate that the item should not be generated. For example, * custom natives are coded by hand. */ METHOD_SKIP, /** * Indicate that a native method should be looked up dynamically. It * is useful when having a dependence on a given library is not * desirable. The library name is specified in the *_custom.h file. */ DYNAMIC, /** * Indicate that the native method represents a constant or global * variable instead of a function. This omits () from the generated * code. */ CONSTANT_GETTER, /** * Indicate that the C function should be casted to a prototype * generated from the parameters of the native method. Useful for * variable argument C functions. */ CAST, /** * Indicate that the native is part of the Java Native Interface. For * example: NewGlobalRef(). */ JNI, /** * Indicate that the native method represents a structure global * variable and the address of it should be returned to Java. This is * done by prepending &. */ ADDRESS, /** * Indicate that the native method is calling a C++ object's method. */ CPP_METHOD, /** * Indicate that the native method is a C++ constructor that allocates * an object on the heap. */ CPP_NEW, /** * Indicate that the native method is a C++ destructor that * deallocates an object from the heap. */ CPP_DELETE, /** * Indicate that the native method is a C# constructor that allocates * an object on the managed (i.e. garbage collected) heap. */ CS_NEW, /** * Indicate that the native method's return value is a * C# managed object. */ CS_OBJECT, /** * Indicate that the native method represents a setter for a field in * an object or structure */ SETTER, /** * Indicate that the native method represents a getter for a field in * an object or structure. */ GETTER, /** * Indicate that the native method takes 2 arguments, a collection and * an item, and the += operator is used to add the item to the * collection. */ ADDER, /** * Indicate that the return value is a pointer. */ POINTER_RETURN, /** * Indicate that this method will be the constant initializer for * the class. When called, it will set all the static constant fields * to the values defined in your platform. */ CONSTANT_INITIALIZER, }NativeStats.java000077500000000000000000000166111475274123300342210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * Copyright (c) 2004, 2006 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map.Entry; /** * Instructions on how to use the NativeStats tool with a standalone SWT * example: *
    *
  1. Compile the native libraries defining the NATIVE_STATS flag.
  2. *
  3. Add the following code around the sections of * interest to dump the native calls done in that section. *
     *      StatsInterface si = MyFooStatsInterface.INSTANCE;
     *      NativeStats stats = new NativeStats(si); 
     *      ... // your code
     *      stats.diff().dump(System.out);
     *      
    *
  4. *
  5. Or add the following code at a given point to dump a snapshot of * the native calls done until that point. *
     *      stats.snapshot().dump(System.out);
     *      
    *
  6. *
* * @author Hiram Chirino */ public class NativeStats { public interface StatsInterface { String getNativeClass(); int functionCount(); String functionName(int ordinal); int functionCounter(int ordinal); } public static class NativeFunction implements Comparable { private final int ordinal; private final String name; private int counter; public NativeFunction(int ordinal, String name, int callCount) { this.ordinal = ordinal; this.name = name; this.counter = callCount; } void subtract(NativeFunction func) { this.counter -= func.counter; } public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } public String getName() { return name; } public int getOrdinal() { return ordinal; } public int compareTo(NativeFunction func) { return func.counter - counter; } public void reset() { counter=0; } public NativeFunction copy() { return new NativeFunction(ordinal, name, counter); } } private final HashMap> snapshot; public NativeStats(StatsInterface... classes) { this(Arrays.asList(classes)); } public NativeStats(Collection classes) { this(snapshot(classes)); } private NativeStats(HashMap> snapshot) { this.snapshot = snapshot; } public void reset() { for (ArrayList functions : snapshot.values()) { for (NativeFunction function : functions) { function.reset(); } } } public void update() { for (Entry> entry : snapshot.entrySet()) { StatsInterface si = entry.getKey(); for (NativeFunction function : entry.getValue()) { function.setCounter( si.functionCounter(function.getOrdinal()) ); } } } public NativeStats snapshot() { NativeStats copy = copy(); copy.update(); return copy; } public NativeStats copy() { HashMap> rc = new HashMap>(snapshot.size()*2); for (Entry> entry : snapshot.entrySet()) { ArrayList list = new ArrayList(entry.getValue().size()); for (NativeFunction function : entry.getValue()) { list.add(function.copy()); } rc.put(entry.getKey(), list); } return new NativeStats(rc); } public NativeStats diff() { HashMap> rc = new HashMap>(snapshot.size()*2); for (Entry> entry : snapshot.entrySet()) { StatsInterface si = entry.getKey(); ArrayList list = new ArrayList(entry.getValue().size()); for (NativeFunction original : entry.getValue()) { NativeFunction copy = original.copy(); copy.setCounter( si.functionCounter(copy.getOrdinal()) ); copy.subtract(original); list.add(copy); } rc.put(si, list); } return new NativeStats(rc); } /** * Dumps the stats to the print stream in a JSON format. * @param ps Print stream. */ public void dump(PrintStream ps) { boolean firstSI=true; for (Entry> entry : snapshot.entrySet()) { StatsInterface si = entry.getKey(); ArrayList funcs = entry.getValue(); int total = 0; for (NativeFunction func : funcs) { total += func.getCounter(); } if( !firstSI ) { ps.print(", "); } firstSI=false; ps.print("["); if( total>0 ) { ps.println("{ "); ps.println(" \"class\": \""+si.getNativeClass()+"\","); ps.println(" \"total\": "+total+", "); ps.print(" \"functions\": {"); boolean firstFunc=true; for (NativeFunction func : funcs) { if (func.getCounter() > 0) { if( !firstFunc ) { ps.print(","); } firstFunc=false; ps.println(); ps.print(" \""+func.getName()+"\": "+func.getCounter()); } } ps.println(); ps.println(" }"); ps.print("}"); } ps.print("]"); } } static private HashMap> snapshot(Collection classes) { HashMap> rc = new HashMap>(); for (StatsInterface sc : classes) { int count = sc.functionCount(); ArrayList functions = new ArrayList(count); for (int i = 0; i < count; i++) { String name = (String) sc.functionName(i); functions.add(new NativeFunction(i, name, 0)); } Collections.sort(functions); rc.put(sc, functions); } return rc; } } PointerMath.java000066400000000000000000000015141475274123300341770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; /** * * @author Hiram Chirino */ public class PointerMath { private static final boolean bits32 = Library.getBitModel() == 32; final public static long add(long ptr, long n) { if(bits32) { return (int)(ptr + n); } else { return ptr + n; } } } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-runtime/src/main/java/org/fusesource/hawtjni/runtime/T32.java000066400000000000000000000015041475274123300323730ustar00rootroot00000000000000/******************************************************************************* * Copyright (C) 2009-2011 FuseSource Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.fusesource.hawtjni.runtime; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Documented; @Documented @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) public @interface T32 { } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/000077500000000000000000000000001475274123300204025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/ext/000077500000000000000000000000001475274123300212025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/ext/ScalatePackage.scala000066400000000000000000000021631475274123300250410ustar00rootroot00000000000000/** * Copyright (C) 2009-2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.fusesource.scalate.support.TemplatePackage import org.fusesource.scalate.{Binding, TemplateSource} /** * Defines the template package of reusable imports, attributes and methods across templates */ class ScalatePackage extends TemplatePackage { def header(source: TemplateSource, bindings: List[Binding]) = """ // common imports go here import _root_.Website._; """ } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/ext/Website.scala000066400000000000000000000041611475274123300236130ustar00rootroot00000000000000/** * Copyright (C) 2009-2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.fusesource.scalate.RenderContext package /** *

*

* * @author Hiram Chirino */ object Website { val project_name= "HawtJNI" val project_slogan= "Making JNI easy and fast." val project_id= "hawtjni" val project_issue_url= "https://github.com/fusesource/hawtjni/issues" val project_forums_url= "http://groups.google.com/group/hawtjni" val project_wiki_url= "https://github.com/fusesource/hawtjni/wiki" val project_logo= "/images/project-logo.png" val project_version= "1.17" val project_snapshot_version= "1.18-SNAPSHOT" val project_versions = List( project_version, "1.16", "1.15", "1.14", "1.13", "1.12", "1.11", "1.10", "1.9", "1.8", "1.7", "1.6", "1.5", "1.4", "1.3", "1.2", "1.1", "1.0" ) val project_keywords= "jni,java,jna,c,objective-c,c++,c#" // ------------------------------------------------------------------- val github_page= "http://github.com/fusesource/hawtjni" val git_user_url= "git://github.com/fusesource/hawtjni.git" val git_commiter_url= "git@github.com:fusesources/hawtjni.git" val project_maven_groupId= "org.fusesource.hawtjni" val project_maven_artifactId= "hawtjni-runtime" val website_base_url= "http://fusesource.github.io/hawtjni/" } jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/ext/scalate/000077500000000000000000000000001475274123300226165ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/ext/scalate/Boot.scala000066400000000000000000000053751475274123300245400ustar00rootroot00000000000000/** * Copyright (C) 2009-2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package scalate import org.fusesource.scalate.util.Logging import java.util.concurrent.atomic.AtomicBoolean import _root_.Website._ import org.fusesource.scalate._ import org.fusesource.scalamd.{MacroDefinition, Markdown} import java.util.regex.Matcher import org.fusesource.scalate.wikitext.Pygmentize class Boot(engine: TemplateEngine) extends Logging { private var _initialised = new AtomicBoolean(false) def run: Unit = { if (_initialised.compareAndSet(false, true)) { def filter(m:Matcher):String = { val filter_name = m.group(1) val body = m.group(2) engine.filter(filter_name) match { case Some(filter)=> filter.filter(RenderContext(), body) case None=> "

filter not found: %s

%s
".format(filter_name, body) } } def pygmentize(m:Matcher):String = Pygmentize.pygmentize(m.group(2), m.group(1)) // add some macros to markdown. Markdown.macros :::= List( MacroDefinition("""\{filter::(.*?)\}(.*?)\{filter\}""", "s", filter, true), MacroDefinition("""\{pygmentize::(.*?)\}(.*?)\{pygmentize\}""", "s", pygmentize, true), MacroDefinition("""\{pygmentize\_and\_compare::(.*?)\}(.*?)\{pygmentize\_and\_compare\}""", "s", pygmentize, true), MacroDefinition("""\$\{project_version\}""", "", _ => project_version.toString, true), MacroDefinition("""\$\{project_name\}""", "", _ => project_name.toString, true), MacroDefinition("""\$\{project_id\}""", "", _ => project_id.toString, true), MacroDefinition("""\$\{project_issue_url\}""", "", _ => project_issue_url.toString, true), MacroDefinition("""\$\{website_base_url\}""", "", _ => website_base_url.toString, true) ) for( ssp <- engine.filter("ssp"); md <- engine.filter("markdown") ) { engine.pipelines += "ssp.md"-> List(ssp, md) engine.pipelines += "ssp.markdown"-> List(ssp, md) } info("Bootstrapped website gen for: %s".format(project_name)) } } }jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/pom.xml000066400000000000000000000177041475274123300217300ustar00rootroot00000000000000 4.0.0 org.fusesource.hawtjni hawtjni-project 1.17 hawtjni-website ${project.artifactId} The HawtJNI Website pom Tomcat60 hawtjni-gh-pages scm:git:https://github.com/fusesource/hawtjni.git org.scala-lang scala-library ${scala-version} org.scala-lang scala-compiler ${scala-version} org.fusesource.scalate scalate-wikitext ${scalate-version} org.fusesource.scalate scalate-page ${scalate-version} org.fusesource.scalamd scalamd ${scalamd-version} org.slf4j slf4j-log4j12 ${slf4j-version} org.fusesource.scalate scalate-test ${scalate-version} test org.fusesource.hawtjni hawtjni-runtime ${project.version} javadoc test ext true maven-source-plugin attach-sources jar org.scala-tools maven-scala-plugin ${scala-plugin-version} compile -Xmx1024m ${scala-version} maven-surefire-plugin once false false **/*Test.* org.fusesource.scalate maven-scalate-plugin ${scalate-version} ${basedir}/src sitegen sitegen package org.apache.maven.plugins maven-scm-publish-plugin 1.1 gh-pages ${project.build.directory}/sitegen gh-pages publish-scm install org.mortbay.jetty jetty-maven-plugin ${jetty-plugin-version} ${basedir}/src scalate.editor ${env.SCALATE_EDITOR} scalate.workdir ${basedir}/target/_scalate scalate.mode development 0 org.apache.maven.plugins maven-dependency-plugin 2.2 unpack package unpack org.fusesource.hawtjni hawtjni-runtime javadoc ${basedir}/target/sitegen/documentation/api org.fusesource.mvnplugins maven-linkchecker-plugin ${mvnplugins-version} http://github.com/ http://git.or.cz/ http://localhost:8080/ http://repo.fusesource.com/ http://search.twitter.com/ http://www.chengin.com/ jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/src/000077500000000000000000000000001475274123300211715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/src/WEB-INF/000077500000000000000000000000001475274123300222205ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/src/WEB-INF/scalate/000077500000000000000000000000001475274123300236345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/src/WEB-INF/scalate/layouts/000077500000000000000000000000001475274123300253345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/hawt-jni/hawtjni-website/src/WEB-INF/scalate/layouts/default.jade000066400000000000000000000057571475274123300276230ustar00rootroot00000000000000!!! Basic :plain - response.setContentType("text/html") -@ var title : String = "" -@ var body: String = null -@ var overview: String = null -@ var spot: String = null -@ var blog: String = null -@ var head: String = null - val include_console = engine.isDevelopmentMode && engine.resourceLoader.exists("/org/fusesource/scalate/console/console_head.scaml") html(lang="en") head meta(content="text/html; charset=utf-8" http-equiv="Content-Type") meta(content="#{project_slogan}" name="description") meta(content="#{project_keywords}" name="keywords") meta(content="#{project_name}" name="author") link(type="text/css" rel="stylesheet" href={uri("/styles/impact/css/pygmentize.css")}) link(type="text/css" rel="stylesheet" href={uri("/styles/impact/css/site.css")}) - if (head!=null) !~~ head -# - if (include_console) - include("/org/fusesource/scalate/console/console_head.scaml") link(href={uri("/css/scalate/console.css")} rel="stylesheet" type="text/css") title= title body div#navigation div.wrapper - include("/_navigation.ssp.md") - if (overview!=null) div#overview div.wrapper -if ( project_logo!=null ) div.logo img(src="#{uri(project_logo)}" alt="#{project_name} logo") div.message !~~ overview - if (spot!=null) div#spot div.wrapper !~~ spot - if (body!=null) div#content div.wrapper !~~ body - if (blog!=null) div#blog div.wrapper !~~ blog -# - if (include_console) = include("/org/fusesource/scalate/console/console.scaml") -# :javascript var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); \n" + "\n"; public static void generateLog( ITestContext testContext, String host, String outputDirectory, Collection failedConfs, Collection skippedConfs, Collection passedTests, Collection failedTests, Collection skippedTests, Collection percentageTests) { try (PrintWriter writer = new PrintWriter(Utils.openWriter(outputDirectory, getOutputFile(testContext)))) { writer .append("\n\n") .append("TestNG: ") .append(testContext.getName()) .append("\n") .append(HtmlHelper.getCssString()) .append(HEAD) .append("\n") .append("\n"); Date startDate = testContext.getStartDate(); Date endDate = testContext.getEndDate(); long duration = (endDate.getTime() - startDate.getTime()) / 1000; int passed = testContext.getPassedTests().size() + testContext.getFailedButWithinSuccessPercentageTests().size(); int failed = testContext.getFailedTests().size(); int skipped = testContext.getSkippedTests().size(); String hostLine = Utils.isStringEmpty(host) ? "" : "Remote host:" + host + "\n"; writer .append("

") .append(testContext.getName()) .append("

") .append("\n") .append("\n") // .append("\n") // .append("\n") .append("\n") .append("\n") .append("\n") .append("\n") .append(hostLine) .append("\n") .append("\n") .append("\n") .append("\n") .append("\n") .append("\n") .append("
Property // file:").append(m_testRunner.getPropertyFileName()).append("
Tests passed/Failed/Skipped:") .append(Integer.toString(passed)) .append("/") .append(Integer.toString(failed)) .append("/") .append(Integer.toString(skipped)) .append("
Started on:") .append(testContext.getStartDate().toString()) .append("
Total time:") .append(Long.toString(duration)) .append(" seconds (") .append(Long.toString(endDate.getTime() - startDate.getTime())) .append(" ms)
Included groups:") .append(arrayToString(testContext.getIncludedGroups())) .append("
Excluded groups:") .append(arrayToString(testContext.getExcludedGroups())) .append("

\n"); writer.append( "(Hover the method name to see the test class name)

\n"); if (!failedConfs.isEmpty()) { generateTable( writer, "FAILED CONFIGURATIONS", failedConfs, "failed", CONFIGURATION_COMPARATOR); } if (!skippedConfs.isEmpty()) { generateTable( writer, "SKIPPED CONFIGURATIONS", skippedConfs, "skipped", CONFIGURATION_COMPARATOR); } if (!failedTests.isEmpty()) { generateTable(writer, "FAILED TESTS", failedTests, "failed", NAME_COMPARATOR); } if (!percentageTests.isEmpty()) { generateTable( writer, "FAILED TESTS BUT WITHIN SUCCESS PERCENTAGE", percentageTests, "percent", NAME_COMPARATOR); } if (!passedTests.isEmpty()) { generateTable(writer, "PASSED TESTS", passedTests, "passed", NAME_COMPARATOR); } if (!skippedTests.isEmpty()) { generateTable(writer, "SKIPPED TESTS", skippedTests, "skipped", NAME_COMPARATOR); } writer.append("\n"); } catch (IOException e) { if (TestRunner.getVerbose() > 1) { Logger.getLogger(TestRunner.class).error(e.getMessage(), e); } else { log(e.getMessage()); } } } private static void log(String s) { Logger.getLogger(TestHTMLReporter.class).info("[TestHTMLReporter] " + s); } private static class NameComparator implements Comparator { @Override public int compare(ITestResult o1, ITestResult o2) { String c1 = o1.getMethod().getMethodName(); String c2 = o2.getMethod().getMethodName(); return c1.compareTo(c2); } } private static class ConfigurationComparator implements Comparator { @Override public int compare(ITestResult o1, ITestResult o2) { ITestNGMethod tm1 = o1.getMethod(); ITestNGMethod tm2 = o2.getMethod(); return annotationValue(tm2) - annotationValue(tm1); } private static int annotationValue(ITestNGMethod method) { if (method.isBeforeSuiteConfiguration()) { return 10; } if (method.isBeforeTestConfiguration()) { return 9; } if (method.isBeforeClassConfiguration()) { return 8; } if (method.isBeforeGroupsConfiguration()) { return 7; } if (method.isBeforeMethodConfiguration()) { return 6; } if (method.isAfterMethodConfiguration()) { return 5; } if (method.isAfterGroupsConfiguration()) { return 4; } if (method.isAfterClassConfiguration()) { return 3; } if (method.isAfterTestConfiguration()) { return 2; } if (method.isAfterSuiteConfiguration()) { return 1; } return 0; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/TextReporter.java000066400000000000000000000140421475274123300314020ustar00rootroot00000000000000package org.testng.reporters; import static org.testng.internal.Utils.isStringNotBlank; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.internal.Utils; /** A simple reporter that collects the results and prints them on standard out. */ public class TextReporter implements ITestListener { private static final String LINE = "\n===============================================\n"; private final int m_verbose; private final String m_testName; public TextReporter(String testName, int verbose) { m_testName = testName; m_verbose = verbose; } @Override public void onFinish(ITestContext context) { if (m_verbose >= 2) { logResults(context); } } private static List resultsToMethods(Collection results) { return results.stream().map(ITestResult::getMethod).collect(Collectors.toList()); } private void logResults(ITestContext context) { // Log Text Set results = context.getFailedConfigurations().getAllResults(); for (ITestResult tr : results) { Throwable ex = tr.getThrowable(); String stackTrace = ""; if (ex != null && m_verbose >= 2) { stackTrace = Utils.shortStackTrace(ex, false); } logResult( "FAILED CONFIGURATION", Utils.detailedMethodName(tr.getMethod(), false), tr.getMethod().getDescription(), stackTrace, tr.getParameters(), tr.getMethod().getParameterTypes()); } results = context.getSkippedConfigurations().getAllResults(); for (ITestResult tr : results) { logResult( "SKIPPED CONFIGURATION", Utils.detailedMethodName(tr.getMethod(), false), tr.getMethod().getDescription(), null, tr.getParameters(), tr.getMethod().getParameterTypes()); } results = context.getPassedTests().getAllResults(); for (ITestResult tr : results) { logResult("PASSED", tr, null); } results = context.getFailedTests().getAllResults(); for (ITestResult tr : results) { Throwable ex = tr.getThrowable(); String stackTrace = ""; if (ex != null && m_verbose >= 2) { stackTrace = Utils.shortStackTrace(ex, false); } logResult("FAILED", tr, stackTrace); } results = context.getSkippedTests().getAllResults(); List rawskipped = new ArrayList<>(results); List skippedTests = Lists.newArrayList(); List retriedTests = Lists.newArrayList(); for (ITestResult result : rawskipped) { if (result.wasRetried()) { retriedTests.add(result); } else { skippedTests.add(result); } } logExceptions("SKIPPED", skippedTests); logExceptions("RETRIED", retriedTests); List ft = resultsToMethods(context.getFailedTests().getAllResults()); StringBuilder logBuf = new StringBuilder(LINE); logBuf.append(" ").append(m_testName).append("\n"); logBuf .append(" Tests run: ") .append(context.getAllTestMethods().length) .append(", Failures: ") .append(ft.size()) .append(", Skips: ") .append(resultsToMethods(skippedTests).size()); if (!retriedTests.isEmpty()) { logBuf.append(", Retries: ").append(resultsToMethods(retriedTests).size()); } int confFailures = context.getFailedConfigurations().size(); int confSkips = context.getSkippedConfigurations().size(); if (confFailures > 0 || confSkips > 0) { logBuf .append("\n") .append(" Configuration Failures: ") .append(confFailures) .append(", Skips: ") .append(confSkips); } logBuf.append(LINE); logResult("", logBuf.toString()); } private void logResult(String status, ITestResult tr, String stackTrace) { logResult( status, tr.getName(), tr.getMethod().getDescription(), stackTrace, tr.getParameters(), tr.getMethod().getParameterTypes()); } private void logExceptions(String status, List results) { results.forEach( tr -> { Throwable throwable = tr.getThrowable(); logResult(status, tr, throwable != null ? Utils.shortStackTrace(throwable, false) : null); }); } private void logResult(String status, String message) { StringBuilder buf = new StringBuilder(); if (isStringNotBlank(status)) { buf.append(status).append(": "); } buf.append(message); System.out.println(buf); } private void logResult( String status, String name, String description, String stackTrace, Object[] params, Class[] paramTypes) { StringBuilder msg = new StringBuilder(name); if (null != params && params.length > 0) { msg.append("("); // The error might be a data provider parameter mismatch, so make // a special case here if (params.length != paramTypes.length) { msg.append(name) .append(": Wrong number of arguments were passed by ") .append("the Data Provider: found ") .append(params.length) .append(" but ") .append("expected ") .append(paramTypes.length) .append(")"); } else { for (int i = 0; i < params.length; i++) { if (i > 0) { msg.append(", "); } msg.append(Utils.toString(params[i], paramTypes[i])); } msg.append(")"); } } if (!Utils.isStringEmpty(description)) { msg.append("\n"); for (int i = 0; i < status.length() + 2; i++) { msg.append(" "); } msg.append(description); } if (!Utils.isStringEmpty(stackTrace)) { msg.append("\n").append(stackTrace); } logResult(status, msg.toString()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/VerboseReporter.java000066400000000000000000000204131475274123300320620ustar00rootroot00000000000000package org.testng.reporters; import java.util.Arrays; import java.util.Collection; import org.testng.IConfigurationListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.internal.Utils; /** * Reporter printing out detailed messages about what TestNG is going to run and what is the status * of what has been just run. * *

To see messages from this reporter, either run Ant in verbose mode ('ant -v') or set verbose * level to 5 or higher * * @since 6.4 */ public class VerboseReporter implements IConfigurationListener, ITestListener { /** Default prefix for messages printed out by this reporter */ public static final String LISTENER_PREFIX = "[VerboseTestNG] "; private String suiteName; private final String prefix; private enum Status { SUCCESS(ITestResult.SUCCESS), FAILURE(ITestResult.FAILURE), SKIP(ITestResult.SKIP), SUCCESS_PERCENTAGE_FAILURE(ITestResult.SUCCESS_PERCENTAGE_FAILURE), STARTED(ITestResult.STARTED); private int status; Status(int i) { status = i; } } /** * Create VerboseReporter with custom prefix * * @param prefix prefix for messages printed out by this reporter */ public VerboseReporter(String prefix) { this.prefix = prefix; } @Override public void beforeConfiguration(ITestResult tr) { logTestResult(Status.STARTED, tr, true); } @Override public void onConfigurationFailure(ITestResult tr) { logTestResult(Status.FAILURE, tr, true); } @Override public void onConfigurationSkip(ITestResult tr) { logTestResult(Status.SKIP, tr, true); } @Override public void onConfigurationSuccess(ITestResult tr) { logTestResult(Status.SUCCESS, tr, true); } @Override public void onTestStart(ITestResult tr) { logTestResult(Status.STARTED, tr, false); } @Override public void onTestFailure(ITestResult tr) { logTestResult(Status.FAILURE, tr, false); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult tr) { logTestResult(Status.SUCCESS_PERCENTAGE_FAILURE, tr, false); } @Override public void onTestSkipped(ITestResult tr) { logTestResult(Status.SKIP, tr, false); } @Override public void onTestSuccess(ITestResult tr) { logTestResult(Status.SUCCESS, tr, false); } @Override public void onStart(ITestContext ctx) { suiteName = ctx.getName(); log( "RUNNING: Suite: \"" + suiteName + "\" containing \"" + ctx.getAllTestMethods().length + "\" Tests (config: " + ctx.getSuite().getXmlSuite().getFileName() + ")"); } @Override public void onFinish(ITestContext context) { logResults(context); suiteName = null; } private ITestNGMethod[] resultsToMethods(Collection results) { return results.stream().map(ITestResult::getMethod).toArray(ITestNGMethod[]::new); } /** Print out test summary */ private void logResults(ITestContext context) { // // Log test summary // ITestNGMethod[] ft = resultsToMethods(context.getFailedTests().getAllResults()); StringBuilder sb = new StringBuilder("\n===============================================\n"); sb.append(" ").append(suiteName).append("\n"); sb.append(" Tests run: ").append(context.getAllTestMethods().length); sb.append(", Failures: ").append(ft.length); sb.append(", Skips: ") .append(Arrays.toString(resultsToMethods(context.getSkippedTests().getAllResults()))); int confFailures = context.getFailedConfigurations().size(); int confSkips = context.getSkippedConfigurations().size(); if (confFailures > 0 || confSkips > 0) { sb.append("\n").append(" Configuration Failures: ").append(confFailures); sb.append(", Skips: ").append(confSkips); } sb.append("\n==============================================="); log(sb.toString()); } /** * Log meaningful message for passed in arguments. Message itself is of form: $status: * "$suiteName" - $methodDeclaration ($actualArguments) finished in $x ms ($run of $totalRuns) * * @param st status of passed in itr * @param itr test result to be described * @param isConfMethod is itr describing configuration method */ private void logTestResult(Status st, ITestResult itr, boolean isConfMethod) { StringBuilder sb = new StringBuilder(); String stackTrace = ""; switch (st) { case STARTED: sb.append("INVOKING"); break; case SKIP: sb.append("SKIPPED"); stackTrace = itr.getThrowable() != null ? Utils.shortStackTrace(itr.getThrowable(), false) : ""; break; case FAILURE: sb.append("FAILED"); stackTrace = itr.getThrowable() != null ? Utils.shortStackTrace(itr.getThrowable(), false) : ""; break; case SUCCESS: sb.append("PASSED"); break; case SUCCESS_PERCENTAGE_FAILURE: sb.append("PASSED with failures"); break; default: // not happen throw new RuntimeException("Unsupported test status:" + itr.getStatus()); } if (isConfMethod) { sb.append(" CONFIGURATION: "); } else { sb.append(": "); } ITestNGMethod tm = itr.getMethod(); int identLevel = sb.length(); sb.append(getMethodDeclaration(tm, itr)); Object[] params = itr.getParameters(); Class[] paramTypes = itr.getMethod().getParameterTypes(); if (null != params && params.length > 0) { // The error might be a data provider parameter mismatch, so make // a special case here if (params.length != paramTypes.length) { sb.append("Wrong number of arguments were passed by the Data Provider: found "); sb.append(params.length); sb.append(" but expected "); sb.append(paramTypes.length); } else { sb.append("(value(s): "); for (int i = 0; i < params.length; i++) { if (i > 0) { sb.append(", "); } sb.append(Utils.toString(params[i], paramTypes[i])); } sb.append(")"); } } if (Status.STARTED != st) { sb.append(" finished in "); sb.append(itr.getEndMillis() - itr.getStartMillis()); sb.append(" ms"); if (!Utils.isStringEmpty(tm.getDescription())) { sb.append("\n"); for (int i = 0; i < identLevel; i++) { sb.append(" "); } sb.append(tm.getDescription()); } if (tm.getInvocationCount() > 1) { sb.append(" ("); sb.append(tm.getCurrentInvocationCount()); sb.append(" of "); sb.append(tm.getInvocationCount()); sb.append(")"); } if (!Utils.isStringEmpty(stackTrace)) { sb.append("\n") .append( stackTrace, 0, stackTrace.lastIndexOf(RuntimeBehavior.getDefaultLineSeparator())); } } else { if (!isConfMethod && tm.getInvocationCount() > 1) { sb.append(" success: "); sb.append(tm.getSuccessPercentage()); sb.append("%"); } } log(sb.toString()); } protected void log(String message) { // prefix all output lines System.out.println(message.replaceAll("(?m)^", prefix)); } /** * @param method method to be described * @return FQN of a class + method declaration for a method passed in ie. * test.triangle.CheckCount.testCheckCount(java.lang.String) */ private String getMethodDeclaration(ITestNGMethod method, ITestResult tr) { // see Utils.detailedMethodName // perhaps should rather adopt the original method instead StringBuilder buf = new StringBuilder(); buf.append("\""); if (suiteName != null) { buf.append(suiteName); } else { buf.append("UNKNOWN"); } buf.append("\""); buf.append(" - "); String tempName = Utils.annotationFormFor(method); if (!tempName.isEmpty()) { buf.append(Utils.annotationFormFor(method)).append(" "); } buf.append(method.getQualifiedName()); Class[] objects = tr.getMethod().getParameterTypes(); buf.append("(").append(Utils.stringifyTypes(objects)).append(")"); return buf.toString(); } @Override public String toString() { return "VerboseReporter{" + "suiteName=" + suiteName + '}'; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/XMLConstants.java000066400000000000000000000035631475274123300312760ustar00rootroot00000000000000package org.testng.reporters; /** * interface groups the XML constants tries to emulate what's in * org.apache.tools.ant.taskdefs.optional.junit.XMLConstants to be compatible with junitreport */ public interface XMLConstants { /** the testsuites element for the aggregate document */ String TESTSUITES = "testsuites"; /** the testsuite element */ String TESTSUITE = "testsuite"; /** the testcase element */ String TESTCASE = "testcase"; /** the error element */ String ERROR = "error"; /** the failure element */ String FAILURE = "failure"; String SKIPPED = "skipped"; /** the system-err element */ String SYSTEM_ERR = "system-err"; /** the system-out element */ String SYSTEM_OUT = "system-out"; /** package attribute for the aggregate document */ String ATTR_PACKAGE = "package"; /** name attribute for property, testcase and testsuite elements */ String ATTR_NAME = "name"; /** time attribute for testcase and testsuite elements */ String ATTR_TIME = "time"; /** errors attribute for testsuite elements */ String ATTR_ERRORS = "errors"; /** failures attribute for testsuite elements */ String ATTR_FAILURES = "failures"; /** ignored attribute for testsuite elements */ String ATTR_IGNORED = "ignored"; /** tests attribute for testsuite elements */ String ATTR_TESTS = "tests"; /** type attribute for failure and error elements */ String ATTR_TYPE = "type"; /** message attribute for failure elements */ String ATTR_MESSAGE = "message"; /** the properties element */ String PROPERTIES = "properties"; /** the property element */ String PROPERTY = "property"; /** value attribute for property elements */ String ATTR_VALUE = "value"; /** classname attribute for testcase elements */ String ATTR_CLASSNAME = "classname"; String ATTR_HOSTNAME = "hostname"; String ATTR_TIMESTAMP = "timestamp"; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/XMLReporter.java000066400000000000000000000203761475274123300311250ustar00rootroot00000000000000package org.testng.reporters; import java.io.File; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.internal.Utils; import org.testng.util.TimeUtils; import org.testng.xml.XmlSuite; /** The main entry for the XML generation operation */ public class XMLReporter implements IReporter, ICustomizeXmlReport { private final XMLReporterConfig config = new XMLReporterConfig(); private XMLStringBuffer rootBuffer; @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { if (Utils.isStringEmpty(config.getOutputDirectory())) { config.setOutputDirectory(outputDirectory); } // Calculate passed/failed/skipped int passed = 0; int failed = 0; int skipped = 0; int ignored = 0; int retried = 0; for (ISuite s : suites) { Map suiteResults = s.getResults(); for (ISuiteResult sr : suiteResults.values()) { ITestContext testContext = sr.getTestContext(); passed += testContext.getPassedTests().size(); failed += testContext.getFailedTests().size(); int retriedPerTest = 0; int skippedPerTest = 0; for (ITestResult result : testContext.getSkippedTests().getAllResults()) { if (result.wasRetried()) { retriedPerTest++; } else { skippedPerTest++; } } skipped += skippedPerTest; retried += retriedPerTest; ignored += testContext.getExcludedMethods().size(); } } rootBuffer = new XMLStringBuffer(); Properties p = new Properties(); p.put("passed", passed); p.put("failed", failed); p.put("skipped", skipped); if (retried > 0) { p.put("retried", retried); } p.put("ignored", ignored); p.put("total", passed + failed + skipped + ignored + retried); rootBuffer.push(XMLReporterConfig.TAG_TESTNG_RESULTS, p); writeReporterOutput(rootBuffer); for (ISuite suite : suites) { writeSuite(suite); } rootBuffer.pop(); Utils.writeUtf8File(config.getOutputDirectory(), fileName(), rootBuffer, null /* no prefix */); } @Override public void addCustomTagsFor(XMLStringBuffer xmlBuffer, ITestResult testResult) {} public String fileName() { return RuntimeBehavior.getDefaultFileNameForXmlReports(); } private void writeReporterOutput(XMLStringBuffer xmlBuffer) { // TODO: Cosmin - maybe a element isn't indicated for each line xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT); List output = Reporter.getOutput(); for (String line : output) { if (line != null) { xmlBuffer.push(XMLReporterConfig.TAG_LINE); xmlBuffer.addCDATA(line); xmlBuffer.pop(); } } xmlBuffer.pop(); } private void writeSuite(ISuite suite) { switch (config.getFileFragmentationLevel()) { case XMLReporterConfig.FF_LEVEL_NONE: writeSuiteToBuffer(rootBuffer, suite); break; case XMLReporterConfig.FF_LEVEL_SUITE: case XMLReporterConfig.FF_LEVEL_SUITE_RESULT: File suiteFile = referenceSuite(rootBuffer, suite); writeSuiteToFile(suiteFile, suite); break; default: throw new AssertionError("Unexpected value: " + config.getFileFragmentationLevel()); } } private void writeSuiteToFile(File suiteFile, ISuite suite) { XMLStringBuffer xmlBuffer = new XMLStringBuffer(); writeSuiteToBuffer(xmlBuffer, suite); File parentDir = suiteFile.getParentFile(); suiteFile.getParentFile().mkdirs(); if (parentDir.exists() || suiteFile.getParentFile().exists()) { Utils.writeUtf8File(parentDir.getAbsolutePath(), fileName(), xmlBuffer.toXML()); } } private File referenceSuite(XMLStringBuffer xmlBuffer, ISuite suite) { String relativePath = suite.getName() + File.separatorChar + fileName(); File suiteFile = new File(config.getOutputDirectory(), relativePath); Properties attrs = new Properties(); attrs.setProperty(XMLReporterConfig.ATTR_URL, relativePath); xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_SUITE, attrs); return suiteFile; } private void writeSuiteToBuffer(XMLStringBuffer xmlBuffer, ISuite suite) { xmlBuffer.push(XMLReporterConfig.TAG_SUITE, getSuiteAttributes(suite)); writeSuiteGroups(xmlBuffer, suite); Map results = suite.getResults(); XMLSuiteResultWriter suiteResultWriter = new XMLSuiteResultWriter(config, this); for (Map.Entry result : results.entrySet()) { suiteResultWriter.writeSuiteResult(xmlBuffer, result.getValue()); } xmlBuffer.pop(); } private void writeSuiteGroups(XMLStringBuffer xmlBuffer, ISuite suite) { xmlBuffer.push(XMLReporterConfig.TAG_GROUPS); Map> methodsByGroups = suite.getMethodsByGroups(); for (Map.Entry> entry : methodsByGroups.entrySet()) { Properties groupAttrs = new Properties(); groupAttrs.setProperty(XMLReporterConfig.ATTR_NAME, entry.getKey()); xmlBuffer.push(XMLReporterConfig.TAG_GROUP, groupAttrs); Set groupMethods = getUniqueMethodSet(entry.getValue()); for (ITestNGMethod groupMethod : groupMethods) { Properties methodAttrs = new Properties(); methodAttrs.setProperty(XMLReporterConfig.ATTR_NAME, groupMethod.getMethodName()); methodAttrs.setProperty(XMLReporterConfig.ATTR_METHOD_SIG, groupMethod.toString()); methodAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, groupMethod.getRealClass().getName()); xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_METHOD, methodAttrs); } xmlBuffer.pop(); } xmlBuffer.pop(); } private Properties getSuiteAttributes(ISuite suite) { Properties props = new Properties(); props.setProperty(XMLReporterConfig.ATTR_NAME, suite.getName()); // Calculate the duration Map results = suite.getResults(); Date minStartDate = new Date(); Date maxEndDate = null; // TODO: We could probably optimize this in order not to traverse this twice for (Map.Entry result : results.entrySet()) { ITestContext testContext = result.getValue().getTestContext(); Date startDate = testContext.getStartDate(); Date endDate = testContext.getEndDate(); if (minStartDate.after(startDate)) { minStartDate = startDate; } if (maxEndDate == null || maxEndDate.before(endDate)) { maxEndDate = endDate != null ? endDate : startDate; } } // The suite could be completely empty if (maxEndDate == null) { maxEndDate = minStartDate; } addDurationAttributes(config, props, minStartDate, maxEndDate); return props; } /** * Add started-at, finished-at and duration-ms attributes to the <suite> tag * * @param config The reporter config * @param attributes The properties * @param minStartDate The minimum start date * @param maxEndDate The maximum end date */ public static void addDurationAttributes( XMLReporterConfig config, Properties attributes, Date minStartDate, Date maxEndDate) { String startTime = TimeUtils.formatTimeInLocalOrSpecifiedTimeZone( minStartDate.getTime(), config.getTimestampFormat()); String endTime = TimeUtils.formatTimeInLocalOrSpecifiedTimeZone( maxEndDate.getTime(), config.getTimestampFormat()); long duration = maxEndDate.getTime() - minStartDate.getTime(); attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime); attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime); attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, Long.toString(duration)); } private Set getUniqueMethodSet(Collection methods) { return new LinkedHashSet<>(methods); } @Override public XMLReporterConfig getConfig() { return config; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/XMLSuiteResultWriter.java000066400000000000000000000341301475274123300330010ustar00rootroot00000000000000package org.testng.reporters; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.testng.IDataProviderMethod; import org.testng.IResultMap; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.collections.Sets; import org.testng.internal.Utils; import org.testng.util.Strings; import org.testng.util.TimeUtils; /** * Utility writing an ISuiteResult to an XMLStringBuffer. Depending on the settings in the * config property it might generate an additional XML file with the actual content and only * reference the file with an url attribute in the passed XMLStringBuffer. * * @author Cosmin Marginean, Mar 16, 2007 */ public class XMLSuiteResultWriter { private final XMLReporterConfig config; private final ICustomizeXmlReport customizer; public XMLSuiteResultWriter(XMLReporterConfig config, ICustomizeXmlReport customizer) { this.config = config; this.customizer = customizer; } /** * Writes the specified ISuiteResult in the given XMLStringBuffer. Please consider that depending * on the settings in the config property it might generate an additional XML file * with the actual content and only reference the file with an url attribute in the * passed XMLStringBuffer. * * @param xmlBuffer The XML buffer where to write or reference the suite result * @param suiteResult The ISuiteResult to serialize */ public void writeSuiteResult(XMLStringBuffer xmlBuffer, ISuiteResult suiteResult) { if (XMLReporterConfig.FF_LEVEL_SUITE_RESULT != config.getFileFragmentationLevel()) { writeAllToBuffer(xmlBuffer, suiteResult); } else { String parentDir = config.getOutputDirectory() + File.separatorChar + suiteResult.getTestContext().getSuite().getName(); File file = referenceSuiteResult(xmlBuffer, parentDir, suiteResult); XMLStringBuffer suiteXmlBuffer = new XMLStringBuffer(); writeAllToBuffer(suiteXmlBuffer, suiteResult); Utils.writeUtf8File( file.getAbsoluteFile().getParent(), file.getName(), suiteXmlBuffer.toXML()); } } private void writeAllToBuffer(XMLStringBuffer xmlBuffer, ISuiteResult suiteResult) { xmlBuffer.push(XMLReporterConfig.TAG_TEST, getSuiteResultAttributes(suiteResult)); Set testResults = Sets.newHashSet(); ITestContext testContext = suiteResult.getTestContext(); addAllTestResults(testResults, testContext.getPassedTests()); addAllTestResults(testResults, testContext.getFailedTests()); addAllTestResults(testResults, testContext.getSkippedTests()); addAllTestResults(testResults, testContext.getPassedConfigurations()); addAllTestResults(testResults, testContext.getSkippedConfigurations()); addAllTestResults(testResults, testContext.getFailedConfigurations()); addAllTestResults(testResults, testContext.getFailedButWithinSuccessPercentageTests()); addTestResults(xmlBuffer, testResults); xmlBuffer.pop(); } @SuppressWarnings("unchecked") private void addAllTestResults(Set testResults, IResultMap resultMap) { if (resultMap != null) { // Sort the results chronologically before adding them List allResults = new ArrayList<>(resultMap.getAllResults()); new ArrayList(allResults) .sort( (Comparator) (o1, o2) -> (int) (o1.getStartMillis() - o2.getStartMillis())); testResults.addAll(allResults); } } private File referenceSuiteResult( XMLStringBuffer xmlBuffer, String parentDir, ISuiteResult suiteResult) { Properties attrs = new Properties(); String suiteResultName = suiteResult.getTestContext().getName() + ".xml"; attrs.setProperty(XMLReporterConfig.ATTR_URL, suiteResultName); xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_TEST, attrs); return new File(parentDir + File.separatorChar + suiteResultName); } private Properties getSuiteResultAttributes(ISuiteResult suiteResult) { Properties attributes = new Properties(); ITestContext tc = suiteResult.getTestContext(); attributes.setProperty(XMLReporterConfig.ATTR_NAME, tc.getName()); XMLReporter.addDurationAttributes(config, attributes, tc.getStartDate(), tc.getEndDate()); return attributes; } private void addTestResults(XMLStringBuffer xmlBuffer, Set testResults) { Map> testsGroupedByClass = buildTestClassGroups(testResults); for (Map.Entry> result : testsGroupedByClass.entrySet()) { Properties attributes = new Properties(); String className = result.getKey(); if (config.isSplitClassAndPackageNames()) { int dot = className.lastIndexOf('.'); attributes.setProperty( XMLReporterConfig.ATTR_NAME, dot > -1 ? className.substring(dot + 1) : className); attributes.setProperty( XMLReporterConfig.ATTR_PACKAGE, dot > -1 ? className.substring(0, dot) : "[default]"); } else { attributes.setProperty(XMLReporterConfig.ATTR_NAME, className); } xmlBuffer.push(XMLReporterConfig.TAG_CLASS, attributes); List sortedResults = result.getValue(); Collections.sort(sortedResults); for (ITestResult testResult : sortedResults) { addTestResult(xmlBuffer, testResult); } xmlBuffer.pop(); } } private Map> buildTestClassGroups(Set testResults) { Map> map = Maps.newHashMap(); for (ITestResult result : testResults) { String className = result.getTestClass().getName(); List list = map.computeIfAbsent(className, k -> Lists.newArrayList()); list.add(result); } return map; } private void addTestResult(XMLStringBuffer xmlBuffer, ITestResult testResult) { Properties attribs = getTestResultAttributes(testResult); attribs.setProperty(XMLReporterConfig.ATTR_STATUS, getStatusString(testResult.getStatus())); if (testResult.wasRetried()) { attribs.setProperty(XMLReporterConfig.ATTR_RETRIED, Boolean.TRUE.toString()); } xmlBuffer.push(XMLReporterConfig.TAG_TEST_METHOD, attribs); addTestMethodParams(xmlBuffer, testResult); addTestResultException(xmlBuffer, testResult); addTestResultOutput(xmlBuffer, testResult); if (config.isGenerateTestResultAttributes()) { addTestResultAttributes(xmlBuffer, testResult); } customizer.addCustomTagsFor(xmlBuffer, testResult); xmlBuffer.pop(); } private String getStatusString(int testResultStatus) { switch (testResultStatus) { case ITestResult.SUCCESS: return "PASS"; case ITestResult.FAILURE: return "FAIL"; case ITestResult.SKIP: return "SKIP"; case ITestResult.SUCCESS_PERCENTAGE_FAILURE: return "SUCCESS_PERCENTAGE_FAILURE"; default: throw new AssertionError("Unexpected value: " + testResultStatus); } } private Properties getTestResultAttributes(ITestResult testResult) { Properties attributes = new Properties(); if (!testResult.getMethod().isTest()) { attributes.setProperty(XMLReporterConfig.ATTR_IS_CONFIG, "true"); } attributes.setProperty(XMLReporterConfig.ATTR_NAME, testResult.getMethod().getMethodName()); String testInstanceName = testResult.getTestName(); if (null != testInstanceName) { attributes.setProperty(XMLReporterConfig.ATTR_TEST_INSTANCE_NAME, testInstanceName); } String description = testResult.getMethod().getDescription(); if (!Utils.isStringEmpty(description)) { attributes.setProperty(XMLReporterConfig.ATTR_DESC, description); } attributes.setProperty( XMLReporterConfig.ATTR_METHOD_SIG, removeClassName(testResult.getMethod().toString())); String startTime = TimeUtils.formatTimeInLocalOrSpecifiedTimeZone( testResult.getStartMillis(), config.getTimestampFormat()); String endTime = TimeUtils.formatTimeInLocalOrSpecifiedTimeZone( testResult.getEndMillis(), config.getTimestampFormat()); attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime); attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime); long duration = testResult.getEndMillis() - testResult.getStartMillis(); String strDuration = Long.toString(duration); attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, strDuration); if (config.isGenerateGroupsAttribute()) { String groupNamesStr = Utils.arrayToString(testResult.getMethod().getGroups()); if (!Utils.isStringEmpty(groupNamesStr)) { attributes.setProperty(XMLReporterConfig.ATTR_GROUPS, groupNamesStr); } } if (config.isGenerateDependsOnMethods()) { String dependsOnStr = Utils.arrayToString(testResult.getMethod().getMethodsDependedUpon()); if (!Utils.isStringEmpty(dependsOnStr)) { attributes.setProperty(XMLReporterConfig.ATTR_DEPENDS_ON_METHODS, dependsOnStr); } } if (config.isGenerateDependsOnGroups()) { String dependsOnStr = Utils.arrayToString(testResult.getMethod().getGroupsDependedUpon()); if (!Utils.isStringEmpty(dependsOnStr)) { attributes.setProperty(XMLReporterConfig.ATTR_DEPENDS_ON_GROUPS, dependsOnStr); } } IDataProviderMethod dp = testResult.getMethod().getDataProviderMethod(); if (dp != null) { String dataProvider = dp.getName(); if (!Strings.isNullOrEmpty(dataProvider)) { attributes.setProperty(XMLReporterConfig.ATTR_DATA_PROVIDER, dataProvider); } } return attributes; } private String removeClassName(String methodSignature) { int firstParanthesisPos = methodSignature.indexOf("("); int dotAferClassPos = methodSignature.substring(0, firstParanthesisPos).lastIndexOf("."); return methodSignature.substring(dotAferClassPos + 1); } public void addTestMethodParams(XMLStringBuffer xmlBuffer, ITestResult testResult) { Object[] parameters = testResult.getParameters(); if ((parameters != null) && (parameters.length > 0)) { xmlBuffer.push(XMLReporterConfig.TAG_PARAMS); for (int i = 0; i < parameters.length; i++) { addParameter(xmlBuffer, parameters[i], i); } xmlBuffer.pop(); } } private void addParameter(XMLStringBuffer xmlBuffer, Object parameter, int i) { Properties attrs = new Properties(); attrs.setProperty(XMLReporterConfig.ATTR_INDEX, String.valueOf(i)); xmlBuffer.push(XMLReporterConfig.TAG_PARAM, attrs); if (parameter == null) { Properties valueAttrs = new Properties(); valueAttrs.setProperty(XMLReporterConfig.ATTR_IS_NULL, "true"); xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_PARAM_VALUE, valueAttrs); } else { xmlBuffer.push(XMLReporterConfig.TAG_PARAM_VALUE); xmlBuffer.addCDATA(parameter.toString()); xmlBuffer.pop(); } xmlBuffer.pop(); } private void addTestResultException(XMLStringBuffer xmlBuffer, ITestResult testResult) { Throwable exception = testResult.getThrowable(); if (exception != null) { Properties exceptionAttrs = new Properties(); exceptionAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, exception.getClass().getName()); xmlBuffer.push(XMLReporterConfig.TAG_EXCEPTION, exceptionAttrs); if (!Utils.isStringEmpty(exception.getMessage())) { xmlBuffer.push(XMLReporterConfig.TAG_MESSAGE); xmlBuffer.addCDATA(exception.getMessage()); xmlBuffer.pop(); } XMLReporterConfig.StackTraceLevels level = calculateStackTraceLevels(testResult); switch (level) { case SHORT: xmlBuffer.push(XMLReporterConfig.TAG_SHORT_STACKTRACE); xmlBuffer.addCDATA(Utils.shortStackTrace(exception, false)); xmlBuffer.pop(); break; case FULL: xmlBuffer.push(XMLReporterConfig.TAG_FULL_STACKTRACE); xmlBuffer.addCDATA(Utils.longStackTrace(exception, false)); xmlBuffer.pop(); break; default: // everything else is ignored for now. } xmlBuffer.pop(); } } private XMLReporterConfig.StackTraceLevels calculateStackTraceLevels(ITestResult testResult) { XMLReporterConfig.StackTraceLevels stackTraceoutputMethod = config.getStackTraceOutput(); if (testResult.isSuccess()) { stackTraceoutputMethod = config.getStackTraceOutputLevelForPassedTests(); } return stackTraceoutputMethod; } private void addTestResultOutput(XMLStringBuffer xmlBuffer, ITestResult testResult) { // TODO: Cosmin - maybe a element isn't indicated for each line xmlBuffer.push(XMLReporterConfig.TAG_REPORTER_OUTPUT); List output = Reporter.getOutput(testResult); for (String line : output) { if (line != null) { xmlBuffer.push(XMLReporterConfig.TAG_LINE); xmlBuffer.addCDATA(line); xmlBuffer.pop(); } } xmlBuffer.pop(); } private void addTestResultAttributes(XMLStringBuffer xmlBuffer, ITestResult testResult) { if (testResult.getAttributeNames() != null && testResult.getAttributeNames().size() > 0) { xmlBuffer.push(XMLReporterConfig.TAG_ATTRIBUTES); for (String attrName : testResult.getAttributeNames()) { if (attrName == null) { continue; } Object attrValue = testResult.getAttribute(attrName); Properties attributeAttrs = new Properties(); attributeAttrs.setProperty(XMLReporterConfig.ATTR_NAME, attrName); if (attrValue == null) { attributeAttrs.setProperty(XMLReporterConfig.ATTR_IS_NULL, "true"); xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_ATTRIBUTE, attributeAttrs); } else { xmlBuffer.push(XMLReporterConfig.TAG_ATTRIBUTE, attributeAttrs); xmlBuffer.addCDATA(attrValue.toString()); xmlBuffer.pop(); } } xmlBuffer.pop(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/000077500000000000000000000000001475274123300265015ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/BannerPanel.java000066400000000000000000000014071475274123300315330ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.reporters.XMLStringBuffer; public class BannerPanel extends BasePanel { public BannerPanel(Model model) { super(model); } @Override public void generate(XMLStringBuffer xsb) { xsb.push(D, C, "top-banner-root"); xsb.addRequired(S, "Test results", C, "top-banner-title-font"); xsb.addRequired(B, "Switch Retro Theme", I, "button", C, "button"); xsb.addEmptyElement("br"); int failedCount = getModel().getAllFailedResults().size(); String testResult = failedCount > 0 ? ", " + pluralize(failedCount, "failed test") : ""; String subTitle = pluralize(getModel().getSuites().size(), "suite") + testResult; xsb.addRequired(S, subTitle, C, "top-banner-font-1"); xsb.pop(D); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/BaseMultiSuitePanel.java000066400000000000000000000017471475274123300332340ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.ISuite; import org.testng.reporters.XMLStringBuffer; public abstract class BaseMultiSuitePanel extends BasePanel implements INavigatorPanel { abstract String getHeader(ISuite suite); abstract String getContent(ISuite suite, XMLStringBuffer xsb); public BaseMultiSuitePanel(Model model) { super(model); } @Override public void generate(XMLStringBuffer xsb) { for (ISuite s : getSuites()) { xsb.push(D, C, "panel", "panel-name", getPanelName(s)); xsb.push(D, C, "main-panel-header rounded-window-top"); xsb.addOptional(S, getHeader(s), C, "header-content"); xsb.pop(D); xsb.push(D, C, "main-panel-content rounded-window-bottom"); xsb.addString(getContent(s, xsb)); xsb.pop(D); xsb.pop(D); } } @Override public String getClassName() { return null; } @Override public String getPanelName(ISuite suite) { return getPrefix() + suiteToTag(suite); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/BasePanel.java000066400000000000000000000016501475274123300312000ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.List; import org.testng.ISuite; public abstract class BasePanel implements IPanel { public static final String C = "class"; public static final String D = "div"; public static final String S = "span"; public static final String B = "button"; public static final String I = "id"; private Model m_model; public BasePanel(Model model) { m_model = model; } protected Model getModel() { return m_model; } protected List getSuites() { return getModel().getSuites(); } protected static String pluralize(int count, String singular) { return Integer.toString(count) + " " + (count == 0 || count > 1 ? (singular.endsWith("s") ? singular + "es" : singular + "s") : singular); } protected static String suiteToTag(ISuite suite) { return suite.getName().replaceAll("[^A-Za-z0-9]", "_"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/ChronologicalPanel.java000066400000000000000000000062531475274123300331150ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.testng.IInvokedMethod; import org.testng.ISuite; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.reporters.XMLStringBuffer; public class ChronologicalPanel extends BaseMultiSuitePanel { public ChronologicalPanel(Model model) { super(model); } @Override public String getPrefix() { return "chronological-"; } @Override public String getHeader(ISuite suite) { return "Methods in chronological order"; } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); List invokedMethods = suite.getAllInvokedMethods(); Collections.sort( invokedMethods, new Comparator() { @Override public int compare(IInvokedMethod arg0, IInvokedMethod arg1) { return (int) (arg0.getTestResult().getStartMillis() - arg1.getTestResult().getStartMillis()); } }); String currentClass = ""; long start = 0; for (IInvokedMethod im : invokedMethods) { ITestNGMethod m = im.getTestMethod(); // for (ITestResult tr : results) { // ITestNGMethod m = tr.getMethod(); String cls = "test-method"; if (m.isBeforeSuiteConfiguration()) { cls = "configuration-suite before"; } else if (m.isAfterSuiteConfiguration()) { cls = "configuration-suite after"; } else if (m.isBeforeTestConfiguration()) { cls = "configuration-test before"; } else if (m.isAfterTestConfiguration()) { cls = "configuration-test after"; } else if (m.isBeforeClassConfiguration()) { cls = "configuration-class before"; } else if (m.isAfterClassConfiguration()) { cls = "configuration-class after"; } else if (m.isBeforeMethodConfiguration()) { cls = "configuration-method before"; } else if (m.isAfterMethodConfiguration()) { cls = "configuration-method after"; } ITestResult tr = im.getTestResult(); String methodName = Model.getTestResultName(tr); if (!m.getTestClass().getName().equals(currentClass)) { if (!"".equals(currentClass)) { xsb.pop(D); } xsb.push(D, C, "chronological-class"); xsb.addRequired(D, m.getTestClass().getName(), C, "chronological-class-name"); currentClass = m.getTestClass().getName(); } xsb.push(D, C, cls); if (tr.getStatus() == ITestResult.FAILURE) { xsb.push("img", "src", Model.getImage("failed")); xsb.pop("img"); } // No need to check for skipped methods since by definition, they were never // invoked. xsb.addRequired(S, methodName, C, "method-name"); if (start == 0) { start = tr.getStartMillis(); } xsb.addRequired(S, Long.toString(tr.getStartMillis() - start) + " ms", C, "method-start"); xsb.pop(D); } return xsb.toXML(); } @Override public String getNavigatorLink(ISuite suite) { return "Chronological view"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/GroupPanel.java000066400000000000000000000025001475274123300314150ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.Collections; import java.util.List; import org.testng.ISuite; import org.testng.reporters.XMLStringBuffer; public class GroupPanel extends BaseMultiSuitePanel { public GroupPanel(Model model) { super(model); } @Override public String getPrefix() { return "group-"; } @Override public String getHeader(ISuite suite) { return "Groups for " + suite.getName(); } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); List sortedGroups = getModel().getGroups(suite.getName()); Collections.sort(sortedGroups); for (String group : sortedGroups) { xsb.push(D, C, "test-group"); xsb.addRequired(S, group, C, "test-group-name"); xsb.addEmptyElement("br"); List sortedMethods = getModel().getMethodsInGroup(group); for (String method : sortedMethods) { xsb.push(D, C, "method-in-group"); xsb.addRequired(S, method, C, "method-in-group-name"); xsb.addEmptyElement("br"); xsb.pop(D); } xsb.pop(D); } return xsb.toXML(); } @Override public String getNavigatorLink(ISuite suite) { return pluralize(getModel().getGroups(suite.getName()).size(), "group"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/INavigatorPanel.java000066400000000000000000000004471475274123300323740ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.ISuite; /** Panels that are accessible from the navigator. */ public interface INavigatorPanel extends IPanel { String getPanelName(ISuite suite); String getNavigatorLink(ISuite suite); String getClassName(); String getPrefix(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/IPanel.java000066400000000000000000000002221475274123300305100ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.reporters.XMLStringBuffer; public interface IPanel { void generate(XMLStringBuffer xsb); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/IgnoredMethodsPanel.java000066400000000000000000000026241475274123300332430ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.ISuite; import org.testng.ITestNGMethod; import org.testng.collections.Maps; import org.testng.collections.SetMultiMap; import org.testng.reporters.XMLStringBuffer; public class IgnoredMethodsPanel extends BaseMultiSuitePanel { public IgnoredMethodsPanel(Model model) { super(model); } @Override public String getPrefix() { return "ignored-methods-"; } @Override public String getHeader(ISuite suite) { return pluralize(suite.getExcludedMethods().size(), "ignored method"); } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); SetMultiMap, ITestNGMethod> map = Maps.newSetMultiMap(); for (ITestNGMethod method : suite.getExcludedMethods()) { map.put(method.getTestClass().getRealClass(), method); } for (Class c : map.keySet()) { xsb.push(D, C, "ignored-class-div"); xsb.addRequired(S, c.getName(), C, "ignored-class-name"); xsb.push(D, C, "ignored-methods-div"); for (ITestNGMethod m : map.get(c)) { xsb.addRequired(S, m.getMethodName(), C, "ignored-method-name"); xsb.addEmptyElement("br"); } xsb.pop(D); xsb.pop(D); } return xsb.toXML(); } @Override public String getNavigatorLink(ISuite suite) { return "Ignored methods"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/Main.java000066400000000000000000000065641475274123300302430ustar00rootroot00000000000000package org.testng.reporters.jq; import static org.testng.reporters.jq.BasePanel.C; import static org.testng.reporters.jq.BasePanel.D; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import org.testng.IReporter; import org.testng.ISuite; import org.testng.internal.Utils; import org.testng.log4testng.Logger; import org.testng.reporters.Files; import org.testng.reporters.XMLStringBuffer; import org.testng.xml.XmlSuite; public class Main implements IReporter { private static final String TESTNG_RESOURCE_PREFIX = "/org/testng/"; private static final String[] RESOURCES = new String[] { "jquery.min.js", "testng-reports.css", "testng-reports.js", "testng-reports1.css", "testng-reports2.js", "passed.png", "failed.png", "skipped.png", "navigator-bullet.png", "bullet_point.png", "collapseall.gif" }; public static final String REPORT_HEADER_FILE = "header"; @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { Model m_model = new Model(suites); XMLStringBuffer xsb = new XMLStringBuffer(" "); // Generate the top banner new BannerPanel(m_model).generate(xsb); // All the panels selectable from the navigator List panels = Arrays.asList( new TestNgXmlPanel(m_model), new TestPanel(m_model), new GroupPanel(m_model), new TimesPanel(m_model), new ReporterPanel(m_model), new IgnoredMethodsPanel(m_model), new ChronologicalPanel(m_model)); // Generate the navigator on the left hand side new NavigatorPanel(m_model, panels).generate(xsb); xsb.push(D, C, "wrapper"); xsb.push(D, "class", "main-panel-root"); // // Generate the main suite panel // new SuitePanel(m_model).generate(xsb); // Generate all the navigator panels for (INavigatorPanel panel : panels) { panel.generate(xsb); } xsb.pop(D); // main-panel-root xsb.pop(D); // wrapper xsb.addString(" \n"); xsb.addString("\n"); xsb.addString("\n"); String all; try { try (InputStream header = getClass().getResourceAsStream(TESTNG_RESOURCE_PREFIX + REPORT_HEADER_FILE)) { if (header == null) { throw new RuntimeException("Couldn't find resource header"); } for (String fileName : RESOURCES) { try (InputStream is = load(fileName)) { if (is == null) { throw new AssertionError("Couldn't find resource: " + fileName); } Files.copyFile(is, new File(outputDirectory, fileName)); } } all = Files.readFile(header); Utils.writeUtf8File(outputDirectory, "index.html", xsb, all); } } catch (IOException e) { Logger.getLogger(Main.class).error(e.getMessage(), e); } } private InputStream load(String fileName) { String path; if (fileName.equals("jquery.min.js")) { path = "/META-INF/resources/webjars/jquery/3.5.1/jquery.min.js"; } else { path = Main.TESTNG_RESOURCE_PREFIX + fileName; } return getClass().getResourceAsStream(path); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/Model.java000066400000000000000000000156401475274123300304120ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.collections.ListMultiMap; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.collections.SetMultiMap; import org.testng.internal.Utils; public class Model { private ListMultiMap m_model = Maps.newListMultiMap(); private List m_suites = null; private Map m_testTags = Maps.newHashMap(); private Map m_testResultMap = Maps.newHashMap(); private Map m_failedResultsByClass = Maps.newHashMap(); private Map m_skippedResultsByClass = Maps.newHashMap(); private Map m_passedResultsByClass = Maps.newHashMap(); private List m_allFailedResults = Lists.newArrayList(); // Each suite is mapped to failed.png, skipped.png or nothing (which means passed.png) private Map m_statusBySuiteName = Maps.newHashMap(); private SetMultiMap m_groupsBySuiteName = Maps.newSetMultiMap(); private SetMultiMap m_methodsByGroup = Maps.newSetMultiMap(); public Model(List suites) { m_suites = suites; init(); } public List getSuites() { return m_suites; } private void init() { int testCounter = 0; for (ISuite suite : m_suites) { List passed = Lists.newArrayList(); List failed = Lists.newArrayList(); List skipped = Lists.newArrayList(); Map suiteResults = suite.getResults(); for (ISuiteResult sr : suiteResults.values()) { ITestContext context = sr.getTestContext(); m_testTags.put(context.getName(), "test-" + testCounter++); failed.addAll(context.getFailedTests().getAllResults()); skipped.addAll(context.getSkippedTests().getAllResults()); passed.addAll(context.getPassedTests().getAllResults()); IResultMap[] map = new IResultMap[] { context.getFailedTests(), context.getSkippedTests(), context.getPassedTests() }; for (IResultMap m : map) { for (ITestResult tr : m.getAllResults()) { m_testResultMap.put(tr, getTestResultName(tr)); } } } // Process them in the order passed, skipped and failed, so that the failed // icon overrides all the others and the skipped icon overrides passed. // Passed { ResultsByClass rbc = new ResultsByClass(); for (ITestResult tr : passed) { rbc.addResult(tr.getTestClass().getRealClass(), tr); updateGroups(suite, tr); } m_passedResultsByClass.put(suite, rbc); } // Skipped { ResultsByClass rbc = new ResultsByClass(); for (ITestResult tr : skipped) { m_statusBySuiteName.put(suite.getName(), "skipped"); rbc.addResult(tr.getTestClass().getRealClass(), tr); updateGroups(suite, tr); } m_skippedResultsByClass.put(suite, rbc); } // Failed { ResultsByClass rbc = new ResultsByClass(); for (ITestResult tr : failed) { m_statusBySuiteName.put(suite.getName(), "failed"); rbc.addResult(tr.getTestClass().getRealClass(), tr); m_allFailedResults.add(tr); updateGroups(suite, tr); } m_failedResultsByClass.put(suite, rbc); } m_model.putAll(suite, failed); m_model.putAll(suite, skipped); m_model.putAll(suite, passed); } } private void updateGroups(ISuite suite, ITestResult tr) { String[] groups = tr.getMethod().getGroups(); m_groupsBySuiteName.putAll(suite.getName(), Arrays.asList(groups)); for (String group : groups) { m_methodsByGroup.put(group, tr.getMethod().getMethodName()); } } public ResultsByClass getFailedResultsByClass(ISuite suite) { return m_failedResultsByClass.get(suite); } public ResultsByClass getSkippedResultsByClass(ISuite suite) { return m_skippedResultsByClass.get(suite); } public ResultsByClass getPassedResultsByClass(ISuite suite) { return m_passedResultsByClass.get(suite); } public String getTag(ITestResult tr) { return m_testResultMap.get(tr); } public List getTestResults(ISuite suite) { return m_model.get(suite); } private static String getMethodName(String name) { if (name == null) { return ""; } return name; } public static String getTestResultName(ITestResult tr) { StringBuilder result = new StringBuilder(getMethodName(tr.getMethod().getMethodName())); Object[] parameters = tr.getParameters(); if (parameters.length > 0) { result.append("("); StringBuilder p = new StringBuilder(); for (int i = 0; i < parameters.length; i++) { if (i > 0) p.append(", "); p.append(Utils.toString(parameters[i])); } if (p.length() > 100) { String s = p.toString().substring(0, 100); s = s + "..."; result.append(s); } else { result.append(p.toString()); } result.append(")"); } return result.toString(); } public List getAllFailedResults() { return m_allFailedResults; } public static String getImage(String tagClass) { return tagClass + ".png"; } public String getStatusForSuite(String suiteName) { String result = m_statusBySuiteName.get(suiteName); return result != null ? result : "passed"; } public List getGroups(String name) { List result = Lists.newArrayList(m_groupsBySuiteName.get(name)); Collections.sort(result); return result; } public List getMethodsInGroup(String groupName) { List result = Lists.newArrayList(m_methodsByGroup.get(groupName)); Collections.sort(result); return result; } public List getAllTestResults(ISuite suite) { return getAllTestResults(suite, true /* tests only */); } public List getAllTestResults(ISuite suite, boolean testsOnly) { List result = Lists.newArrayList(); for (ISuiteResult sr : suite.getResults().values()) { result.addAll(sr.getTestContext().getPassedTests().getAllResults()); result.addAll(sr.getTestContext().getFailedTests().getAllResults()); result.addAll(sr.getTestContext().getSkippedTests().getAllResults()); if (!testsOnly) { result.addAll(sr.getTestContext().getPassedConfigurations().getAllResults()); result.addAll(sr.getTestContext().getFailedConfigurations().getAllResults()); result.addAll(sr.getTestContext().getSkippedConfigurations().getAllResults()); } } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/NavigatorPanel.java000066400000000000000000000204741475274123300322650ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.List; import java.util.Map; import java.util.function.Predicate; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.reporters.XMLStringBuffer; public class NavigatorPanel extends BasePanel { private List m_panels; public NavigatorPanel(Model model, List panels) { super(model); m_panels = panels; } @Override public void generate(XMLStringBuffer main) { main.push(D, C, "navigator-root"); main.push(D, C, "navigator-suite-header"); main.addRequired(S, "All suites"); main.push("a", C, "collapse-all-link", "href", "#", "title", "Collapse/expand all the suites"); main.push("img", "src", "collapseall.gif", C, "collapse-all-icon"); main.pop("img"); main.pop("a"); main.pop(D); for (ISuite suite : getSuites()) { if (suite.getResults().size() == 0) { continue; } String suiteName = "suite-" + suiteToTag(suite); XMLStringBuffer header = new XMLStringBuffer(main.getCurrentIndent()); Map results = suite.getResults(); int failed = 0; int skipped = 0; int passed = 0; for (ISuiteResult result : results.values()) { ITestContext context = result.getTestContext(); failed += context.getFailedTests().size(); skipped += context.getSkippedTests().size(); passed += context.getPassedTests().size(); } // Suite name in big font header.push(D, C, "suite"); header.push(D, C, "rounded-window"); // Extra div so the highlighting logic will only highlight this line and not // the entire container header.push(D, C, "suite-header light-rounded-window-top"); header.push("a", "href", "#", "panel-name", suiteName, C, "navigator-link"); header.addOptional( S, suite.getName(), C, "suite-name border-" + getModel().getStatusForSuite(suite.getName())); header.pop("a"); header.pop(D); header.push(D, C, "navigator-suite-content"); generateInfo(header, suite); generateResult(header, failed, skipped, passed, suite, suiteName); header.pop("ul"); header.pop(D); // suite-section-content header.pop(D); // suite-header header.pop(D); // suite header.pop(D); // result-section header.pop(D); // navigator-suite-content main.addString(header.toXML()); } main.pop(D); } private void generateResult( XMLStringBuffer header, int failed, int skipped, int passed, ISuite suite, String suiteName) { // // Results // header.push(D, C, "result-section"); header.push(D, C, "suite-section-title"); header.addRequired(S, "Results"); header.pop(D); // Method stats int total = failed + skipped + passed; String stats = String.format( "%s, %s %s %s", pluralize(total, "method"), maybe(failed, "failed", ", "), maybe(skipped, "skipped", ", "), maybe(passed, "passed", "")); header.push(D, C, "suite-section-content"); header.push("ul"); header.push("li"); header.addOptional(S, stats, C, "method-stats"); header.pop("li"); generateMethodList( "Failed methods", new ResultsByStatus(suite, "failed", ITestResult.FAILURE), suiteName, header); Predicate skip = result -> !result.wasRetried(); IResultProvider provider = new ResultsByStatus(suite, "skipped", ITestResult.SKIP, skip); generateMethodList("Skipped methods", provider, suiteName, header); provider = new ResultsByStatus(suite, "skipped", ITestResult.SKIP, ITestResult::wasRetried); generateMethodList("Retried methods", provider, suiteName, header); provider = new ResultsByStatus(suite, "passed", ITestResult.SUCCESS); generateMethodList("Passed methods", provider, suiteName, header); } private void generateInfo(XMLStringBuffer header, ISuite suite) { // // Info // header.push(D, C, "suite-section-title"); header.addRequired(S, "Info"); header.pop(D); header.push(D, C, "suite-section-content"); header.push("ul"); // All the panels for (INavigatorPanel panel : m_panels) { addLinkTo(header, panel, suite); } header.pop("ul"); header.pop(D); // suite-section-content } private void addLinkTo(XMLStringBuffer header, INavigatorPanel panel, ISuite suite) { String text = panel.getNavigatorLink(suite); header.push("li"); header.push("a", "href", "#", "panel-name", panel.getPanelName(suite), C, "navigator-link "); String className = panel.getClassName(); if (className != null) { header.addOptional(S, text, C, className); } else { header.addOptional(S, text); } header.pop("a"); header.pop("li"); } private static String maybe(int count, String s, String sep) { return count > 0 ? count + " " + s + sep : ""; } private List getMethodsByStatus( ISuite suite, int status, Predicate condition) { List result = Lists.newArrayList(); List testResults = getModel().getTestResults(suite); for (ITestResult tr : testResults) { if (tr.getStatus() == status && condition.test(tr)) { result.add(tr); } } result.sort(ResultsByClass.METHOD_NAME_COMPARATOR); return result; } private interface IResultProvider { List getResults(); String getType(); } private abstract static class BaseResultProvider implements IResultProvider { protected ISuite m_suite; protected String m_type; public BaseResultProvider(ISuite suite, String type) { m_suite = suite; m_type = type; } @Override public String getType() { return m_type; } } private class ResultsByStatus extends BaseResultProvider { private final int m_status; private final Predicate condition; public ResultsByStatus(ISuite suite, String type, int status) { this(suite, type, status, (result) -> true); } public ResultsByStatus( ISuite suite, String type, int m_status, Predicate condition) { super(suite, type); this.m_status = m_status; this.condition = condition; } @Override public List getResults() { return getMethodsByStatus(m_suite, m_status, condition); } } private void generateMethodList( String name, IResultProvider provider, String suiteName, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); String type = provider.getType(); String image = Model.getImage(type); xsb.push("li"); // The methods themselves xsb.addRequired(S, name, C, "method-list-title " + type); // The mark up to show the (hide)/(show) links xsb.push(S, C, "show-or-hide-methods " + type); xsb.addRequired( "a", " (hide)", "href", "#", C, "hide-methods " + type + " " + suiteName, "panel-name", suiteName); xsb.addRequired( "a", " (show)", "href", "#", C, "show-methods " + type + " " + suiteName, "panel-name", suiteName); xsb.pop(S); // List of methods xsb.push(D, C, "method-list-content " + type + " " + suiteName); int count = 0; List testResults = provider.getResults(); if (testResults != null) { testResults.sort(ResultsByClass.METHOD_NAME_COMPARATOR); for (ITestResult tr : testResults) { String testName = Model.getTestResultName(tr); xsb.push(S); xsb.addEmptyElement("img", "src", image, "width", "3%"); xsb.addRequired( "a", testName, "href", "#", "hash-for-method", getModel().getTag(tr), "panel-name", suiteName, "title", tr.getTestClass().getName(), C, "method navigator-link"); xsb.pop(S); xsb.addEmptyElement("br"); count++; } } xsb.pop(D); xsb.pop("li"); if (count > 0) { main.addString(xsb.toXML()); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/ReporterPanel.java000066400000000000000000000024521475274123300321310ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.List; import org.testng.ISuite; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.reporters.XMLStringBuffer; /** Display the reporter output for each test result. */ public class ReporterPanel extends BaseMultiSuitePanel { public ReporterPanel(Model model) { super(model); } @Override public String getPrefix() { return "reporter-"; } @Override public String getHeader(ISuite suite) { return "Reporter output for " + suite.getName(); } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); for (ITestResult tr : getModel().getAllTestResults(suite)) { List lines = Reporter.getOutput(tr); if (!lines.isEmpty()) { xsb.push(D, C, "reporter-method-div"); xsb.addRequired(S, Model.getTestResultName(tr), C, "reporter-method-name"); xsb.push(D, C, "reporter-method-output-div"); for (String output : lines) { xsb.addRequired(S, output, C, "reporter-method-output"); } xsb.pop(D); xsb.pop(D); } } return xsb.toXML(); } @Override public String getNavigatorLink(ISuite suite) { return "Reporter output"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/ResultsByClass.java000066400000000000000000000017621475274123300322740ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.testng.ITestResult; import org.testng.collections.ListMultiMap; import org.testng.collections.Maps; public class ResultsByClass { public static final Comparator METHOD_NAME_COMPARATOR = new Comparator() { @Override public int compare(ITestResult arg0, ITestResult arg1) { return arg0.getMethod().getMethodName().compareTo(arg1.getMethod().getMethodName()); } }; private ListMultiMap, ITestResult> m_results = Maps.newListMultiMap(); public void addResult(Class c, ITestResult tr) { m_results.put(c, tr); } public List getResults(Class c) { List result = m_results.get(c); Collections.sort(result, METHOD_NAME_COMPARATOR); return result; } public Set> getClasses() { return m_results.keySet(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/SuitePanel.java000066400000000000000000000061371475274123300314240ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.List; import org.testng.ISuite; import org.testng.ITestResult; import org.testng.internal.Utils; import org.testng.reporters.XMLStringBuffer; import org.testng.util.Strings; public class SuitePanel extends BasePanel { private static final String PASSED = "passed"; private static final String SKIPPED = "skipped"; private static final String FAILED = "failed"; public SuitePanel(Model model) { super(model); } @Override public void generate(XMLStringBuffer xsb) { for (ISuite suite : getSuites()) { generateSuitePanel(suite, xsb); } } private void generateSuitePanel(ISuite suite, XMLStringBuffer xsb) { String divName = suiteToTag(suite); xsb.push(D, C, "panel " + divName, "panel-name", "suite-" + divName); String[] statuses = new String[] {FAILED, SKIPPED, PASSED}; ResultsByClass[] results = new ResultsByClass[] { getModel().getFailedResultsByClass(suite), getModel().getSkippedResultsByClass(suite), getModel().getPassedResultsByClass(suite), }; for (int i = 0; i < results.length; i++) { ResultsByClass byClass = results[i]; for (Class c : byClass.getClasses()) { generateClassPanel(c, byClass.getResults(c), xsb, statuses[i], suite); } } xsb.pop(D); } private void generateClassPanel( Class c, List results, XMLStringBuffer xsb, String status, ISuite suite) { xsb.push(D, C, "suite-" + suiteToTag(suite) + "-class-" + status); xsb.push(D, C, "main-panel-header rounded-window-top"); // Passed/failed icon xsb.addEmptyElement("img", "src", Model.getImage(status)); xsb.addOptional(S, c.getName(), C, "class-name"); xsb.pop(D); xsb.push(D, C, "main-panel-content rounded-window-bottom"); for (ITestResult tr : results) { generateMethod(tr, xsb); } xsb.pop(D); xsb.pop(D); } private void generateMethod(ITestResult tr, XMLStringBuffer xsb) { xsb.push(D, C, "method"); xsb.push(D, C, "method-content"); xsb.push("a", "name", Model.getTestResultName(tr)); xsb.pop("a"); xsb.addOptional(S, tr.getMethod().getMethodName(), C, "method-name"); // Parameters? if (tr.getParameters().length > 0) { StringBuilder sb = new StringBuilder(); boolean first = true; for (Object p : tr.getParameters()) { if (!first) sb.append(", "); first = false; sb.append(Utils.toString(p)); } xsb.addOptional(S, "(" + sb.toString() + ")", C, "parameters"); } // Exception? if (tr.getStatus() != ITestResult.SUCCESS && tr.getThrowable() != null) { StringBuilder stackTrace = new StringBuilder(); stackTrace.append(Utils.shortStackTrace(tr.getThrowable(), true)); xsb.addOptional(D, stackTrace.toString() + "\n", C, "stack-trace"); } // Description? String description = tr.getMethod().getDescription(); if (!Strings.isNullOrEmpty(description)) { xsb.push("em"); xsb.addString("(" + description + ")"); xsb.pop("em"); } xsb.pop(D); xsb.pop(D); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/TestNgXmlPanel.java000066400000000000000000000016751475274123300322220ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.ISuite; import org.testng.internal.Utils; import org.testng.reporters.XMLStringBuffer; public class TestNgXmlPanel extends BaseMultiSuitePanel { public TestNgXmlPanel(Model model) { super(model); } @Override public String getPrefix() { return "test-xml-"; } @Override public String getHeader(ISuite suite) { return suite.getXmlSuite().getFileName(); } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); xsb.push("pre"); xsb.addString(Utils.escapeHtml(suite.getXmlSuite().toXml())); xsb.pop("pre"); return xsb.toXML(); } @Override public String getNavigatorLink(ISuite suite) { String fqName = suite.getXmlSuite().getFileName(); if (fqName == null) fqName = "/[unset file name]"; return fqName.substring(fqName.lastIndexOf("/") + 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/TestPanel.java000066400000000000000000000022301475274123300312400ustar00rootroot00000000000000package org.testng.reporters.jq; import org.testng.ISuite; import org.testng.reporters.XMLStringBuffer; import org.testng.xml.XmlTest; /** Display the list of <test> tags. */ public class TestPanel extends BaseMultiSuitePanel { public TestPanel(Model model) { super(model); } @Override public String getPrefix() { return "testlist-"; } @Override public String getHeader(ISuite suite) { return "Tests for " + suite.getName(); } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); xsb.push("ul"); for (XmlTest test : suite.getXmlSuite().getTests()) { xsb.push("li"); int count = test.getXmlClasses().size(); String name = test.getName() + " (" + pluralize(count, "class") + ")"; xsb.addRequired(S, name, C, "test-name"); xsb.pop("li"); } xsb.pop("ul"); return xsb.toXML(); } @Override public String getNavigatorLink(ISuite suite) { return pluralize(suite.getXmlSuite().getTests().size(), "test"); } @Override public String getClassName() { return "test-stats"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/jq/TimesPanel.java000066400000000000000000000113011475274123300314010ustar00rootroot00000000000000package org.testng.reporters.jq; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.collections.Maps; import org.testng.reporters.XMLStringBuffer; import org.testng.xml.XmlSuite; public class TimesPanel extends BaseMultiSuitePanel { private Map m_totalTime = Maps.newHashMap(); public TimesPanel(Model model) { super(model); } @Override public String getPrefix() { return "times-"; } @Override public String getHeader(ISuite suite) { return "Times for " + suite.getName(); } private String js(ISuite suite) { String functionName = "tableData_" + suiteToTag(suite); StringBuilder result = new StringBuilder( "suiteTableInitFunctions.push('" + functionName + "');\n" + "function " + functionName + "() {\n" + "var data = new google.visualization.DataTable();\n" + "data.addColumn('number', 'Number');\n" + "data.addColumn('string', 'Method');\n" + "data.addColumn('string', 'Class');\n" + "data.addColumn('number', 'Time (ms)');\n"); List allTestResults = getModel().getAllTestResults(suite); result.append("data.addRows(").append(allTestResults.size()).append(");\n"); allTestResults.sort((o1, o2) -> (int) (time(o2) - time(o1))); int index = 0; for (ITestResult tr : allTestResults) { ITestNGMethod m = tr.getMethod(); long time = tr.getEndMillis() - tr.getStartMillis(); result .append("data.setCell(") .append(index) .append(", 0, ") .append(index) .append(")\n") .append("data.setCell(") .append(index) .append(", 1, '") .append(m.getMethodName()) .append("')\n") .append("data.setCell(") .append(index) .append(", 2, '") .append(m.getTestClass().getName()) .append("')\n") .append("data.setCell(") .append(index) .append(", 3, ") .append(time) .append(");\n"); Long total = m_totalTime.get(suite.getName()); if (total == null) { total = 0L; } m_totalTime.put(suite.getName(), total + time); index++; } result .append("window.suiteTableData['") .append(suiteToTag(suite)) .append("']") .append("= { tableData: data, tableDiv: 'times-div-") .append(suiteToTag(suite)) .append("'}\n") .append("return data;\n") .append("}\n"); return result.toString(); } @Override public String getContent(ISuite suite, XMLStringBuffer main) { XMLStringBuffer xsb = new XMLStringBuffer(main.getCurrentIndent()); xsb.push(D, C, "times-div"); xsb.push("script", "type", "text/javascript"); xsb.addString(js(suite)); xsb.pop("script"); long time = maxTime(suite); xsb.addRequired( S, String.format("Total running time: %s", prettyDuration(time)), C, "suite-total-time"); xsb.push(D, "id", "times-div-" + suiteToTag(suite)); xsb.pop(D); xsb.pop(D); return xsb.toXML(); } private String prettyDuration(long totalTime) { String result; if (totalTime < 1000) { result = totalTime + " ms"; } else if (totalTime < 1000 * 60) { result = (totalTime / 1000) + " seconds"; } else if (totalTime < 1000 * 60 * 60) { result = (totalTime / 1000 / 60) + " minutes"; } else { result = (totalTime / 1000 / 60 / 60) + " hours"; } return result; } @Override public String getNavigatorLink(ISuite suite) { return "Times"; } private static long time(ITestResult o1) { return o1.getEndMillis() - o1.getStartMillis(); } private long maxTime(ISuite suite) { boolean testsInParallel = XmlSuite.ParallelMode.TESTS.equals(suite.getXmlSuite().getParallel()); Long result = m_totalTime.get(suite.getName()); // there are no running tests in the suite if (result == null) { return 0L; } if (!testsInParallel) { return result; } Optional maxValue = suite.getResults().values().stream() .map(ISuiteResult::getTestContext) .max(Comparator.comparing(TimesPanel::time)); if (maxValue.isPresent()) { return time(maxValue.get()); } return result; } private static Long time(ITestContext ctx) { return ctx.getEndDate().getTime() - ctx.getStartDate().getTime(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/util/000077500000000000000000000000001475274123300270445ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/reporters/util/StackTraceTools.java000066400000000000000000000032041475274123300327530ustar00rootroot00000000000000package org.testng.reporters.util; import org.testng.ITestNGMethod; /** * Functionality to allow tools to analyse and subdivide stack traces. * * @author Paul Mendelson * @since 5.3 * @version $Revision: 173 $ */ public final class StackTraceTools { private StackTraceTools() { // defeat instantiation. } /** * @param stack The stack trace * @param method The test method * @return topmost position of the test method in the stack, or top of stack if method * is not in it. */ public static int getTestRoot(StackTraceElement[] stack, ITestNGMethod method) { if (stack == null || method == null) { return -1; } String cname = method.getTestClass().getName(); for (int x = stack.length - 1; x >= 0; x--) { if (cname.equals(stack[x].getClassName()) && method.getMethodName().equals(stack[x].getMethodName())) { return x; } } return stack.length - 1; } /** * @param stack The stacktrace * @param method The test method * @return topmost position of the test method in the stack, or top of stack if method * is not in it. */ public static StackTraceElement[] getTestNGInstrastructure( StackTraceElement[] stack, ITestNGMethod method) { if (method == null || stack == null) { return new StackTraceElement[] {}; } int slot = StackTraceTools.getTestRoot(stack, method); if (slot >= 0) { StackTraceElement[] r = new StackTraceElement[stack.length - slot]; System.arraycopy(stack, slot, r, 0, r.length); return r; } else { return new StackTraceElement[0]; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/thread/000077500000000000000000000000001475274123300253115ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/thread/IExecutorFactory.java000066400000000000000000000065331475274123300314220ustar00rootroot00000000000000package org.testng.thread; import java.util.Comparator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.testng.IDynamicGraph; import org.testng.ISuite; import org.testng.ITestNGMethod; /** * Represents the capabilities to be possessed by any implementation that can be plugged into TestNG * to execute nodes from a {@link org.testng.IDynamicGraph} object. */ public interface IExecutorFactory { /** * @param name - The name to be used as a prefix for all created threads. * @param graph - A {@link org.testng.IDynamicGraph} object that represents the graph of methods * and the hierarchy of execution. * @param factory - A {@link IThreadWorkerFactory} factory to create threads. * @param corePoolSize the number of threads to keep in the pool, even if they are idle, unless * {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the pool * @param keepAliveTime when the number of threads is greater than the core, this is the maximum * time that excess idle threads will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are executed. This queue will * hold only the {@code Runnable} tasks submitted by the {@code execute} method. * @param comparator - A {@link Comparator} to order nodes internally. * @return - A new {@link ITestNGThreadPoolExecutor} that is capable of running suites in * parallel. */ ITestNGThreadPoolExecutor newSuiteExecutor( String name, IDynamicGraph graph, IThreadWorkerFactory factory, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, Comparator comparator); /** * @param name - The name to be used as a prefix for all created threads. * @param graph - A {@link IDynamicGraph} object that represents the graph of methods and the * hierarchy of execution. * @param factory - A {@link IThreadWorkerFactory} factory to create threads. * @param corePoolSize the number of threads to keep in the pool, even if they are idle, unless * {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the pool * @param keepAliveTime when the number of threads is greater than the core, this is the maximum * time that excess idle threads will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are executed. This queue will * hold only the {@code Runnable} tasks submitted by the {@code execute} method. * @param comparator - A {@link Comparator} to order nodes internally. * @return - A new {@link ITestNGThreadPoolExecutor} that is capable of running test methods in * parallel. */ ITestNGThreadPoolExecutor newTestMethodExecutor( String name, IDynamicGraph graph, IThreadWorkerFactory factory, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, Comparator comparator); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/thread/ITestNGThreadPoolExecutor.java000066400000000000000000000005011475274123300331260ustar00rootroot00000000000000package org.testng.thread; import java.util.concurrent.ExecutorService; /** Represents the capabilities of a TestNG specific {@link ExecutorService} */ public interface ITestNGThreadPoolExecutor extends ExecutorService { /** Helps kick start the execution and is the point of entry for execution. */ void run(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/thread/IThreadWorkerFactory.java000066400000000000000000000007361475274123300322240ustar00rootroot00000000000000package org.testng.thread; import java.util.List; /** A factory that creates workers used by {@code GraphThreadPoolExecutor} */ public interface IThreadWorkerFactory { /** * Creates {@code IWorker} for specified set of tasks. It is not necessary that number of workers * returned be same as number of tasks entered. * * @param freeNodes tasks that need to be executed * @return list of workers */ List> createWorkers(List freeNodes); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/thread/IWorker.java000066400000000000000000000012651475274123300275420ustar00rootroot00000000000000package org.testng.thread; import java.util.List; /** A runnable object that is used by {@code GraphThreadPoolExecutor} to execute tasks */ public interface IWorker extends Runnable, Comparable> { /** @return list of tasks this worker is working on. */ List getTasks(); /** @return the maximum time allowed for the worker to complete the task. */ long getTimeOut(); /** @return the priority of this task. */ int getPriority(); default long getCurrentThreadId() { return -1; } default void setThreadIdToRunOn(long threadIdToRunOn) {} default long getThreadIdToRunOn() { return -1; } default boolean completed() { return true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/util/000077500000000000000000000000001475274123300250175ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/util/RetryAnalyzerCount.java000066400000000000000000000023641475274123300315130ustar00rootroot00000000000000package org.testng.util; import java.util.concurrent.atomic.AtomicInteger; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; /** * An implementation of IRetryAnalyzer that allows you to specify the maximum number of times you * want your test to be retried. * * @author tocman@gmail.com (Jeremie Lenfant-Engelmann) */ public abstract class RetryAnalyzerCount implements IRetryAnalyzer { // Default retry once. AtomicInteger count = new AtomicInteger(1); /** @param count the max number of time the method needs to be retried. */ protected void setCount(int count) { this.count.set(count); } /** @return the current counter value */ protected int getCount() { return this.count.get(); } /** * Retries the test if count is not 0. * * @param result The result of the test. */ @Override public boolean retry(ITestResult result) { if (count.getAndDecrement() > 0) { return retryMethod(result); } return false; } /** * The method implemented by the class that test if the test must be retried or not. * * @param result The result of the test. * @return true if the test must be retried, false otherwise. */ public abstract boolean retryMethod(ITestResult result); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/util/TimeUtils.java000066400000000000000000000033221475274123300276010ustar00rootroot00000000000000package org.testng.util; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.util.TimeZone; import org.testng.internal.RuntimeBehavior; import org.testng.internal.Utils; /** A Utility class that deals with time. */ public final class TimeUtils { private TimeUtils() {} /** * @param timeInMilliSeconds - The time in milliseconds * @param format - A format that can be used by {@link SimpleDateFormat} * @return - A formatted string representation of the time in the timezone as obtained via {@link * RuntimeBehavior#getTimeZone()} */ public static String formatTimeInLocalOrSpecifiedTimeZone( long timeInMilliSeconds, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); TimeZone timeZone = RuntimeBehavior.getTimeZone(); sdf.setTimeZone(timeZone); return sdf.format(timeInMilliSeconds); } /** A sample task to be executed. */ @FunctionalInterface public interface Task { /** The actual work to be executed. */ void execute(); } /** * Helper method that can be used to compute the time. * * @param msg - A user friendly message to be shown in the logs. * @param task - A {@link Task} that represents the task to be executed. */ public static void computeAndShowTime(String msg, Task task) { Instant start = Instant.now(); try { task.execute(); } finally { Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toMillis(); String text = msg + " took " + timeElapsed + " ms."; Utils.log(text); if (timeElapsed > 20000) { Utils.log("[WARNING] Probable slow call ( > 20 seconds): " + text); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/000077500000000000000000000000001475274123300246425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/IFileParser.java000066400000000000000000000003261475274123300276530ustar00rootroot00000000000000package org.testng.xml; import java.io.InputStream; import org.testng.TestNGException; public interface IFileParser { T parse(String filePath, InputStream is, boolean loadClasses) throws TestNGException; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/IPostProcessor.java000066400000000000000000000003521475274123300304430ustar00rootroot00000000000000package org.testng.xml; import java.util.Collection; /** Used by Parser to perform changes on an XML suite after it's been parsed. */ public interface IPostProcessor { Collection process(Collection suites); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/ISuiteParser.java000066400000000000000000000001751475274123300300670ustar00rootroot00000000000000package org.testng.xml; public interface ISuiteParser extends IFileParser { boolean accept(String fileName); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/LaunchSuite.java000066400000000000000000000275641475274123300277470ustar00rootroot00000000000000package org.testng.xml; import static org.testng.internal.Utils.isStringNotBlank; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import org.testng.collections.Lists; import org.testng.log4testng.Logger; import org.testng.reporters.XMLStringBuffer; import org.testng.xml.internal.Parser; /** * This class is used to encapsulate a launch. Various synthetic XML files are created depending on * whether the user is trying to launch a suite, a class, a method, etc... */ public abstract class LaunchSuite { /** This class's log4testng Logger. */ private static final Logger LOGGER = Logger.getLogger(LaunchSuite.class); protected boolean m_temporary; /** * Constructs a LaunchSuite * * @param isTemp the temporary status */ protected LaunchSuite(boolean isTemp) { m_temporary = isTemp; } /** * Returns the temporary state. * * @return the temporary state. */ public boolean isTemporary() { return m_temporary; } /** * Saves the suite file in the specified directory and returns the file pathname. * * @param directory the directory where the suite file is to be saved. * @return the file pathname of the saved file. */ public abstract File save(File directory); public abstract XMLStringBuffer getSuiteBuffer(); /** ExistingSuite is a non-temporary LaunchSuite based on an existing file. */ public static class ExistingSuite extends LaunchSuite { /** The existing suite path (either relative to the project root or an absolute path) */ private File m_suitePath; /** * Constructs a ExistingSuite based on an existing file * * @param path the path to the existing Launch suite. */ public ExistingSuite(File path) { super(false); m_suitePath = path; } @Override public XMLStringBuffer getSuiteBuffer() { throw new UnsupportedOperationException("Not implemented yet"); } /** Trying to run an existing XML file: copy its content to where the plug-in expects it. */ @Override public File save(File directory) { return m_suitePath; } } /** CustomizedSuite TODO cquezel JavaDoc. */ private abstract static class CustomizedSuite extends LaunchSuite { protected String m_projectName; protected String m_suiteName; /** The annotation type. May be null. */ protected Map m_parameters; /** The string buffer used to write the XML file. */ private XMLStringBuffer m_suiteBuffer; /** * Constructs a CustomizedSuite TODO cquezel JavaDoc. * * @param projectName * @param className * @param parameters * @param annotationType */ private CustomizedSuite( final String projectName, final String className, final Map parameters, final String annotationType) { super(true); m_projectName = projectName; m_suiteName = className; m_parameters = parameters; } /** * TODO cquezel JavaDoc * * @return */ protected XMLStringBuffer createContentBuffer() { XMLStringBuffer suiteBuffer = new XMLStringBuffer(); suiteBuffer.setDocType("suite SYSTEM \"" + Parser.HTTPS_TESTNG_DTD_URL + "\""); Properties attrs = new Properties(); attrs.setProperty("parallel", XmlSuite.ParallelMode.NONE.toString()); attrs.setProperty("name", m_suiteName); suiteBuffer.push("suite", attrs); if (m_parameters != null) { for (Map.Entry entry : m_parameters.entrySet()) { Properties paramAttrs = new Properties(); paramAttrs.setProperty("name", entry.getKey()); paramAttrs.setProperty("value", entry.getValue()); suiteBuffer.push("parameter", paramAttrs); suiteBuffer.pop("parameter"); } } initContentBuffer(suiteBuffer); suiteBuffer.pop("suite"); return suiteBuffer; } /** * TODO cquezel JavaDoc * * @return */ @Override public XMLStringBuffer getSuiteBuffer() { if (null == m_suiteBuffer) { m_suiteBuffer = createContentBuffer(); } return m_suiteBuffer; } /** * Initializes the content of the xml string buffer. * * @param suiteBuffer the string buffer to initialize. */ protected abstract void initContentBuffer(XMLStringBuffer suiteBuffer); /** * {@inheritDoc} This implementation saves the suite to the "temp-testng-customsuite.xml" file * in the specified directory. */ @Override public File save(File directory) { final File suiteFile = new File(directory, "temp-testng-customsuite.xml"); saveSuiteContent(suiteFile, getSuiteBuffer()); return suiteFile; } /** * Saves the content of the string buffer to the specified file. * * @param file the file to write to. * @param content the content to write to the file. */ protected void saveSuiteContent(final File file, final XMLStringBuffer content) { try (OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"))) { fw.write(content.getStringBuffer().toString()); } catch (IOException ioe) { // TODO CQ is this normal to swallow exception here LOGGER.error("IO Exception", ioe); } } } /** A MethodsSuite is a suite made up of methods. */ static class MethodsSuite extends CustomizedSuite { protected Collection m_methodNames; protected String m_className; protected int m_logLevel; /** * Constructs a MethodsSuite TODO cquezel JavaDoc. * * @param projectName * @param className * @param methodNames * @param parameters * @param annotationType (may be null) * @param logLevel */ MethodsSuite( final String projectName, final String className, final Collection methodNames, final Map parameters, final String annotationType, final int logLevel) { super(projectName, className, parameters, annotationType); m_className = className; m_methodNames = methodNames; m_logLevel = logLevel; } /** {@inheritDoc} */ @Override protected void initContentBuffer(XMLStringBuffer suiteBuffer) { Properties testAttrs = new Properties(); testAttrs.setProperty("name", m_className); testAttrs.setProperty("verbose", String.valueOf(m_logLevel)); suiteBuffer.push("test", testAttrs); suiteBuffer.push("classes"); Properties classAttrs = new Properties(); classAttrs.setProperty("name", m_className); if ((null != m_methodNames) && (m_methodNames.size() > 0)) { suiteBuffer.push("class", classAttrs); suiteBuffer.push("methods"); for (Object methodName : m_methodNames) { Properties methodAttrs = new Properties(); methodAttrs.setProperty("name", (String) methodName); suiteBuffer.addEmptyElement("include", methodAttrs); } suiteBuffer.pop("methods"); suiteBuffer.pop("class"); } else { suiteBuffer.addEmptyElement("class", classAttrs); } suiteBuffer.pop("classes"); suiteBuffer.pop("test"); } } static class ClassesAndMethodsSuite extends CustomizedSuite { protected Map> m_classes; protected int m_logLevel; ClassesAndMethodsSuite( final String projectName, final Map> classes, final Map parameters, final String annotationType, final int logLevel) { super(projectName, "Custom suite", parameters, annotationType); m_classes = classes; m_logLevel = logLevel; } /** {@inheritDoc} */ @Override protected void initContentBuffer(XMLStringBuffer suiteBuffer) { Properties testAttrs = new Properties(); testAttrs.setProperty("name", m_projectName); testAttrs.setProperty("verbose", String.valueOf(m_logLevel)); suiteBuffer.push("test", testAttrs); suiteBuffer.push("classes"); for (Map.Entry> entry : m_classes.entrySet()) { Properties classAttrs = new Properties(); classAttrs.setProperty("name", entry.getKey()); Collection methodNames = sanitize(entry.getValue()); if ((null != methodNames) && (methodNames.size() > 0)) { suiteBuffer.push("class", classAttrs); suiteBuffer.push("methods"); for (String methodName : methodNames) { Properties methodAttrs = new Properties(); methodAttrs.setProperty("name", methodName); suiteBuffer.addEmptyElement("include", methodAttrs); } suiteBuffer.pop("methods"); suiteBuffer.pop("class"); } else { suiteBuffer.addEmptyElement("class", classAttrs); } } suiteBuffer.pop("classes"); suiteBuffer.pop("test"); } private Collection sanitize(Collection source) { if (null == source) { return null; } List result = Lists.newArrayList(); for (String name : source) { if (isStringNotBlank(name)) { result.add(name); } } return result; } } /** ClassListSuite TODO cquezel JavaDoc. */ static class ClassListSuite extends CustomizedSuite { protected Collection m_packageNames; protected Collection m_classNames; protected Collection m_groupNames; protected int m_logLevel; ClassListSuite( final String projectName, final Collection packageNames, final Collection classNames, final Collection groupNames, final Map parameters, final String annotationType, final int logLevel) { super(projectName, "Custom suite", parameters, annotationType); m_packageNames = packageNames; m_classNames = classNames; m_groupNames = groupNames; m_logLevel = logLevel; } /** {@inheritDoc} */ @Override protected void initContentBuffer(XMLStringBuffer suiteBuffer) { Properties testAttrs = new Properties(); testAttrs.setProperty("name", m_projectName); testAttrs.setProperty("verbose", String.valueOf(m_logLevel)); suiteBuffer.push("test", testAttrs); if (null != m_groupNames) { suiteBuffer.push("groups"); suiteBuffer.push("run"); for (String groupName : m_groupNames) { Properties includeAttrs = new Properties(); includeAttrs.setProperty("name", groupName); suiteBuffer.addEmptyElement("include", includeAttrs); } suiteBuffer.pop("run"); suiteBuffer.pop("groups"); } // packages belongs to suite according to the latest DTD if ((m_packageNames != null) && (m_packageNames.size() > 0)) { suiteBuffer.push("packages"); for (String packageName : m_packageNames) { Properties packageAttrs = new Properties(); packageAttrs.setProperty("name", packageName); suiteBuffer.addEmptyElement("package", packageAttrs); } suiteBuffer.pop("packages"); } if ((m_classNames != null) && (m_classNames.size() > 0)) { suiteBuffer.push("classes"); for (String className : m_classNames) { Properties classAttrs = new Properties(); classAttrs.setProperty("name", className); suiteBuffer.addEmptyElement("class", classAttrs); } suiteBuffer.pop("classes"); } suiteBuffer.pop("test"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/Parser.java000066400000000000000000000007301475274123300267410ustar00rootroot00000000000000package org.testng.xml; import java.io.InputStream; /** * Parser is a parser for a TestNG XML test suite file. * * @deprecated - This class stands deprecated as of TestNG 7.5.0. There are no * alternatives for this class. */ @SuppressWarnings("unused") @Deprecated public class Parser extends org.testng.xml.internal.Parser { public Parser(String path) { super(path); } public Parser(InputStream is) { super(is); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/SuiteGenerator.java000066400000000000000000000032731475274123300304520ustar00rootroot00000000000000package org.testng.xml; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.Map; /** * Factory to create custom suites. * * @author Hani Suleiman Date: Jul 25, 2005 Time: 1:12:18 PM */ public class SuiteGenerator { private static final Collection EMPTY_CLASS_LIST = Collections.emptyList(); public static LaunchSuite createProxiedXmlSuite(final File xmlSuitePath) { return new LaunchSuite.ExistingSuite(xmlSuitePath); } public static LaunchSuite createSuite( String projectName, Collection packageNames, Map> classAndMethodNames, Collection groupNames, Map parameters, String annotationType, int logLevel) { LaunchSuite result; Collection classes = classAndMethodNames != null ? classAndMethodNames.keySet() : EMPTY_CLASS_LIST; if ((null != groupNames) && !groupNames.isEmpty()) { // // Create a suite from groups // result = new LaunchSuite.ClassListSuite( projectName, packageNames, classes, groupNames, parameters, annotationType, logLevel); } else if (packageNames != null && packageNames.size() > 0) { // // Create a suite from packages // result = new LaunchSuite.ClassListSuite( projectName, packageNames, classes, groupNames, parameters, annotationType, logLevel); } else { // // Default suite creation // result = new LaunchSuite.ClassesAndMethodsSuite( projectName, classAndMethodNames, parameters, annotationType, logLevel); } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/SuiteXmlParser.java000066400000000000000000000014251475274123300304360ustar00rootroot00000000000000package org.testng.xml; import java.io.IOException; import java.io.InputStream; import org.testng.TestNGException; import org.testng.xml.internal.Parser; import org.xml.sax.SAXException; public class SuiteXmlParser extends XMLParser implements ISuiteParser { @Override public XmlSuite parse(String currentFile, InputStream inputStream, boolean loadClasses) { TestNGContentHandler contentHandler = new TestNGContentHandler(currentFile, loadClasses); try { parse(inputStream, contentHandler); return contentHandler.getSuite(); } catch (SAXException | IOException e) { throw new TestNGException(e); } } @Override public boolean accept(String fileName) { return Parser.hasFileScheme(fileName) && fileName.endsWith(".xml"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/java/org/testng/xml/TestNGContentHandler.java000066400000000000000000000656611475274123300315200ustar00rootroot00000000000000package org.testng.xml; import static org.testng.internal.Utils.isStringBlank; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Stack; import org.testng.ITestObjectFactory; import org.testng.TestNGException; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.internal.RuntimeBehavior; import org.testng.internal.Utils; import org.testng.log4testng.Logger; import org.testng.util.Strings; import org.testng.xml.internal.Parser; import org.xml.sax.Attributes; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * Suite definition parser utility. * * @author Cedric Beust * @author Alexandru Popescu */ // TODO move to internal public class TestNGContentHandler extends DefaultHandler { private XmlSuite m_currentSuite = null; private XmlTest m_currentTest = null; private XmlDefine m_currentDefine = null; private XmlRun m_currentRun = null; private List m_currentClasses = null; private int m_currentTestIndex = 0; private int m_currentClassIndex = 0; private int m_currentIncludeIndex = 0; private List m_currentPackages = null; private XmlPackage m_currentPackage = null; private final List m_suites = Lists.newArrayList(); private XmlGroups m_currentGroups = null; private Map m_currentTestParameters = null; private Map m_currentSuiteParameters = null; private Map m_currentClassParameters = null; private Include m_currentInclude; // Borrowed this implementation from this SO post : https://stackoverflow.com/a/29751441/679824 private final EntityResolver m_redirectionAwareResolver = (publicId, systemId) -> { URL url = new URL(systemId); InputStream stream = getClass().getResourceAsStream(url.getPath()); if (stream == null) { String msg = String.format( "Failed to read [%s] from CLASSPATH. " + "Attempting to read from [%s].", url.getPath(), systemId); Logger.getLogger(getClass()).warn(msg); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int status = conn.getResponseCode(); if ((status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) { String newUrl = conn.getHeaderField("Location"); conn = (HttpURLConnection) new URL(newUrl).openConnection(); } stream = conn.getInputStream(); } return new InputSource( Objects.requireNonNull(stream, "Failed to load DTD from " + systemId)); }; enum Location { SUITE, TEST, CLASS, INCLUDE, EXCLUDE } private final Stack m_locations = new Stack<>(); private XmlClass m_currentClass = null; private ArrayList m_currentIncludedMethods = null; private List m_currentExcludedMethods = null; private ArrayList m_currentSelectors = null; private XmlMethodSelector m_currentSelector = null; private String m_currentLanguage = null; private String m_currentExpression = null; private final List m_suiteFiles = Lists.newArrayList(); private boolean m_enabledTest; private List m_listeners; private final String m_fileName; private final boolean m_loadClasses; private boolean m_validate = false; private boolean m_hasWarn = false; public TestNGContentHandler(String fileName, boolean loadClasses) { m_fileName = fileName; m_loadClasses = loadClasses; } @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (skipConsideringSystemId(systemId)) { m_validate = true; InputStream is = loadDtdUsingClassLoader(); if (is != null) { return new InputSource(is); } // If the classpath loading of DTD fails, then we try to load it from "https" TestNG site. System.out.println( "WARNING: couldn't find in classpath " + systemId + "\n" + "Fetching it from " + Parser.HTTPS_TESTNG_DTD_URL); return m_redirectionAwareResolver.resolveEntity(publicId, Parser.HTTPS_TESTNG_DTD_URL); } // If we are here, then we don't know the host from which user is trying to load the dtd if (RuntimeBehavior.useSecuredUrlForDtd() && isUnsecuredUrl(systemId)) { throw new TestNGException(RuntimeBehavior.unsecuredUrlDocumentation()); } return m_redirectionAwareResolver.resolveEntity(publicId, systemId); } private static boolean skipConsideringSystemId(String systemId) { return Strings.isNullOrEmpty(systemId) || TestNGURLs.isDTDDomainInternallyKnownToTestNG(systemId) || isMalformedFileSystemBasedSystemId(systemId); } private static boolean isMalformedFileSystemBasedSystemId(String systemId) { try { URL url = new URL(URLDecoder.decode(systemId, StandardCharsets.UTF_8.name()).trim()); if (url.getProtocol().equals("file")) { File file = new File(url.getFile()); boolean isDirectory = file.isDirectory(); boolean fileExists = file.exists(); return isDirectory || !fileExists; } return false; } catch (MalformedURLException | UnsupportedEncodingException e) { return true; } } private static boolean isUnsecuredUrl(String str) { URI uri; try { uri = new URI(str); } catch (URISyntaxException e) { throw new RuntimeException(e); } // scheme is null for local uri return uri.getScheme() != null && uri.getScheme().equals("http"); } private InputStream loadDtdUsingClassLoader() { InputStream is = getClass().getClassLoader().getResourceAsStream(Parser.TESTNG_DTD); if (is != null) { return is; } return Thread.currentThread().getContextClassLoader().getResourceAsStream(Parser.TESTNG_DTD); } /** Parse */ private void xmlSuiteFile(boolean start, Attributes attributes) { if (start) { String path = attributes.getValue("path"); pushLocation(Location.SUITE); m_suiteFiles.add(path); } else { m_currentSuite.setSuiteFiles(m_suiteFiles); popLocation(); } } /** Parse */ private void xmlSuite(boolean start, Attributes attributes) { if (start) { pushLocation(Location.SUITE); String name = attributes.getValue("name"); if (isStringBlank(name)) { throw new TestNGException("The tag must define the name attribute"); } m_currentSuite = new XmlSuite(); m_currentSuite.setFileName(m_fileName); m_currentSuite.setName(name); m_currentSuiteParameters = Maps.newHashMap(); String verbose = attributes.getValue("verbose"); if (null != verbose) { m_currentSuite.setVerbose(Integer.parseInt(verbose)); } String jUnit = attributes.getValue("junit"); if (null != jUnit) { m_currentSuite.setJUnit(Boolean.valueOf(jUnit)); } String parallel = attributes.getValue("parallel"); if (parallel != null) { XmlSuite.ParallelMode mode = XmlSuite.ParallelMode.getValidParallel(parallel); if (mode != null) { m_currentSuite.setParallel(mode); } else { Utils.log( "Parser", 1, "[WARN] Unknown value of attribute 'parallel' at suite level: '" + parallel + "'."); } } String parentModule = attributes.getValue("parent-module"); if (parentModule != null) { m_currentSuite.setParentModule(parentModule); } String guiceStage = attributes.getValue("guice-stage"); if (guiceStage != null) { m_currentSuite.setGuiceStage(guiceStage); } XmlSuite.FailurePolicy configFailurePolicy = XmlSuite.FailurePolicy.getValidPolicy(attributes.getValue("configfailurepolicy")); if (null != configFailurePolicy) { m_currentSuite.setConfigFailurePolicy(configFailurePolicy); } String groupByInstances = attributes.getValue("group-by-instances"); if (groupByInstances != null) { m_currentSuite.setGroupByInstances(Boolean.parseBoolean(groupByInstances)); } String skip = attributes.getValue("skipfailedinvocationcounts"); if (skip != null) { m_currentSuite.setSkipFailedInvocationCounts(Boolean.parseBoolean(skip)); } String threadCount = attributes.getValue("thread-count"); if (null != threadCount) { m_currentSuite.setThreadCount(Integer.parseInt(threadCount)); } String dataProviderThreadCount = attributes.getValue("data-provider-thread-count"); if (null != dataProviderThreadCount) { m_currentSuite.setDataProviderThreadCount(Integer.parseInt(dataProviderThreadCount)); } String timeOut = attributes.getValue("time-out"); if (null != timeOut) { m_currentSuite.setTimeOut(timeOut); } String objectFactory = attributes.getValue("object-factory"); if (null != objectFactory && m_loadClasses) { try { m_currentSuite.setObjectFactoryClass( (Class) Class.forName(objectFactory)); } catch (Exception e) { Utils.log( "Parser", 1, "[ERROR] Unable to create custom object factory '" + objectFactory + "' :" + e); } } String preserveOrder = attributes.getValue("preserve-order"); if (preserveOrder != null) { m_currentSuite.setPreserveOrder(Boolean.valueOf(preserveOrder)); } String allowReturnValues = attributes.getValue("allow-return-values"); if (allowReturnValues != null) { m_currentSuite.setAllowReturnValues(Boolean.valueOf(allowReturnValues)); } } else { m_currentSuite.setParameters(m_currentSuiteParameters); m_suites.add(m_currentSuite); m_currentSuiteParameters = null; popLocation(); } } /** Parse */ private void xmlDefine(boolean start, Attributes attributes) { if (start) { String name = attributes.getValue("name"); m_currentDefine = new XmlDefine(); m_currentDefine.setName(name); } else { // define is only defined within the context of XmlGroups m_currentGroups.addDefine(m_currentDefine); m_currentDefine = null; } } /** Parse jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/navigator-bullet.png000066400000000000000000000005401475274123300311170ustar00rootroot00000000000000‰PNG  IHDR 7ÿgAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<òIDATxÚbüÿÿ?1€ D|ýxˈg‚h¼ ³}òÔ´Ÿ¿~*ÎÁªdõ—7ÿ›yüϨ‹ýóæÁÿ@~HÃLdàâãd`ce˜sx%ÃÑ‹gJÑWÈÌÂÌÀ/ÌË ¥.ÎpàÉ †Å;×Áœâ„¢ 8¸Ù¤”Å^s¼cXºØý ‚ÝÍŒŒŒ ¬ì¬ †*Ú Ö& ¡éX2121òk1h ª¬)âæWÛ‡¡P€ƒÁMÜ–A„Sp"[ Tô=xÖUväþóú(hJу{P…® Å ›"f$6® -v—QpAJÌIEND®B`‚jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/passed.png000066400000000000000000000017731475274123300271300ustar00rootroot00000000000000‰PNG  IHDR Vu\çiCCPICC Profilex…TßkÓPþÚe°á‹:g >h‘ndStCœ¶kWºÍZê6·!H›¦m\šÆ$í~°Ù‹o:Åwñ>ù Ùƒo{’ Æaø¬ˆ"Lö"³ž›4M'S¹÷»ßùî9'çä^ ùqZÓ/USOÅÂüÄäßò^C+ühM‹†J&G@Ó²yï³óÆltîoß«þcÕš• ð ¾”5Ä"áY i\ÔtàÖ‰ï15ÂÍLsX§ g8ocáŒ#–f45@š ÂÅB:K¸@8˜iàó ØÎä'&©’.‹<«ER/ådE² öðsƒò_°¨”é›­çmšNÑ|ŠÞ9}pŒæÕÁ?_½A¸pX6ã£5~BÍ$®&½çîti˜íeš—Y)%$¼bT®3liæ ‰šæÓíôP’°Ÿ4¿43YóãíP•ë1ÅõöKFôº½×Û‘“ã5>§)Ö@þ½÷õrŠåy’ðë´Õô[’:VÛÛäͦ#ÃÄwQ?HB‚Žd(à‘B ašcĪøL"J¤ÒitTy²8Ö;(“–íGxÉ_¸^õ[²¸öàûžÝ%׎¼…Å·£ØQíµéº²šua¥£ná7¹å›m« QþŠå±H^eÊO‚Q×u6æS—üu Ï2”î%vX º¬ð^ø*l O…—¿ÔÈÎÞ­Ë€q,>«žSÍÆì%ÒLÒëd¸¿ŠõBÆù1CZ¾$MœŠ9òÚP 'w‚ëæâ\/מ»Ì]áú¹­.r#ŽÂõE|!ð¾3¾>_·oˆa§Û¾Ódë£1Zë»Ó‘º¢±z”Û'ö=Žª²±¾±~V+´¢cjJ³tO%mN—ó“ï„ |ˆ®-‰«bWO+ o™ ^— I¯HÙ.°;í¶SÖ]æi_s9ó*péýÃë.7U^ÀÑs. 3uä °|^,ëÛ<ž·€‘;Ûc­=maº‹>V«Ût.[»«ÕŸÏªÕÝçä x£ü©# Ö¡_2˜IDAT(c”œ¨ûŸÀD‚Z°R’5° Û`+ã†"”¬Äà¦aÅ 5I° !J®`Åùk[à† 8éYÞ%†ß¿Ãq¨;Cï¾ù «Ÿ®‚k@qȤÑSV_ØÉðñûg°¢CÏÏÀƒ(À&­e`˜\VT»u×ïßP4 8 $såý]B8öü<˜F&_Äœk4%“½¨IEND®B`‚jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/skipped.png000066400000000000000000000017071475274123300273050ustar00rootroot00000000000000‰PNG  IHDR Vu\çiCCPICC Profilex…TßkÓPþÚe°á‹:g >h‘ndStCœ¶kWºÍZê6·!H›¦m\šÆ$í~°Ù‹o:Åwñ>ù Ùƒo{’ Æaø¬ˆ"Lö"³ž›4M'S¹÷»ßùî9'çä^ ùqZÓ/USOÅÂüÄäßò^C+ühM‹†J&G@Ó²yï³óÆltîoß«þcÕš• ð ¾”5Ä"áY i\ÔtàÖ‰ï15ÂÍLsX§ g8ocáŒ#–f45@š ÂÅB:K¸@8˜iàó ØÎä'&©’.‹<«ER/ådE² öðsƒò_°¨”é›­çmšNÑ|ŠÞ9}pŒæÕÁ?_½A¸pX6ã£5~BÍ$®&½çîti˜íeš—Y)%$¼bT®3liæ ‰šæÓíôP’°Ÿ4¿43YóãíP•ë1ÅõöKFôº½×Û‘“ã5>§)Ö@þ½÷õrŠåy’ðë´Õô[’:VÛÛäͦ#ÃÄwQ?HB‚Žd(à‘B ašcĪøL"J¤ÒitTy²8Ö;(“–íGxÉ_¸^õ[²¸öàûžÝ%׎¼…Å·£ØQíµéº²šua¥£ná7¹å›m« QþŠå±H^eÊO‚Q×u6æS—üu Ï2”î%vX º¬ð^ø*l O…—¿ÔÈÎÞ­Ë€q,>«žSÍÆì%ÒLÒëd¸¿ŠõBÆù1CZ¾$MœŠ9òÚP 'w‚ëæâ\/מ»Ì]áú¹­.r#ŽÂõE|!ð¾3¾>_·oˆa§Û¾Ódë£1Zë»Ó‘º¢±z”Û'ö=Žª²±¾±~V+´¢cjJ³tO%mN—ó“ï„ |ˆ®-‰«bWO+ o™ ^— I¯HÙ.°;í¶SÖ]æi_s9ó*péýÃë.7U^ÀÑs. 3uä °|^,ëÛ<ž·€‘;Ûc­=maº‹>V«Ût.[»«ÕŸÏªÕÝçä x£ü©# Ö¡_2dIDAT(c|{Œá? €‰µ`¥p B–¸-B–ƒkxwœ‘Yf3H $p tMèŠAjX@2@Ö„l2L Š 0A|4†˜3mB6EL1L6Mp èŠqib¤yL^ã*Ç#ÚIEND®B`‚jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/testng-reports.css000066400000000000000000000123531475274123300306510ustar00rootroot00000000000000body { margin: 0 0 5px 5px; } ul { margin: 0; } li { list-style-type: none; } a { text-decoration: none; } a:hover { text-decoration: underline; } .navigator-selected { background: #ffa500; } .wrapper { position: absolute; top: 60px; bottom: 0; left: 400px; right: 0; overflow: auto; } .navigator-root { position: absolute; top: 60px; bottom: 0; left: 0; width: 400px; overflow-y: auto; } .suite { margin: 0 10px 10px 0; background-color: #fff8dc; } .suite-name { padding-left: 10px; font-size: 25px; font-family: Times, sans-serif; } .main-panel-header { padding: 5px; background-color: #9FB4D9; /*afeeee*/; font-family: monospace; font-size: 18px; } .main-panel-content { padding: 5px; margin-bottom: 10px; background-color: #DEE8FC; /*d0ffff*/; } .rounded-window { border-radius: 10px; border-style: solid; border-width: 1px; } .rounded-window-top { border-top-right-radius: 10px 10px; border-top-left-radius: 10px 10px; border-style: solid; border-width: 1px; overflow: auto; } .light-rounded-window-top { border-top-right-radius: 10px 10px; border-top-left-radius: 10px 10px; } .rounded-window-bottom { border-style: solid; border-width: 0 1px 1px 1px; border-bottom-right-radius: 10px 10px; border-bottom-left-radius: 10px 10px; overflow: auto; } .method-name { font-size: 12px; font-family: monospace; } .method-content { border-style: solid; border-width: 0 0 1px 0; margin-bottom: 10px; padding-bottom: 5px; width: 80%; } .parameters { font-size: 14px; font-family: monospace; } .stack-trace { white-space: pre; font-family: monospace; font-size: 12px; font-weight: bold; margin-top: 0; margin-left: 20px; } .testng-xml { font-family: monospace; } .method-list-content { margin-left: 10px; } .navigator-suite-content { margin-left: 10px; font: 12px 'Lucida Grande'; } .suite-section-title { margin-top: 10px; width: 80%; border-style: solid; border-width: 1px 0 0 0; font-family: Times, sans-serif; font-size: 18px; font-weight: bold; } .suite-section-content { list-style-image: url(bullet_point.png); } .top-banner-root { position: absolute; top: 0; height: 45px; left: 0; right: 0; padding: 5px; margin: 0 0 5px 0; background-color: #0066ff; font-family: Times, sans-serif; color: #fff; text-align: center; } .button{ position: absolute; margin-left:500px; margin-top:8px; background-color: white; color:#0066ff; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight:bold; border-color:#0066ff ; border-radius:25px; cursor: pointer; height:30px; width:150px; outline:none; } .top-banner-title-font { font-size: 25px; } .test-name { font-family: 'Lucida Grande', sans-serif; font-size: 16px; } .suite-icon { padding: 5px; float: right; height: 20px; } .test-group { font: 20px 'Lucida Grande'; margin: 5px 5px 10px 5px; border-width: 0 0 1px 0; border-style: solid; padding: 5px; } .test-group-name { font-weight: bold; } .method-in-group { font-size: 16px; margin-left: 80px; } table.google-visualization-table-table { width: 100%; } .reporter-method-name { font-size: 14px; font-family: monospace; } .reporter-method-output-div { padding: 5px; margin: 0 0 5px 20px; font-size: 12px; font-family: monospace; border-width: 0 0 0 1px; border-style: solid; } .ignored-class-div { font-size: 14px; font-family: monospace; } .ignored-methods-div { padding: 5px; margin: 0 0 5px 20px; font-size: 12px; font-family: monospace; border-width: 0 0 0 1px; border-style: solid; } .border-failed { border-top-left-radius: 10px 10px; border-bottom-left-radius: 10px 10px; border-style: solid; border-width: 0 0 0 10px; border-color: #f00; } .border-skipped { border-top-left-radius: 10px 10px; border-bottom-left-radius: 10px 10px; border-style: solid; border-width: 0 0 0 10px; border-color: #edc600; } .border-passed { border-top-left-radius: 10px 10px; border-bottom-left-radius: 10px 10px; border-style: solid; border-width: 0 0 0 10px; border-color: #19f52d; } .times-div { text-align: center; padding: 5px; } .suite-total-time { font: 16px 'Lucida Grande'; } .configuration-suite { margin-left: 20px; } .configuration-test { margin-left: 40px; } .configuration-class { margin-left: 60px; } .configuration-method { margin-left: 80px; } .test-method { margin-left: 100px; } .chronological-class { background-color: skyblue; border-style: solid; border-width: 0 0 1px 1px; } .method-start { float: right; } .chronological-class-name { padding: 0 0 0 5px; color: #008; } .after, .before, .test-method { font-family: monospace; font-size: 14px; } .navigator-suite-header { font-size: 22px; margin: 0 10px 5px 0; background-color: #deb887; text-align: center; } .collapse-all-icon { padding: 5px; float: right; } /*retro Theme*/ jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/testng-reports.js000066400000000000000000000070341475274123300304750ustar00rootroot00000000000000$(document).ready(function() { $('a.navigator-link').on("click", function() { // Extract the panel for this link var panel = getPanelName($(this)); // Mark this link as currently selected $('.navigator-link').parent().removeClass('navigator-selected'); $(this).parent().addClass('navigator-selected'); showPanel(panel); }); installMethodHandlers('failed'); installMethodHandlers('skipped'); installMethodHandlers('passed', true); // hide passed methods by default $('a.method').on("click", function() { showMethod($(this)); return false; }); // Hide all the panels and display the first one (do this last // to make sure the click() will invoke the listeners) $('.panel').hide(); $('.navigator-link').first().trigger("click"); // Collapse/expand the suites $('a.collapse-all-link').on("click", function() { var contents = $('.navigator-suite-content'); if (contents.css('display') == 'none') { contents.show(); } else { contents.hide(); } }); }); // The handlers that take care of showing/hiding the methods function installMethodHandlers(name, hide) { function getContent(t) { return $('.method-list-content.' + name + "." + t.attr('panel-name')); } function getHideLink(t, name) { var s = 'a.hide-methods.' + name + "." + t.attr('panel-name'); return $(s); } function getShowLink(t, name) { return $('a.show-methods.' + name + "." + t.attr('panel-name')); } function getMethodPanelClassSel(element, name) { var panelName = getPanelName(element); var sel = '.' + panelName + "-class-" + name; return $(sel); } $('a.hide-methods.' + name).on("click", function() { var w = getContent($(this)); w.hide(); getHideLink($(this), name).hide(); getShowLink($(this), name).show(); getMethodPanelClassSel($(this), name).hide(); }); $('a.show-methods.' + name).on("click", function() { var w = getContent($(this)); w.show(); getHideLink($(this), name).show(); getShowLink($(this), name).hide(); showPanel(getPanelName($(this))); getMethodPanelClassSel($(this), name).show(); }); if (hide) { $('a.hide-methods.' + name).trigger("click"); } else { $('a.show-methods.' + name).trigger("click"); } } function getHashForMethod(element) { return element.attr('hash-for-method'); } function getPanelName(element) { return element.attr('panel-name'); } function showPanel(panelName) { $('.panel').hide(); var panel = $('.panel[panel-name="' + panelName + '"]'); panel.show(); } function showMethod(element) { var hashTag = getHashForMethod(element); var panelName = getPanelName(element); showPanel(panelName); var current = document.location.href; var base = current.substring(0, current.indexOf('#')) document.location.href = base + '#' + hashTag; var newPosition = $(document).scrollTop() - 65; $(document).scrollTop(newPosition); } function drawTable() { for (var i = 0; i < suiteTableInitFunctions.length; i++) { window[suiteTableInitFunctions[i]](); } for (var k in window.suiteTableData) { var v = window.suiteTableData[k]; var div = v.tableDiv; var data = v.tableData var table = new google.visualization.Table(document.getElementById(div)); table.draw(data, { showRowNumber : false }); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/testng-reports1.css000066400000000000000000000156121475274123300307330ustar00rootroot00000000000000body { background-color: whitesmoke; margin: 0 0 5px 5px; } ul { margin-top: 10px; margin-left:-10px; } li { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; padding:5px 5px; } a { text-decoration: none; color: black; font-size: 14px; } a:hover { color:black ; text-decoration: underline; } .navigator-selected { /* #ffa500; Mouse hover color after click Orange.*/ background:#027368 } .wrapper { position: absolute; top: 60px; bottom: 0; left: 400px; right: 0; margin-right:9px; overflow: auto;/*imortant*/ } .navigator-root { position: absolute; top: 60px; bottom: 0; left: 0; width: 400px; overflow-y: auto;/*important*/ } .suite { margin: -5px 10px 10px 5px; background-color: whitesmoke ;/*Colour of the left bside box*/ } .suite-name { font-size: 24px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;/*All TEST SUITE*/ color: white; } .main-panel-header { padding: 5px; background-color: #027368; /*afeeee*/; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color:white; font-size: 18px; } .main-panel-content { padding: 5px; margin-bottom: 10px; background-color: #CCD0D1; /*d0ffff*/; /*Belongs to backGround of rightSide boxes*/ } .rounded-window { border-style: dotted; border-width: 1px;/*Border of left Side box*/ background-color: whitesmoke; border-radius: 10px; } .rounded-window-top { border-top-right-radius: 10px 10px; border-top-left-radius: 10px 10px; border-style: solid; border-width: 1px; overflow: auto;/*Top of RightSide box*/ } .light-rounded-window-top { background-color: #027368; padding-left:120px; border-radius: 10px; } .rounded-window-bottom { border-bottom-right-radius: 10px 10px; border-bottom-left-radius: 10px 10px; overflow: auto;/*Bottom of rightSide box*/ } .method-name { font-size: 14px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: bold; } .method-content { border-style: solid; border-width: 0 0 1px 0; margin-bottom: 10px; padding-bottom: 5px; width: 100%; } .parameters { font-size: 14px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .stack-trace { white-space: pre; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 12px; font-weight: bold; margin-top: 0; margin-left: 20px; /*Error Stack Trace Message*/ } .testng-xml { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .method-list-content { margin-left: 10px; } .navigator-suite-content { margin-left: 10px; font: 12px 'Lucida Grande'; } .suite-section-title { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; font-weight:bold; background-color: #8C8887; margin-left: -10px; margin-top:10px; padding:6px; } .suite-section-content { list-style-image: url(bullet_point.png); background-color: whitesmoke; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; overflow: hidden; } .top-banner-root { position: absolute; top: 0; height: 45px; left: 0; right: 0; padding: 5px; margin: 0 0 5px 0; background-color: #027368; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; color: #fff; text-align: center;/*Belongs to the Top of Report*//*Status: - Completed*/ } .top-banner-title-font { font-size: 25px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 3px; float: right; } .test-name { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; } .suite-icon { padding: 5px; float: right; height: 20px; } .test-group { font: 20px 'Lucida Grande'; margin: 5px 5px 10px 5px; border-width: 0 0 1px 0; border-style: solid; padding: 5px; } .test-group-name { font-weight: bold; } .method-in-group { font-size: 16px; margin-left: 80px; } table.google-visualization-table-table { width: 100%; } .reporter-method-name { font-size: 14px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .reporter-method-output-div { padding: 5px; margin: 0 0 5px 20px; font-size: 12px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; border-width: 0 0 0 1px; border-style: solid; } .ignored-class-div { font-size: 14px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .ignored-methods-div { padding: 5px; margin: 0 0 5px 20px; font-size: 12px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; border-width: 0 0 0 1px; border-style: solid; } .border-failed { border-radius:2px; border-style: solid; border-width: 0 0 0 10px; border-color: #F20505; } .border-skipped { border-radius:2px; border-style: solid; border-width: 0 0 0 10px; border-color: #F2BE22; } .border-passed { border-radius:2px; border-style: solid; border-width: 0 0 0 10px; border-color: #038C73; } .times-div { text-align: center; padding: 5px; } .suite-total-time { font: 16px 'Lucida Grande'; } .configuration-suite { margin-left: 20px; } .configuration-test { margin-left: 40px; } .configuration-class { margin-left: 60px; } .configuration-method { margin-left: 80px; } .test-method { margin-left: 100px; } .chronological-class { background-color: #CCD0D1; border-width: 0 0 1px 1px;/*Chronological*/ } .method-start { float: right; } .chronological-class-name { padding: 0 0 0 5px; margin-top:5px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #008; } .after, .before, .test-method { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; margin-top:5px; } .navigator-suite-header { font-size: 18px; margin: 0px 10px 10px 5px; padding: 5px; border-radius: 10px; background-color: #027368; color: white; font-weight:bold; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; text-align: center; /*All Suites on top of left box*//*Status: -Completed*/ } .collapse-all-icon { padding: 3px; float: right; } .button{ position: absolute; margin-left:500px; margin-top:8px; background-color: white; color:#027368; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight:bold; border-color:#027368; border-radius:25px; cursor: pointer; height:30px; width:150px; outline: none; } /*Author: - Akhil Gullapalli*/jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/org/testng/testng-reports2.js000066400000000000000000000070421475274123300305560ustar00rootroot00000000000000window.onload = function () { let cookies = document.cookie; let cookieValue = cookies.split('='); if (cookieValue[1] === 'null' || localStorage.getItem('Theme') === 'null') { document.getElementById('retro').setAttribute('disabled', 'false'); } else if (cookieValue[1] === 'Switch Ultra Theme' || localStorage.getItem('Theme') === 'Switch Ultra Theme') { document.getElementById('button').innerText = "Switch Retro Theme"; document.getElementById('retro').setAttribute('disabled', 'false'); } else if (cookieValue[1] === 'Switch Retro Theme' || localStorage.getItem('Theme') === 'Switch Retro Theme') { if (cookieValue[1] === 'Switch Ultra Theme' || localStorage.getItem('Theme') === 'Switch Ultra Theme') { document.getElementById('button').innerText = "Switch Retro Theme"; document.getElementById('retro').setAttribute('disabled', 'false'); document.getElementById('button').innerText = "Switch Ultra Theme"; document.getElementById('retro').removeAttribute('disabled'); document.getElementById('ultra').setAttribute('disabled', 'false'); localStorage.setItem('Theme', select); } else if (select === 'Switch Ultra Theme') { document.getElementById('button').innerText = "Switch Retro Theme"; document.getElementById('ultra').removeAttribute('disabled'); document.getElementById('retro').setAttribute('disabled', 'false'); localStorage.setItem('Theme', select); } } else if (cookieValue[1] === 'Switch Retro Theme' || localStorage.getItem('Theme') === 'Switch Retro Theme') { document.getElementById('button').innerText = "Switch Ultra Theme"; document.getElementById('ultra').setAttribute('disabled', 'false'); } } document.getElementById('button').onclick = function () { let select = document.getElementById('button').innerText; if (select === 'Switch Retro Theme') { let d = new Date(); days = 365; d.setTime(+d + (days * 86400000)); //24 * 60 * 60 * 1000 document.cookie = "Theme =" + select + "; expires=" + d.toGMTString() + ";"; document.getElementById('button').innerText = "Switch Ultra Theme"; document.getElementById('retro').removeAttribute('disabled'); document.getElementById('ultra').setAttribute('disabled', 'false'); localStorage.setItem('Theme', select); } else if (select === 'Switch Ultra Theme') { let d = new Date(); days = 365; d.setTime(+d + (days * 86400000)); //24 * 60 * 60 * 1000 document.cookie = "Theme =" + select + "; expires=" + d.toGMTString() + ";"; document.getElementById('button').innerText = "Switch Retro Theme"; document.getElementById('ultra').removeAttribute('disabled'); document.getElementById('retro').setAttribute('disabled', 'false'); localStorage.setItem('Theme', select); } } //Function to mouse hovering affect. document.getElementById('button').onmouseover = function () { document.getElementById('button').style.borderRadius = "25px"; document.getElementById('button').style.width = "180px"; document.getElementById('button').style.height = "45px"; document.getElementById('button').style.marginTop = "1px"; } //Function to mouse out affect document.getElementById('button').onmouseout = function () { document.getElementById('button').style.borderRadius = "25px"; document.getElementById('button').style.width = "150px"; document.getElementById('button').style.height = "30px"; document.getElementById('button').style.marginTop = "8px"; } //This is the file where we handle the switching of the Themes. /*Author:- Akhil Gullapalli*/ jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/testng-1.0.dtd000066400000000000000000000202221475274123300253330ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/testng.css000066400000000000000000000004571475274123300250640ustar00rootroot00000000000000.invocation-failed, .test-failed { background-color: #DD0000; } .invocation-percent, .test-percent { background-color: #006600; } .invocation-passed, .test-passed { background-color: #00AA00; } .invocation-skipped, .test-skipped { background-color: #CCCC00; } .main-page { font-size: x-large; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/main/resources/testngtasks000066400000000000000000000000401475274123300253270ustar00rootroot00000000000000testng=org.testng.TestNGAntTask jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/000077500000000000000000000000001475274123300210615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/000077500000000000000000000000001475274123300224065ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/000077500000000000000000000000001475274123300233655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/groovy/000077500000000000000000000000001475274123300247125ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/groovy/EasyJUnitGroovySample.groovy000066400000000000000000000005161475274123300324060ustar00rootroot00000000000000package test.groovy import org.junit.Test import static groovy.test.GroovyAssert.shouldFail // Sample from https://groovy-lang.org/testing.html#_junit_4 class EasyJUnitGroovySample { @Test void indexOutOfBoundsAccess() { def numbers = [1, 2, 3, 4] shouldFail { numbers.get(4) } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/groovy/GroovyTest.groovy000066400000000000000000000043561475274123300303160ustar00rootroot00000000000000package test.groovy import org.testng.IMethodInstance import org.testng.IMethodInterceptor import org.testng.ITestContext import org.testng.ITestNGListener import org.testng.TestListenerAdapter import org.testng.annotations.Test import org.testng.reporters.JUnitXMLReporter import test.SimpleBaseTest import static org.assertj.core.api.Assertions.assertThat class GroovyTest extends SimpleBaseTest { @Test void easyGroovySampleShouldWork() { def tng = create(EasyJUnitGroovySample) tng.setJUnit(true) def adapter = new TestListenerAdapter() tng.addListener((ITestNGListener)adapter) tng.run() assert adapter.failedTests.isEmpty() assert adapter.skippedTests.isEmpty() assert adapter.passedTests.size() == 1 } @Test void specialNameGroovySampleShouldWork() { def tng = create(SpecialNameJUnitGroovySample) tng.setJUnit(true) def adapter = new TestListenerAdapter() tng.addListener((ITestNGListener)adapter) tng.run() assert adapter.failedTests.isEmpty() assert adapter.skippedTests.isEmpty() assert adapter.passedTests.size() == 1 } @Test void spockSampleShouldWork() { def tng = create(SpockSample) tng.setJUnit(true) def adapter = new TestListenerAdapter() tng.addListener((ITestNGListener)adapter) tng.run() assert adapter.failedTests.isEmpty() assert adapter.skippedTests.isEmpty() assert adapter.passedTests.size() == 1 } @Test void reporterWithSpockSampleShouldWork() { def tng = create(SpockSample) tng.setJUnit(true) tng.addListener((ITestNGListener) new JUnitXMLReporter()) tng.run() } @Test(description = "GITHUB-2360") void groovyInternalMethodsAreSkipped() { def tng = create Issue2360Sample def testMethodNames = [] IMethodInterceptor methodInterceptor = { List methods, ITestContext context -> testMethodNames = methods.collect { it.method.methodName } methods } tng.methodInterceptor = methodInterceptor tng.run() assertThat testMethodNames containsExactly "test1", "test2" } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/groovy/Issue2360Sample.java000066400000000000000000000010261475274123300303210ustar00rootroot00000000000000package test.groovy; import groovy.transform.Internal; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Sample test used by {@link Issue2360Sample}. */ @Test public class Issue2360Sample { @DataProvider public static Object[][] foo() { return new Object[][] {new Object[] {true}, new Object[] {false}}; } public void test1() {} @Test(dataProvider = "foo") public void test2(boolean foo) {} @Internal public void test3() {} @Internal public void test4(boolean foo) {} } SpecialNameJUnitGroovySample.groovy000066400000000000000000000005331475274123300336060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/groovypackage test.groovy import org.junit.Test import static groovy.test.GroovyAssert.shouldFail // Sample from https://groovy-lang.org/testing.html#_junit_4 class SpecialNameJUnitGroovySample { @Test void "index Out Of Bounds Access"() { def numbers = [1, 2, 3, 4] shouldFail { numbers.get(4) } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/groovy/test/groovy/SpockSample.groovy000066400000000000000000000004761475274123300304110ustar00rootroot00000000000000package test.groovy import spock.lang.Specification class SpockSample extends Specification { def "adding an element leads to size increase"() { setup: "a new stack instance is created" def stack = new Stack() when: stack.push 42 then: stack.size() == 1 } }jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/000077500000000000000000000000001475274123300220025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/ConverterSample2.java000066400000000000000000000012121475274123300260340ustar00rootroot00000000000000// Not that this file has no package (that's what we are testing) and therefore, // it is at the wrong location, but it's easier to leave it here. // Also, do not change the line numbers since the test will make sure // that the tags are generated in hardcoded line numbers import junit.framework.TestCase; public class ConverterSample2 extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public final void testClassJunit() {} public final void testSetClassId() {} public final void testSetClassName() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/ConverterSample4.java000066400000000000000000000034051475274123300260440ustar00rootroot00000000000000/* * Created on 12-Sep-2006 by micheb10 * it is at the wrong location, but it's easier to leave it here. * Also, do not change the line numbers since the test will make sure * that the tags are generated in hardcoded line numbers */ /** * Sample file for the Javadocv annotations to Java 5 annotations converter for the default package * * @author micheb10 12-Sep-2006 */ public class ConverterSample4 { /** * This comment line should be preserved * * @testng.before-suite alwaysRun = "true" */ public void beforeSuiteAlwaysRun() { // We are just checking appropriate annotations are added so we don't care about body } /** @testng.test */ public void plainTest() { // Empty body } /** * @testng.test * @testng.expected-exceptions value = "java.lang.NullPointerException * java.lang.NumberFormatException" */ public void expectedExceptions() { // Empty body } /** @testng.test groups = "groupA groupB" */ public void testGroups() { // Empty body } /** @testng.after-method */ public void afterMethod() { // Empty body } /** * This key should be preserved * * @author The author is a standard tag and should not be touched * @testng.test groups = "groupA" dependsOnMethods = "expectedExceptions" timeOut="3000" * unrecognised="futureProof" * @version another standard tag should not be changed * @testng.expected-exceptions value = "java.lang.NullPointerException * java.lang.NumberFormatException" */ public void testEverything() {} /** @testng.data-provider name="test1" */ public Object[][] dataProvider() { return null; } /** @testng.factory */ @SuppressWarnings({"unchecked", "deprecation"}) public Object[] factory() { return null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/NoPackageTest.java000066400000000000000000000005611475274123300253370ustar00rootroot00000000000000import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** @author Filippo Diotalevi */ public class NoPackageTest { private boolean m_run = false; @Test(groups = {"nopackage"}) public void test() { m_run = true; } @AfterMethod(groups = {"nopackage"}) public void after() { assert m_run : "test method was not run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/ReporterConfigTest.java000066400000000000000000000016301475274123300264350ustar00rootroot00000000000000import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Objects; import org.testng.annotations.Test; import org.testng.internal.ReporterConfig; public class ReporterConfigTest { private static final String CLASS_NAME = "org.testng.reporters.XMLReporter"; private static final String PROP_NAME_1 = "generateTestResultAttributes"; private static final String PROP_NAME_2 = "generateGroupsAttribute"; private static final String CONFIG_STR = CLASS_NAME + ":" + PROP_NAME_1 + "=true," + PROP_NAME_2 + "=true"; @Test public void testDeserialize() { ReporterConfig config = ReporterConfig.deserialize(CONFIG_STR); assertEquals(Objects.requireNonNull(config).getClassName(), CLASS_NAME); String serial = config.serialize(); assertTrue(serial.contains(PROP_NAME_1 + "=true")); assertTrue(serial.contains(PROP_NAME_2 + "=true")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/groovy/000077500000000000000000000000001475274123300233275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/groovy/transform/000077500000000000000000000000001475274123300253425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/groovy/transform/Internal.java000066400000000000000000000005331475274123300277620ustar00rootroot00000000000000package groovy.transform; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Internal {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/000077500000000000000000000000001475274123300225715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/000077500000000000000000000000001475274123300240755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/DryRunSample.java000066400000000000000000000010641475274123300273260ustar00rootroot00000000000000package org.testng; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DryRunSample { @BeforeSuite public void beforeSuite() { throw new RuntimeException("Error"); } @BeforeClass public void beforeClass() { throw new RuntimeException("error"); } @Test(dataProvider = "dp") public void test1(int i) {} @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/DryRunTest.java000066400000000000000000000012361475274123300270250ustar00rootroot00000000000000package org.testng; import static org.assertj.core.api.Assertions.assertThat; import org.testng.annotations.Test; import org.testng.internal.RuntimeBehavior; import test.SimpleBaseTest; public class DryRunTest extends SimpleBaseTest { @Test public void testDryRun() { System.setProperty(RuntimeBehavior.TESTNG_MODE_DRYRUN, "true"); try { TestNG tng = create(DryRunSample.class); TestListenerAdapter listener = new TestListenerAdapter(); tng.addListener(listener); tng.run(); assertThat(listener.getPassedTests()).hasSize(2); } finally { System.setProperty(RuntimeBehavior.TESTNG_MODE_DRYRUN, "false"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/JarFileUtilsTest.java000066400000000000000000000133551475274123300301440ustar00rootroot00000000000000package org.testng; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.jarfileutils.JarCreator; import org.testng.xml.IPostProcessor; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class JarFileUtilsTest { private static File jar = null; @BeforeClass public void generateTestJar() throws IOException { jar = JarCreator.generateJar(); } @Test public void testWithValidTestNames() throws MalformedURLException { JarFileUtils utils = newJarFileUtils(Collections.singletonList("testng-tests-child1")); runTest( utils, 1, new String[] {"testng-tests-child1"}, new String[] {"org.testng.jarfileutils.org.testng.SampleTest1"}); } @Test public void testWithNoTestNames() throws MalformedURLException { JarFileUtils utils = newJarFileUtils(null); runTest( utils, 3, new String[] {"testng-tests-child1", "testng-tests-child2", "testng-tests-child3"}, new String[] { "org.testng.jarfileutils.org.testng.SampleTest1", "org.testng.jarfileutils.org.testng.SampleTest2", "org.testng.jarfileutils.org.testng.SampleTest3" }); } @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = "\nThe test\\(s\\) <\\[testng-tests-child11\\]> cannot be found.") public void testWithInvalidTestNames() throws MalformedURLException { JarFileUtils utils = newJarFileUtils(Collections.singletonList("testng-tests-child11")); runTest( utils, 1, new String[] {"testng-tests-child1"}, new String[] {"org.testng.jarfileutils.org.testng.SampleTest1"}); } @Test public void testWithInvalidXmlFile() throws MalformedURLException { JarFileUtils utils = newJarFileUtils( "invalid-testng-tests.xml", Collections.singletonList("testng-tests-child11")); runTest( utils, 1, null, new String[] { "org.testng.jarfileutils.org.testng.SampleTest1", "org.testng.jarfileutils.org.testng.SampleTest2", "org.testng.jarfileutils.org.testng.SampleTest3" }, "Jar suite"); } @Test public void testWithValidTestNamesFromMultiChildSuites() throws MalformedURLException { JarFileUtils utils = newJarFileUtils( Arrays.asList("testng-tests-child2", "testng-tests-child4", "testng-tests-child5")); String[] expectedTestNames = new String[] {"testng-tests-child2", "testng-tests-child4", "testng-tests-child5"}; String[] expectedClassNames = new String[] { "org.testng.jarfileutils.org.testng.SampleTest2", "org.testng.jarfileutils.org.testng.SampleTest4", "org.testng.jarfileutils.org.testng.SampleTest5" }; List suites = utils.extractSuitesFrom(jar); assertThat(suites).hasSize(3); XmlSuite suite = suites.get(0); assertThat(suite.getName()).isEqualTo("testng-tests-suite"); List testNames = new LinkedList<>(); List classNames = new LinkedList<>(); for (XmlSuite xmlSuite : suites) { extractClassNames(xmlSuite, testNames, classNames); } assertThat(testNames).containsExactly(expectedTestNames); assertThat(classNames).contains(expectedClassNames); } private static void extractClassNames( XmlSuite xmlSuite, List testNames, List classNames) { for (XmlTest xmlTest : xmlSuite.getTests()) { testNames.add(xmlTest.getName()); for (XmlClass xmlClass : xmlTest.getXmlClasses()) { classNames.add(xmlClass.getName()); } } } private static void runTest( JarFileUtils utils, int numberOfTests, String[] expectedTestNames, String[] expectedClassNames) { runTest(utils, numberOfTests, expectedTestNames, expectedClassNames, "testng-tests-suite"); } private static void runTest( JarFileUtils utils, int numberOfTests, String[] expectedTestNames, String[] expectedClassNames, String expectedSuiteName) { List suites = utils.extractSuitesFrom(jar); assertThat(suites).hasSize(1); XmlSuite suite = suites.get(0); assertThat(suite.getName()).isEqualTo(expectedSuiteName); assertThat(suite.getTests()).hasSize(numberOfTests); List testNames = new LinkedList<>(); List classNames = new LinkedList<>(); extractClassNames(suite, testNames, classNames); if (expectedTestNames != null) { assertThat(testNames).containsExactly(expectedTestNames); } assertThat(classNames).contains(expectedClassNames); } public static class FakeProcessor implements IPostProcessor { @Override public Collection process(Collection suites) { return suites; } } private static JarFileUtils newJarFileUtils(List testNames) throws MalformedURLException { return newJarFileUtils("jarfileutils/testng-tests.xml", testNames); } private static JarFileUtils newJarFileUtils(String suiteXmlName, List testNames) throws MalformedURLException { URL url = jar.toURI().toURL(); URLClassLoader classLoader = new URLClassLoader(new URL[] {url}, ClassLoader.getSystemClassLoader()); Thread.currentThread().setContextClassLoader(classLoader); return new JarFileUtils(new FakeProcessor(), suiteXmlName, testNames); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/SampleIModule.java000066400000000000000000000003461475274123300274430ustar00rootroot00000000000000package org.testng; import com.google.inject.Module; public final class SampleIModule implements IModule { private static final Module module = binder -> {}; @Override public Module getModule() { return module; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/000077500000000000000000000000001475274123300257115ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/ClassHelperTest.java000066400000000000000000000120031475274123300316150ustar00rootroot00000000000000package org.testng.internal; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.UUID; import org.assertj.core.api.Assertions; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.internal.issue1339.BabyPanda; import org.testng.internal.issue1339.LittlePanda; import org.testng.internal.issue1456.TestClassSample; import org.testng.internal.misamples.AbstractMoves; import org.testng.internal.misamples.Batman; import org.testng.internal.misamples.JohnTravoltaMoves; import org.testng.internal.misamples.MickJagger; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class ClassHelperTest { @Test public void testGetAvailableMethods() { runTest(getExpected(), LittlePanda.class); } @Test public void testGetAvailableMethodsWhenOverrdingIsInvolved() { List expected = getExpected("equals", "hashCode", "toString"); runTest(expected, BabyPanda.class); } @Test public void testFindClassInSameTest() { runTest(TestClassSample.class, 1, TestClassSample.class); } @Test public void testFindClassesInSameTest() { runTest(TestClassSample.class, 2, TestClassSample.class, BabyPanda.class); } @Test public void testNoClassDefFoundError() { URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {}) { @Override public Class loadClass(String name) throws ClassNotFoundException { throw new NoClassDefFoundError(); } }; ClassHelper.addClassLoader(urlClassLoader); String fakeClassName = UUID.randomUUID().toString(); Assert.assertNull( ClassHelper.forName(fakeClassName), "The result should be null; no exception should be thrown."); } @Test(dataProvider = "data") public void testWithDefaultMethodsBeingOverridden( Class cls, int expectedCount, String... expected) { Set methods = ClassHelper.getAvailableMethodsExcludingDefaults(cls); Assertions.assertThat(methods).hasSize(expectedCount); for (Method m : methods) { String actual = m.getDeclaringClass().getName() + "." + m.getName(); Assertions.assertThat(expected).contains(actual); } } @DataProvider(name = "data") public Object[][] getTestData() { return new Object[][] { {MickJagger.class, 1, MickJagger.class.getName() + ".dance"}, { JohnTravoltaMoves.class, 2, new String[] { JohnTravoltaMoves.class.getName() + ".walk", AbstractMoves.class.getName() + ".dance" } }, { Batman.class, 3, new String[] { Batman.class.getName() + ".fly", Batman.class.getName() + ".liftWeights", Batman.class.getName() + ".yellSlogan" } } }; } private static void runTest(Class classToBeFound, int expectedCount, Class... classes) { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("xml_suite"); newXmlTest("test1", xmlSuite, classes); newXmlTest("test2", xmlSuite, classes); newXmlTest("test3", xmlSuite, classes); XmlClass[] xmlClasses = ClassHelper.findClassesInSameTest(classToBeFound, xmlSuite); assertThat(xmlClasses.length).isEqualTo(expectedCount); } private static void newXmlTest(String testname, XmlSuite xmlSuite, Class... clazz) { XmlTest xmlTest = new XmlTest(xmlSuite); xmlTest.setName(testname); xmlTest.setXmlClasses(newXmlClass(clazz)); } private static List newXmlClass(Class... classes) { List xmlClasses = new ArrayList<>(); for (Class clazz : classes) { xmlClasses.add(new XmlClass(clazz)); } return xmlClasses; } private static void runTest(List expected, Class whichClass) { Set methods = ClassHelper.getAvailableMethods(whichClass); // Intentionally not using assertEquals because when this test is executed via gradle an // additional method // called "jacocoInit()" is getting added, which does not get added when this test is executed // individually int size = expected.size(); Assert.assertTrue( methods.size() >= size, "Number of methods found should have been atleast " + size); for (Method method : methods) { if ("$jacocoInit".equalsIgnoreCase(method.getName())) { continue; } Assert.assertTrue(expected.contains(method.getName())); } } private static List getExpected(String... additionalMethods) { String[] defaultMethods = new String[] {"announcer", "announcer", "inheritable", "inheritable"}; if (additionalMethods == null) { return Arrays.asList(defaultMethods); } List expected = new ArrayList<>(Arrays.asList(defaultMethods)); expected.addAll(Arrays.asList(additionalMethods)); return expected; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/ConsoleReporter.java000066400000000000000000000025701475274123300317050ustar00rootroot00000000000000package org.testng.internal; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.*; import org.testng.xml.XmlSuite; public class ConsoleReporter implements IReporter { @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { for (ISuite suite : suites) { for (Map.Entry testResult : suite.getResults().entrySet()) { Set results = testResult.getValue().getTestContext().getFailedTests().getAllResults(); if (results.isEmpty()) { continue; } System.out.println( "Failures in :" + suite.getName() + ", :" + testResult.getKey()); for (ITestResult result : results) { String c = result.getMethod().getRealClass().getName(); String m = result.getMethod().getMethodName() + "()"; System.out.println(c + "." + m); if (result.getThrowable() != null) { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); result.getThrowable().printStackTrace(writer); System.out.println( String.format("StackTrace:\n %s \n", Utils.filterTrace(sw.toString()))); } } } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/DynamicGraphHelperTest.java000066400000000000000000000246741475274123300331370ustar00rootroot00000000000000package org.testng.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.ITestObjectFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.IAnnotation; import org.testng.annotations.ITestAnnotation; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.collections.Sets; import org.testng.internal.annotations.AnnotationHelper; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.internal.dynamicgraph.FactoryTestClassSample; import org.testng.internal.dynamicgraph.FakeTestClass; import org.testng.internal.dynamicgraph.FakeWrappedFactoryMethod; import org.testng.internal.dynamicgraph.HardDependencyTestClassSample; import org.testng.internal.dynamicgraph.HardDependencyViaGroupsTestClassSample; import org.testng.internal.dynamicgraph.IndependentTestClassSample; import org.testng.internal.dynamicgraph.SequentialClassA; import org.testng.internal.dynamicgraph.SequentialClassB; import org.testng.internal.dynamicgraph.SoftDependencyTestClassSample; import org.testng.internal.dynamicgraph.testpackage.PackageTestClassA; import org.testng.internal.dynamicgraph.testpackage.PackageTestClassBAbstract; import org.testng.internal.dynamicgraph.testpackage.PackageTestClassBB; import org.testng.internal.objects.InstanceCreator; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class DynamicGraphHelperTest extends SimpleBaseTest { private static final IAnnotationFinder finder = new JDK15AnnotationFinder(new DefaultAnnotationTransformer()); @Test public void testCreateDynamicGraphAllIndependent() { DynamicGraph graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); assertThat(graph.getEdges()).isEmpty(); } @Test(dataProvider = "getDependencyData") public void testCreateDynamicGraphWithDependency(Class clazz) { DynamicGraph graph = newGraph(clazz); assertThat(graph.getFreeNodes()).hasSize(1); Map edges = searchForMethod("b", graph); assertThat(edges).hasSize(1); edges = searchForMethod("a", graph); assertThat(edges).isEmpty(); } @Test(dataProvider = "getSoftDependencyData") public void testCreateDynamicGraphWithSoftDependency(Class clazz) { DynamicGraph graph = newGraph(clazz); assertThat(graph.getFreeNodes()).hasSize(2); Map edges = searchForMethod("b", graph); assertThat(edges).isEmpty(); edges = searchForMethod("a", graph); assertThat(edges).isEmpty(); } @DataProvider(name = "getDependencyData") public Object[][] getDependencyData() { return new Object[][] { {HardDependencyTestClassSample.class}, {HardDependencyViaGroupsTestClassSample.class} }; } @DataProvider(name = "getSoftDependencyData") public Object[][] getSoftDependencyData() { return new Object[][] {{SoftDependencyTestClassSample.class}}; } @Test public void testCreateDynamicGraphWithPreserveOrderAndNoParallelism() { Class[] classes = new Class[] {SequentialClassA.class, SequentialClassB.class}; XmlTest xmlTest = createXmlTest("suite", "test", classes); xmlTest.setPreserveOrder(true); xmlTest.setParallel(XmlSuite.ParallelMode.NONE); DynamicGraph graph = newGraph(xmlTest, classes); List methodNames = Arrays.asList("testMethodOneSequentialClassB", "testMethodTwoSequentialClassB"); for (String methodName : methodNames) { Map edges = searchForMethod(methodName, graph); assertThat(extractDestinationInfoFromEdge(edges)) .contains("testMethodOneSequentialClassA", "testMethodTwoSequentialClassA"); } } @Test public void testCreateDynamicGraphWithGroupByInstances() { Class[] classes = new Class[] {FactoryTestClassSample.class}; XmlTest xmlTest = createXmlTest("suite", "test", classes); xmlTest.setGroupByInstances(true); ITestNGMethod[] methods = methods(ITestAnnotation.class, xmlTest, classes); List methodList = Lists.newLinkedList(); List objects = Lists.newLinkedList(); objects.add(new FactoryTestClassSample("one")); objects.add(new FactoryTestClassSample("two")); for (FactoryTestClassSample object : objects) { for (ITestNGMethod method : methods) { methodList.add(new FakeWrappedFactoryMethod(method, object)); } } ITestNGMethod[] allMethods = methodList.toArray(new ITestNGMethod[0]); for (Class clazz : classes) { ITestClass testClass = new FakeTestClass(clazz); List tstMethods = Lists.newArrayList(); MethodHelper.fixMethodsWithClass(allMethods, testClass, tstMethods); } DynamicGraph graph = DynamicGraphHelper.createDynamicGraph(allMethods, xmlTest); Map edges = searchForMethod("testMethod", graph, "two"); Set actualObjectIds = Sets.newHashSet(); List actualMethodNames = Lists.newLinkedList(); for (ITestNGMethod to : edges.keySet()) { actualObjectIds.add(to.getInstance().toString()); actualMethodNames.add(to.getMethodName()); } assertThat(actualObjectIds).containsExactly("one"); assertThat(actualMethodNames).contains("testMethod", "anotherTestMethod"); } @DataProvider public Object[][] classesFromPackage() { return new Object[][] { { new Class[] { PackageTestClassA.class, PackageTestClassBAbstract.class, PackageTestClassBB.class } }, {new Class[] {PackageTestClassA.class, PackageTestClassBB.class}} }; } @Test(dataProvider = "classesFromPackage") public void testCreateDynamicGraphWithPackageWithAbstractClassPreserveOrderTrue( Class[] classes) { XmlTest xmlTest = createXmlTest("2249_suite", "2249_test", classes); xmlTest.setPreserveOrder(true); DynamicGraph graph = newGraph(xmlTest, classes); assertThat( graph.getFreeNodes().stream() .map(ITestNGMethod::getMethodName) .collect(Collectors.toList())) .containsExactly("a1", "a2"); } @Test(dataProvider = "classesFromPackage") public void testCreateDynamicGraphWithPackageWithoutAbstractClass(Class[] classes) { XmlTest xmlTest = createXmlTest("2249_suite", "2249_test", classes); xmlTest.setPreserveOrder(false); DynamicGraph graph = newGraph(xmlTest, classes); assertThat( graph.getFreeNodes().stream() .map(ITestNGMethod::getMethodName) .collect(Collectors.toList())) .containsExactly("a1", "a2", "b2", "b1"); } private static List extractDestinationInfoFromEdge(Map edges) { List destinations = Lists.newLinkedList(); for (ITestNGMethod to : edges.keySet()) { destinations.add(to.getMethodName()); } return destinations; } private static Map searchForMethod( String methodName, DynamicGraph graph) { return searchForMethod(methodName, graph, null); } private static Map searchForMethod( String methodName, DynamicGraph graph, Object instance) { for (Map.Entry> edge : graph.getEdges().entrySet()) { if (edge.getKey().getMethodName().equals(methodName) && (instance == null || edge.getKey().getInstance().toString().equals(instance.toString()))) { return edge.getValue(); } } return Maps.newHashMap(); } private static DynamicGraph newGraph(Class... classes) { XmlTest xmlTest = createXmlTest("suite", "test", classes); return newGraph(xmlTest, classes); } private static DynamicGraph newGraph(XmlTest xmlTest, Class... classes) { ITestNGMethod[] methods = methods(ITestAnnotation.class, xmlTest, classes); return DynamicGraphHelper.createDynamicGraph(methods, xmlTest); } private static ITestNGMethod[] methods( Class annotationClass, XmlTest xmlTest, Class... classes) { List allMethods = Lists.newArrayList(); for (Class clazz : classes) { List tstMethods = associateInstanceToMethods(clazz, xmlTest, annotationClass); allMethods.addAll(tstMethods); } return allMethods.toArray(new ITestNGMethod[0]); } private static List associateInstanceToMethods( Class clazz, XmlTest xmlTest, Class annotationClass) { ITestClass testClass = new FakeTestClass(clazz); ITestNGMethod[] rawMethods = methods(clazz, xmlTest, annotationClass); Object object = newInstance(clazz); List fixedMethods = Lists.newArrayList(); if (object == null) { // Looks like there was a non default constructor on the class (maybe because its driven by a // factory) // So lets not try to associate the instance. We will use the method as is. fixedMethods.addAll(Arrays.asList(rawMethods)); } else { for (ITestNGMethod each : rawMethods) { ITestNGMethod m = new TestNGMethod( new ITestObjectFactory() {}, each.getConstructorOrMethod().getMethod(), finder, xmlTest, object); fixedMethods.add(m); } } List tstMethods = Lists.newArrayList(); MethodHelper.fixMethodsWithClass( fixedMethods.toArray(new ITestNGMethod[0]), testClass, tstMethods); return tstMethods; } private static Object newInstance(Class clazz) { try { return InstanceCreator.newInstance(clazz); } catch (Exception e) { return null; } } private static ITestNGMethod[] methods( Class clazz, XmlTest xmlTest, Class annotationClass) { return AnnotationHelper.findMethodsWithAnnotation( new ITestObjectFactory() {}, clazz, annotationClass, finder, xmlTest); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/DynamicGraphTest.java000066400000000000000000000312631475274123300317670ustar00rootroot00000000000000package org.testng.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.IDynamicGraph; import org.testng.IDynamicGraph.Status; import org.testng.ITestNGMethod; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.ListMultiMap; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.internal.dynamicgraph.EdgeWeightTestSample1; import org.testng.internal.dynamicgraph.EdgeWeightTestSample2; import org.testng.internal.dynamicgraph.LotsOfEdgesTest; import org.testng.xml.XmlSuite; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.TestClassContainerForGitHubIssue1360; public class DynamicGraphTest extends SimpleBaseTest { private static class Node { private final String name; private Node(String name) { this.name = name; } @Override public String toString() { return name; } } @SafeVarargs private static void assertFreeNodesEquals(IDynamicGraph graph, T... expected) { assertFreeNodesEquals(graph, Arrays.asList(expected)); } private static void assertFreeNodesEquals(IDynamicGraph graph, List expected) { // Compare free nodes using isEqualTo instead of containsOnly as we care about ordering too. assertThat(graph.getFreeNodes()).isEqualTo(expected); } @Test public void test8() { /* digraph test8 { a1; a2; b1 -> {a1; a2;} b2 -> {a1; a2;} c1 -> {b1; b2;} x; y; } */ DynamicGraph dg = new DynamicGraph<>(); Node a1 = new Node("a1"); Node a2 = new Node("a2"); Node b1 = new Node("b1"); Node b2 = new Node("b2"); Node c1 = new Node("c1"); dg.addNode(a1); dg.addNode(a2); dg.addNode(b1); dg.addNode(b2); dg.addNode(c1); dg.addEdges(1, b1, Arrays.asList(a1, a2)); dg.addEdges(1, b2, Arrays.asList(a1, a2)); dg.addEdges(1, c1, Arrays.asList(b1, b2)); dg.addEdges(0, a2, Arrays.asList(a1, b1, c1)); dg.addEdges(0, b2, Arrays.asList(a1, b1, c1)); Node x = new Node("x"); Node y = new Node("y"); dg.addNode(x); dg.addNode(y); dg.addEdges(0, a1, Arrays.asList(x, y)); dg.addEdges(0, b1, Arrays.asList(x, y)); dg.addEdges(0, c1, Arrays.asList(x, y)); assertFreeNodesEquals(dg, x, y); dg.setStatus(dg.getFreeNodes(), Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(x, Status.FINISHED); dg.setStatus(y, Status.FINISHED); assertFreeNodesEquals(dg, a1); dg.setStatus(a1, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(a1, Status.FINISHED); assertFreeNodesEquals(dg, a2); dg.setStatus(a2, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(a2, Status.FINISHED); assertFreeNodesEquals(dg, b1); dg.setStatus(b1, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(b1, Status.FINISHED); assertFreeNodesEquals(dg, b2); dg.setStatus(b2, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(b2, Status.FINISHED); assertFreeNodesEquals(dg, c1); } @Test public void test2() { /* digraph test2 { a1; a2; b1 -> {a1; a2;} x; } */ DynamicGraph dg = new DynamicGraph<>(); Node a1 = new Node("a1"); Node a2 = new Node("a2"); Node b1 = new Node("b1"); dg.addNode(a1); dg.addNode(a2); dg.addNode(b1); dg.addEdges(1, b1, Arrays.asList(a1, a2)); dg.addEdges(0, a2, Arrays.asList(a1, b1)); Node x = new Node("x"); dg.addNode(x); dg.addEdge(0, a1, x); dg.addEdge(0, b1, x); assertFreeNodesEquals(dg, x); dg.setStatus(x, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(x, Status.FINISHED); assertFreeNodesEquals(dg, a1); dg.setStatus(a1, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(a1, Status.FINISHED); assertFreeNodesEquals(dg, a2); dg.setStatus(a2, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(a2, Status.FINISHED); assertFreeNodesEquals(dg, b1); Node b2 = new Node("b2"); // 2 dg.setStatus(b2, Status.RUNNING); dg.setStatus(b1, Status.FINISHED); assertFreeNodesEquals(dg); } @Test public void test3() { DynamicGraph dg = new DynamicGraph<>(); Node a = new Node("a"); Node b = new Node("b"); Node c = new Node("c"); dg.addNode(a); dg.addNode(b); dg.addNode(c); dg.addEdge(1, a, b); dg.addEdge(0, c, b); dg.addEdge(0, b, a); assertFreeNodesEquals(dg, b); dg.setStatus(b, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(b, Status.FINISHED); assertFreeNodesEquals(dg, a); dg.setStatus(a, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(a, Status.FINISHED); assertFreeNodesEquals(dg, c); dg.setStatus(c, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(c, Status.FINISHED); assertFreeNodesEquals(dg); } @Test public void test4() { DynamicGraph dg = new DynamicGraph<>(); Node a = new Node("a"); Node b = new Node("b"); dg.addNode(a); dg.addNode(b); dg.addEdge(0, b, a); assertFreeNodesEquals(dg, a); dg.setStatus(a, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(a, Status.FINISHED); assertFreeNodesEquals(dg, b); dg.setStatus(b, Status.RUNNING); assertFreeNodesEquals(dg); dg.setStatus(b, Status.FINISHED); assertFreeNodesEquals(dg); } @Test public void testOrderingOfEdgesWithSameWeight() { Class[] classes = new Class[] { TestClassContainerForGitHubIssue1360.TestNG1.class, TestClassContainerForGitHubIssue1360.TestNG2.class, TestClassContainerForGitHubIssue1360.TestNG3.class }; List methods = extractTestNGMethods(classes); DynamicGraph graph = new DynamicGraph<>(); ListMultiMap methodsByPriority = Maps.newListMultiMap(); for (ITestNGMethod method : methods) { methodsByPriority.put(method.getPriority(), method); graph.addNode(method); } List availablePriorities = Lists.newArrayList(methodsByPriority.keySet()); Collections.sort(availablePriorities); Integer previousPriority = methods.size() > 0 ? availablePriorities.get(0) : 0; for (int i = 1; i < availablePriorities.size(); i++) { Integer currentPriority = availablePriorities.get(i); for (ITestNGMethod p0Method : methodsByPriority.get(previousPriority)) { for (ITestNGMethod p1Method : methodsByPriority.get(currentPriority)) { graph.addEdge(1, p1Method, p0Method); } } previousPriority = currentPriority; } List expected = Arrays.asList("TestNG1.test1TestNG1", "TestNG2.test1TestNG2", "TestNG3.test1TestNG3"); runAssertion(graph, expected); expected = Arrays.asList("TestNG1.test2TestNG1", "TestNG2.test2TestNG2", "TestNG3.test2TestNG3"); runAssertion(graph, expected); expected = Arrays.asList("TestNG1.test3TestNG1", "TestNG2.test3TestNG2", "TestNG3.test3TestNG3"); runAssertion(graph, expected); } @Test public void edgeWeightTest1() { List expectedOrder1 = Arrays.asList("t1", "t2", "t3"); TestNG tng = create(EdgeWeightTestSample1.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); Assert.assertEquals(listener.getSucceedMethodNames(), expectedOrder1); } @Test public void edgeWeightTest2() { List expectedOrder2 = Arrays.asList("t1", "t2", "t3", "t4", "t5"); TestNG tng = create(EdgeWeightTestSample2.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); Assert.assertEquals(listener.getSucceedMethodNames(), expectedOrder2); } private static void runAssertion(IDynamicGraph graph, List expected) { List p1Methods = graph.getFreeNodes(); Assert.assertEquals(p1Methods.size(), 3); graph.setStatus(p1Methods, Status.FINISHED); for (ITestNGMethod p1Method : p1Methods) { Assert.assertTrue(expected.contains(constructName(p1Method))); } } private static String constructName(ITestNGMethod method) { return method.getConstructorOrMethod().getDeclaringClass().getSimpleName() + "." + method.getMethodName(); } @Test public void testDuplicationFunctionality() { XmlSuite suite = createXmlSuite("suite", "test", TestClassSample.class); TestNG testng = create(suite); MethodMultiplyingInterceptor tla = new MethodMultiplyingInterceptor(); testng.addListener(tla); testng.run(); int expected = tla.getMultiplyCount() + tla.getOriginalMethodCount(); assertThat(tla.getPassedTests().size()).isEqualTo(expected); } @Test(expectedExceptions = IllegalStateException.class) public void testPreventCycles() { // Cycles having the same weight should throw an IllegalStateException immediately. DynamicGraph dg = new DynamicGraph<>(); dg.addEdge(0, "a", "b"); dg.addEdge(0, "b", "a"); } @Test public void testAllowedCycles() { // Cycles with differing weights are explicitly allowed as the graph will discard the lowest // weighted edge in // order to free up the cycle. DynamicGraph dg = new DynamicGraph<>(); dg.addEdge(0, "a", "b"); // Different weight is allowed dg.addEdge(1, "b", "a"); } @Test public void testGainWeight() { DynamicGraph dg = new DynamicGraph<>(); dg.addEdge(1, "a", "b"); assertThat(dg.getEdges().values().size()).isEqualTo(1); assertThat(dg.getEdges().get("a").get("b")).isEqualTo(1); // Duplicated edge, but with lower weight dg.addEdge(0, "a", "b"); // Should only be one edge with same weight assertThat(dg.getEdges().values().size()).isEqualTo(1); assertThat(dg.getEdges().get("a").get("b")).isEqualTo(1); // Duplicated edge, but with higher weight dg.addEdge(2, "a", "b"); // Should only be one edge with weight of 2 now. assertThat(dg.getEdges().values().size()).isEqualTo(1); assertThat(dg.getEdges().get("a").get("b")).isEqualTo(2); } /** * Inefficient algorithms within DynamicGraph can quickly make the execution time explode. This * test puts some minimal limits on the time it takes to process the graph. At the time of the * addition of this test, it took less than 100ms to execute. 2000ms gives enough headroom to * prevent flaky failures because of external conditions such as slower or lower CPU resources. */ @Test(timeOut = 2000) public void testLotsOfEdges() { // https://github.com/cbeust/testng/issues/1710 TestNG tng = create(LotsOfEdgesTest.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); } /** * Test that DynamicGraph correctly handles selecting free nodes so that independent nodes can be * processed in parallel. */ @Test public void testParallel() { DynamicGraph dg = new DynamicGraph<>(); List fizz = Lists.newArrayList(); List buzz = Lists.newArrayList(); List fizzBuzz = Lists.newArrayList(); List other = Lists.newArrayList(); for (int i = 0; i < 100; i++) { dg.addNode(i); if (i % 15 == 0) { fizzBuzz.add(i); } else if (i % 5 == 0) { buzz.add(i); } else if (i % 3 == 0) { fizz.add(i); } else { other.add(i); } } // Fizzbuzz based dependencies – fizz depends on other, buzz depends on fizz, fizzbuzz depends // on buzz. for (Integer f : fizz) { for (Integer o : other) { dg.addEdge(0, f, o); } } for (Integer b : buzz) { for (Integer f : fizz) { dg.addEdge(0, b, f); } } for (Integer fb : fizzBuzz) { for (Integer b : buzz) { dg.addEdge(0, fb, b); } } // other is ready assertFreeNodesEquals(dg, other); dg.setStatus(other, Status.FINISHED); // fizz is ready assertFreeNodesEquals(dg, fizz); dg.setStatus(fizz, Status.FINISHED); // buzz is ready assertFreeNodesEquals(dg, buzz); dg.setStatus(buzz, Status.FINISHED); // fizzbuzz is ready assertFreeNodesEquals(dg, fizzBuzz); dg.setStatus(fizzBuzz, Status.FINISHED); // all done assertThat(dg.getFreeNodes()).isEmpty(); assertThat(dg.getNodeCountWithStatus(Status.READY)).isEqualTo(0); assertThat(dg.getNodeCountWithStatus(Status.FINISHED)).isEqualTo(100); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/GroupsHelperTest.java000066400000000000000000000030661475274123300320400ustar00rootroot00000000000000package org.testng.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Maps; public class GroupsHelperTest { @Test public void testCreateGroupsWithoutMetaGroups() { Map expected = Maps.newHashMap(); expected.put("foo", "foo"); Map actual = GroupsHelper.createGroups(Collections.emptyMap(), Collections.singletonList("foo")); assertThat(actual).containsAllEntriesOf(expected); } @Test(dataProvider = "getTestData") public void testCreateGroupsWithMetaGroups( String metaGrpName, List grpName, Map expected) { Map> metaGroups = Maps.newHashMap(); metaGroups.put(metaGrpName, Collections.singletonList(metaGrpName)); Map actual = GroupsHelper.createGroups(metaGroups, grpName); assertThat(actual).containsAllEntriesOf(expected); } @DataProvider(name = "getTestData") public Object[][] getTestData() { return new Object[][] { {"bar", Collections.singletonList("foo"), constructExpectedMap("foo")}, {"bar", Arrays.asList("foo", "bar"), constructExpectedMap("foo", "bar")} }; } private static Map constructExpectedMap(String... keys) { Map map = Maps.newHashMap(); for (String key : keys) { map.put(key, key); } return map; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/MethodHelperTest.java000066400000000000000000000027141475274123300320000ustar00rootroot00000000000000package org.testng.internal; import org.testng.ITestNGMethod; import org.testng.ITestObjectFactory; import org.testng.Reporter; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.internal.issue2195.TestClass; import test.tmp.AnnotationTransformer; public class MethodHelperTest { @Test(expectedExceptions = {TestNGException.class}) public void findDependedUponMethods() throws NoSuchMethodException { TestClass testClass = new TestClass(); ConstructorOrMethod constructorOrMethod = new ConstructorOrMethod(testClass.getClass().getMethod("dummyMethod")); IAnnotationFinder annotationFinder = new JDK15AnnotationFinder(new AnnotationTransformer()); ITestNGMethod method = new ConfigurationMethod( new ITestObjectFactory() {}, constructorOrMethod, annotationFinder, false, false, false, false, false, false, true, false, new String[0], new String[0], Reporter.getCurrentTestResult().getTestContext().getCurrentXmlTest(), testClass); method.addMethodDependedUpon("dummyDependsOnMethod"); ITestNGMethod[] methods = new ITestNGMethod[0]; MethodHelper.findDependedUponMethods(method, methods); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/MethodInstanceTest.java000066400000000000000000000310611475274123300323220ustar00rootroot00000000000000package org.testng.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.testng.Assert; import org.testng.IClass; import org.testng.IRetryAnalyzer; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlTest; /** * Unit tests for {@link MethodInstance}. * * @author Andreas Kluth */ public class MethodInstanceTest { public static void main(String[] args) { new MethodInstanceTest().sortByIndexSatisfiesContract(); } @Test public void sortByIndexSatisfiesContract() { // Build a list of entries imposing the same behavior as the live suite, reduced to the // minimum to create the same condition. List methods = new ArrayList<>(); methods.add(buildMethodInstance("unittests", "StateTest", 1, "aCategorization")); methods.add(buildMethodInstance("unittests", "StateTest", 1, "bCategorization")); methods.add(buildMethodInstance("unittests", "StateTest", 1, "cCategorization")); methods.add(buildMethodInstance("unittests", "StateTest", 1, "dCategorization")); methods.add(buildMethodInstance("unittests", "StateTest", 1, "eCategorization")); methods.add(buildMethodInstance("unittests", "StateTest", 1, "fCategorization")); methods.add(buildMethodInstance("unittests", "StatusTest", 2, "aStatus")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildTestNgFactoryMethodInstance("unittests")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "aChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "bChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "cChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "dChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "eChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "fChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "gChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "eChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "hChangeTest")); methods.add(buildMethodInstance("unittests", "ChangeTest", 3, "iChangeTest")); methods.add(buildMethodInstance("unittests", "IdentifierClassTest", 4, "aIdentifier")); methods.add(buildMethodInstance("unittests", "IdentifierClassTest", 4, "bIdentifier")); methods.add(buildMethodInstance("unittests", "StatisticsTest", 0, "aStatistics")); methods.add(buildMethodInstance("unittests", "StatisticsTest", 0, "bStatistics")); methods.add(buildMethodInstance("unittests", "StatisticsTest", 0, "cStatistics")); try { methods.sort(MethodInstance.SORT_BY_INDEX); } catch (IllegalArgumentException ex) { Assert.fail("Comparison method violates its general contract!"); } } private MethodInstance buildTestNgFactoryMethodInstance(String xmlTestName) { TestClassStub testClass = new TestClassStub(new XmlTestStub(xmlTestName), null); return new MethodInstance(new TestNGMethodStub(null, testClass)); } private MethodInstance buildMethodInstance( String xmlTestName, String xmlClassName, int xmlClassIndex, String methodName) { TestClassStub testClass = new TestClassStub( new XmlTestStub(xmlTestName), new XmlClassStub(xmlClassName, xmlClassIndex)); return new MethodInstance(new TestNGMethodStub(methodName, testClass)); } public static class XmlClassStub extends XmlClass { private int index; private String name; public XmlClassStub(String name, int index) { this.name = name; this.index = index; } @Override public String getName() { return name; } @Override public int getIndex() { return index; } @Override public List getIncludedMethods() { return Collections.emptyList(); } } public static class XmlTestStub extends XmlTest { private String name; public XmlTestStub(String name) { this.name = name; } @Override public String getName() { return name; } } public static class TestClassStub implements ITestClass { private XmlTest xmlTest; private XmlClass xmlClass; public TestClassStub(XmlTest xmlTest, XmlClass xmlClass) { this.xmlTest = xmlTest; this.xmlClass = xmlClass; } @Override public String getName() { return null; } @Override public XmlTest getXmlTest() { return xmlTest; } @Override public XmlClass getXmlClass() { return xmlClass; } @Override public String getTestName() { return null; } @Override public Class getRealClass() { return xmlClass.getSupportClass(); } @Override public void addInstance(Object instance) {} @Override public Object[] getInstances(boolean reuse) { return null; } @Override public long[] getInstanceHashCodes() { return null; } @Override public ITestNGMethod[] getTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeClassMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterClassMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeSuiteMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterSuiteMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeTestConfigurationMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterTestConfigurationMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeGroupsMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterGroupsMethods() { return new ITestNGMethod[0]; } } public static class TestNGMethodStub implements ITestNGMethod { private TestClassStub testClassStub; private String methodName; public TestNGMethodStub(String methodName, TestClassStub testClassStub) { this.methodName = methodName; this.testClassStub = testClassStub; } @Override public ITestNGMethod clone() { return (TestNGMethodStub) this; } @Override public Class getRealClass() { return null; } @Override public ITestClass getTestClass() { return testClassStub; } @Override public void setTestClass(ITestClass cls) {} @Override public String getMethodName() { return methodName; } @Override public Object getInstance() { return null; } @Override public long[] getInstanceHashCodes() { return null; } @Override public String[] getGroups() { return null; } @Override public String[] getGroupsDependedUpon() { return null; } @Override public String getMissingGroup() { return null; } @Override public void setMissingGroup(String group) {} @Override public String[] getBeforeGroups() { return null; } @Override public String[] getAfterGroups() { return null; } @Override public String[] getMethodsDependedUpon() { return null; } @Override public void addMethodDependedUpon(String methodName) {} @Override public boolean isTest() { return false; } @Override public boolean isBeforeMethodConfiguration() { return false; } @Override public boolean isAfterMethodConfiguration() { return false; } @Override public boolean isBeforeClassConfiguration() { return false; } @Override public boolean isAfterClassConfiguration() { return false; } @Override public boolean isBeforeSuiteConfiguration() { return false; } @Override public boolean isAfterSuiteConfiguration() { return false; } @Override public boolean isBeforeTestConfiguration() { return false; } @Override public boolean isAfterTestConfiguration() { return false; } @Override public boolean isBeforeGroupsConfiguration() { return false; } @Override public boolean isAfterGroupsConfiguration() { return false; } @Override public long getTimeOut() { return 0; } @Override public void setTimeOut(long timeOut) {} @Override public int getInvocationCount() { return 0; } @Override public void setInvocationCount(int count) {} @Override public void setMoreInvocationChecker(Callable moreInvocationChecker) {} @Override public boolean hasMoreInvocation() { return false; } @Override public int getSuccessPercentage() { return 0; } @Override public String getId() { return null; } @Override public void setId(String id) {} @Override public long getDate() { return 0; } @Override public void setDate(long date) {} @Override public boolean canRunFromClass(IClass testClass) { return false; } @Override public boolean isAlwaysRun() { return false; } @Override public int getThreadPoolSize() { return 0; } @Override public void setThreadPoolSize(int threadPoolSize) {} @Override public boolean getEnabled() { return false; } @Override public String getDescription() { return null; } @Override public void setDescription(String description) {} @Override public void incrementCurrentInvocationCount() {} @Override public int getCurrentInvocationCount() { return 0; } @Override public void setParameterInvocationCount(int n) {} @Override public int getParameterInvocationCount() { return 0; } @Override public IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return null; } @Override public Class getRetryAnalyzerClass() { return null; } @Override public void setRetryAnalyzerClass(Class clazz) {} @Override public boolean skipFailedInvocations() { return false; } @Override public void setSkipFailedInvocations(boolean skip) {} @Override public long getInvocationTimeOut() { return 0; } @Override public boolean ignoreMissingDependencies() { return false; } @Override public void setIgnoreMissingDependencies(boolean ignore) {} @Override public List getInvocationNumbers() { return null; } @Override public void setInvocationNumbers(List numbers) {} @Override public void addFailedInvocationNumber(int number) {} @Override public List getFailedInvocationNumbers() { return null; } @Override public int getPriority() { return 0; } @Override public void setPriority(int priority) {} @Override public int getInterceptedPriority() { return 0; } @Override public void setInterceptedPriority(int priority) {} @Override public XmlTest getXmlTest() { return null; } @Override public ConstructorOrMethod getConstructorOrMethod() { return null; } @Override public Map findMethodParameters(XmlTest test) { return null; } @Override public String getQualifiedName() { return getRealClass().getName() + "." + getMethodName(); } } } MethodMultiplyingInterceptor.java000066400000000000000000000023611475274123300343740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internalpackage org.testng.internal; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.TestListenerAdapter; import org.testng.collections.Lists; public class MethodMultiplyingInterceptor extends TestListenerAdapter implements IMethodInterceptor { private int originalMethodCount; private int multiplyCount = 0; @Override public List intercept(List methods, ITestContext context) { originalMethodCount = methods.size(); List newMethods = Lists.newArrayList(); for (IMethodInstance method : methods) { newMethods.add(method); TestClassSample.Occurs occurs = method .getMethod() .getConstructorOrMethod() .getMethod() .getAnnotation(TestClassSample.Occurs.class); if (occurs == null) { continue; } multiplyCount += occurs.times(); for (int i = 1; i <= occurs.times(); i++) { newMethods.add(method); } } return newMethods; } public int getOriginalMethodCount() { return originalMethodCount; } public int getMultiplyCount() { return multiplyCount; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/ParametersTest.java000066400000000000000000000022641475274123300315230ustar00rootroot00000000000000package org.testng.internal; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.testng.internal.Parameters.FilterOutInJectedTypesResult; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.xml.XmlTest; /** Provide test for package visible methods in org.testng.internal.Parameters */ public class ParametersTest { @Test @Parameters({"testdata"}) @SuppressWarnings("unused") public void filterOutInJectedTypesFromOptionalValuesTest( XmlTest xmlTest, @Optional("optionaltestdata") String testdata) { JDK15AnnotationFinder finder = new JDK15AnnotationFinder(null); Method curMethod = new Object() {}.getClass().getEnclosingMethod(); FilterOutInJectedTypesResult filterOutResult = org.testng.internal.Parameters.filterOutInJectedTypesFromOptionalValues( curMethod.getParameterTypes(), finder.findOptionalValues(curMethod)); Assert.assertEquals(filterOutResult.getOptionalValues()[0], "optionaltestdata"); Assert.assertEquals(filterOutResult.getParameterTypes()[0], String.class); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/TestClassSample.java000066400000000000000000000006561475274123300316320ustar00rootroot00000000000000package org.testng.internal; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.testng.annotations.Test; public class TestClassSample { @Test @Occurs(times = 2) public void testMethod() {} @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD}) public @interface Occurs { int times() default 1; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/TestListenerHelperTest.java000066400000000000000000000065571475274123300332160ustar00rootroot00000000000000package org.testng.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.testng.DataProviderHolder; import org.testng.ITestContext; import org.testng.ITestNGListenerFactory; import org.testng.ITestObjectFactory; import org.testng.TestNGException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.internal.listeners.DummyListenerFactory; import org.testng.internal.listeners.TestClassDoublingupAsListenerFactory; import org.testng.internal.listeners.TestClassWithCompositeListener; import org.testng.internal.listeners.TestClassWithListener; import org.testng.internal.listeners.TestClassWithMultipleListenerFactories; import org.testng.internal.paramhandler.FakeTestContext; import org.testng.xml.XmlClass; import test.SimpleBaseTest; public class TestListenerHelperTest { private IAnnotationFinder finder = new JDK15AnnotationFinder(new DefaultAnnotationTransformer()); @Test(dataProvider = "getTestData") public void testfindAllListeners(Class clazz, int expectedSize, boolean testFactoryClass) { TestListenerHelper.ListenerHolder holder = TestListenerHelper.findAllListeners(clazz, finder); assertThat(holder.getListenerClasses()).hasSize(expectedSize); if (testFactoryClass) { assertThat(holder.getListenerFactoryClass()).isNotNull(); } } @DataProvider(name = "getTestData") public Object[][] getTestData() { return new Object[][] { {TestClassWithListener.class, 1, false}, {SimpleBaseTest.class, 0, false}, {TestClassWithCompositeListener.class, 1, true} }; } @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = "\nFound more than one class implementing ITestNGListenerFactory:class " + "org.testng.internal.listeners.DummyListenerFactory and class org.testng.internal.listeners.DummyListenerFactory") public void testFindAllListenersErrorCondition() { TestListenerHelper.findAllListeners(TestClassWithMultipleListenerFactories.class, finder); } @Test(dataProvider = "getFactoryTestData") public void testCreateListenerFactory( Class testClazz, Class listenerClazz) { ITestContext ctx = new FakeTestContext(testClazz); ClassInfoMap classMap = new ClassInfoMap(Collections.singletonList(new XmlClass(testClazz))); ITestObjectFactory objectFactory = new ITestObjectFactory() {}; Configuration configuration = new Configuration(); configuration.setObjectFactory(objectFactory); TestNGClassFinder finder = new TestNGClassFinder( classMap, Maps.newHashMap(), configuration, ctx, new DataProviderHolder()); ITestNGListenerFactory factory = TestListenerHelper.createListenerFactory(objectFactory, finder, listenerClazz, ctx); assertThat(factory).isNotNull(); } @DataProvider(name = "getFactoryTestData") public Object[][] getFactoryTestData() { return new Object[][] { {TestClassWithListener.class, DummyListenerFactory.class}, {TestClassDoublingupAsListenerFactory.class, TestClassDoublingupAsListenerFactory.class} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/UtilsTest.java000066400000000000000000000022501475274123300305130ustar00rootroot00000000000000package org.testng.internal; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.testng.Assert.assertEquals; import static org.testng.internal.Utils.join; import java.util.List; import org.testng.annotations.Test; /** * Unit tests for {@link Utils}. * * @author Tomas Pollak */ public class UtilsTest { private static final char INVALID_CHAR = 0xFFFE; private static final char REPLACEMENT_CHAR = 0xFFFD; @Test public void escapeUnicode() { assertEquals(Utils.escapeUnicode("test"), "test"); assertEquals( Utils.escapeUnicode(String.valueOf(INVALID_CHAR)), String.valueOf(REPLACEMENT_CHAR)); } @Test public void createEmptyStringWhenJoiningEmptyListWithJoin() { List emptyList = emptyList(); assertEquals("", join(emptyList, ",")); } @Test public void joinTwoStringsWithJoinStrings() { List twoStrings = asList("one", "two"); assertEquals("one,two", Utils.join(twoStrings, ",")); } @Test public void createEmptyStringWhenJoiningEmptyListWithJoinStrings() { List emptyList = emptyList(); assertEquals("", Utils.join(emptyList, ",")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistener/000077500000000000000000000000001475274123300304045ustar00rootroot00000000000000FailingAfterClass.java000066400000000000000000000005131475274123300345100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistenerpackage org.testng.internal.conflistener; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class FailingAfterClass { @AfterClass public void failingAfterClass() { throw new RuntimeException("expected @AfterClass failure"); } @Test public void testBeforeFailingAfterClass() {} } FailingAfterSuite.java000066400000000000000000000004661475274123300345430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistenerpackage org.testng.internal.conflistener; import org.testng.annotations.AfterSuite; import org.testng.annotations.Test; public class FailingAfterSuite { @AfterSuite(alwaysRun = true) public void afterSuite() { throw new RuntimeException("Test exception"); } @Test public void dummytest() {} } FailingAfterTest.java000066400000000000000000000005441475274123300343660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistenerpackage org.testng.internal.conflistener; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; public class FailingAfterTest { @AfterTest(alwaysRun = true) public void afterTest() { throw new RuntimeException("Test exception"); } @AfterTest public void skippedAfterTest() {} @Test public void dummytest() {} } FailingBeforeClass.java000066400000000000000000000005201475274123300346470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistenerpackage org.testng.internal.conflistener; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class FailingBeforeClass { @BeforeClass public void failingBeforeClass() { throw new RuntimeException("expected @BeforeClass failure"); } @Test public void testAfterFailingBeforeClass() {} } FailingBeforeSuite.java000066400000000000000000000004501475274123300346750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistenerpackage org.testng.internal.conflistener; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class FailingBeforeSuite { @BeforeSuite public void beforeSuite() { throw new RuntimeException("Test exception"); } @Test public void dummytest() {} } FailingBeforeTest.java000066400000000000000000000006051475274123300345250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistenerpackage org.testng.internal.conflistener; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class FailingBeforeTest { @BeforeSuite public void passingBeforeSuite() {} @BeforeTest public void beforeTest() { throw new RuntimeException("Test exception"); } @Test public void dummytest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/conflistener/testng.xml000066400000000000000000000017071475274123300324370ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraph/000077500000000000000000000000001475274123300303575ustar00rootroot00000000000000EdgeWeightTestSample1.java000066400000000000000000000006241475274123300352440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class EdgeWeightTestSample1 { @Test( groups = {"g1"}, priority = 2) public void t1() {} @Test( groups = {"g2"}, dependsOnGroups = "g1", priority = 0) public void t2() {} @Test( groups = {"g2"}, dependsOnGroups = "g1", priority = 1) public void t3() {} } EdgeWeightTestSample2.java000066400000000000000000000011061475274123300352410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class EdgeWeightTestSample2 { @Test(priority = 1) public void t1() {} @Test( groups = {"group2"}, priority = 2) public void t2() {} @Test( groups = {"group3"}, dependsOnGroups = "group2", priority = 3) public void t3() {} @Test( groups = {"group4"}, dependsOnGroups = "group3", priority = 0) public void t4() {} @Test( groups = {"group4"}, dependsOnGroups = "group3", priority = 1) public void t5() {} } FactoryTestClassSample.java000066400000000000000000000011541475274123300355430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryTestClassSample { private String text; @Factory(dataProvider = "getData") public FactoryTestClassSample(String text) { this.text = text; } @Test public void testMethod() {} @Test public void anotherTestMethod() {} @Override public String toString() { return text; } @DataProvider(name = "getData") public static Object[][] getData() { return new Object[][] {{"one"}, {"two"}, {"three"}}; } } FakeTestClass.java000066400000000000000000000037571475274123300336530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.xml.XmlClass; import org.testng.xml.XmlTest; public class FakeTestClass implements ITestClass { private Class clazz; public FakeTestClass(Class clazz) { this.clazz = clazz; } @Override public ITestNGMethod[] getTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeClassMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterClassMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeSuiteMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterSuiteMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeTestConfigurationMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterTestConfigurationMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeGroupsMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterGroupsMethods() { return new ITestNGMethod[0]; } @Override public String getName() { return clazz.getName(); } @Override public XmlTest getXmlTest() { return null; } @Override public XmlClass getXmlClass() { return new XmlClass(clazz); } @Override public String getTestName() { return ""; } @Override public Class getRealClass() { return clazz; } @Override public Object[] getInstances(boolean create) { return new Object[0]; } @Override public long[] getInstanceHashCodes() { return new long[0]; } @Override public void addInstance(Object instance) {} } FakeWrappedFactoryMethod.java000066400000000000000000000006621475274123300360310ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.ITestNGMethod; import org.testng.internal.WrappedTestNGMethod; public class FakeWrappedFactoryMethod extends WrappedTestNGMethod { private Object instance; public FakeWrappedFactoryMethod(ITestNGMethod testNGMethod, Object instance) { super(testNGMethod); this.instance = instance; } @Override public Object getInstance() { return instance; } } HardDependencyTestClassSample.java000066400000000000000000000003221475274123300370050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class HardDependencyTestClassSample { @Test public void a() {} @Test(dependsOnMethods = "a") public void b() {} } HardDependencyViaGroupsTestClassSample.java000066400000000000000000000003621475274123300406510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class HardDependencyViaGroupsTestClassSample { @Test(groups = "master") public void a() {} @Test(dependsOnGroups = "master") public void b() {} } IndependentTestClassSample.java000066400000000000000000000002671475274123300363750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class IndependentTestClassSample { @Test public void a() {} @Test public void b() {} } LotsOfEdgesTest.java000066400000000000000000000140041475274123300341600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; // https://github.com/cbeust/testng/issues/1710 public class LotsOfEdgesTest { @Test( priority = 1, groups = {"group1"}) void test_1_1() {} @Test( priority = 2, groups = {"group1"}) void test_1_2() {} @Test( priority = 3, groups = {"group1"}) void test_1_3() {} @Test( priority = 1, groups = {"group1"}) void test_1_4() {} @Test( priority = 2, groups = {"group1"}) void test_1_5() {} @Test( priority = 6, groups = {"group1"}) void test_1_6() {} @Test( priority = 7, groups = {"group1"}) void test_1_7() {} @Test( priority = 8, groups = {"group1"}) void test_1_8() {} @Test( priority = 9, groups = {"group1"}) void test_1_9() {} @Test( priority = 10, groups = {"group1"}) void test_1_10() {} @Test( priority = 1, groups = {"group1"}) void test_2_1() {} @Test( priority = 2, groups = {"group1"}) void test_2_2() {} @Test( priority = 3, groups = {"group1"}) void test_2_3() {} @Test( priority = 1, groups = {"group1"}) void test_2_4() {} @Test( priority = 2, groups = {"group1"}) void test_2_5() {} @Test( priority = 6, groups = {"group1"}) void test_2_6() {} @Test( priority = 7, groups = {"group1"}) void test_2_7() {} @Test( priority = 8, groups = {"group1"}) void test_2_8() {} @Test( priority = 9, dependsOnGroups = {"group1"}) void test_3_9() {} @Test( priority = 10, dependsOnGroups = {"group1"}) void test_3_10() {} @Test( priority = 1, dependsOnGroups = {"group1"}) void test_4_1() {} @Test( priority = 2, dependsOnGroups = {"group1"}) void test_4_2() {} @Test( priority = 3, dependsOnGroups = {"group1"}) void test_4_3() {} @Test( priority = 1, dependsOnGroups = {"group1"}) void test_4_4() {} @Test( priority = 2, dependsOnGroups = {"group1"}) void test_4_5() {} @Test( priority = 6, dependsOnGroups = {"group1"}) void test_4_6() {} @Test( priority = 7, dependsOnGroups = {"group1"}) void test_4_7() {} @Test( priority = 8, dependsOnGroups = {"group1"}) void test_4_8() {} @Test( priority = 9, dependsOnGroups = {"group1"}) void test_4_9() {} @Test( priority = 10, dependsOnGroups = {"group1"}) void test_4_10() {} @Test( priority = 1, dependsOnGroups = {"group1"}) void test_5_1() {} @Test( priority = 2, dependsOnGroups = {"group1"}) void test_5_2() {} @Test( priority = 3, dependsOnGroups = {"group1"}) void test_5_3() {} @Test( priority = 1, dependsOnGroups = {"group1"}) void test_5_4() {} @Test( priority = 2, dependsOnGroups = {"group1"}) void test_5_5() {} @Test( priority = 6, dependsOnGroups = {"group1"}) void test_5_6() {} @Test( priority = 7, dependsOnGroups = {"group1"}) void test_5_7() {} @Test( priority = 8, dependsOnGroups = {"group1"}) void test_5_8() {} @Test( priority = 9, dependsOnGroups = {"group1"}) void test_5_9() {} @Test( priority = 10, dependsOnGroups = {"group1"}) void test_5_10() {} @Test(priority = 9) void test_2_9() {} @Test(priority = 10) void test_2_10() {} @Test(priority = 1) void test_3_1() {} @Test(priority = 2) void test_3_2() {} @Test(priority = 3) void test_3_3() {} @Test(priority = 1) void test_3_4() {} @Test(priority = 2) void test_3_5() {} @Test(priority = 6) void test_3_6() {} @Test(priority = 7) void test_3_7() {} @Test(priority = 8) void test_3_8() {} @Test(priority = 1) void test_6_1() {} @Test(priority = 2) void test_6_2() {} @Test(priority = 3) void test_6_3() {} @Test(priority = 1) void test_6_4() {} @Test(priority = 2) void test_6_5() {} @Test(priority = 6) void test_6_6() {} @Test(priority = 7) void test_6_7() {} @Test(priority = 8) void test_6_8() {} @Test(priority = 9) void test_6_9() {} @Test(priority = 10) void test_6_10() {} @Test(priority = 1) void test_7_1() {} @Test(priority = 2) void test_7_2() {} @Test(priority = 3) void test_7_3() {} @Test(priority = 1) void test_7_4() {} @Test(priority = 2) void test_7_5() {} @Test(priority = 6) void test_7_6() {} @Test(priority = 7) void test_7_7() {} @Test(priority = 8) void test_7_8() {} @Test(priority = 9) void test_7_9() {} @Test(priority = 10) void test_7_10() {} @Test(priority = 1) void test_8_1() {} @Test(priority = 2) void test_8_2() {} @Test(priority = 3) void test_8_3() {} @Test(priority = 1) void test_8_4() {} @Test(priority = 2) void test_8_5() {} @Test(priority = 6) void test_8_6() {} @Test(priority = 7) void test_8_7() {} @Test(priority = 8) void test_8_8() {} @Test(priority = 9) void test_8_9() {} @Test(priority = 10) void test_8_10() {} @Test(priority = 1) void test_9_1() {} @Test(priority = 2) void test_9_2() {} @Test(priority = 3) void test_9_3() {} @Test(priority = 1) void test_9_4() {} @Test(priority = 2) void test_9_5() {} @Test(priority = 6) void test_9_6() {} @Test(priority = 7) void test_9_7() {} @Test(priority = 8) void test_9_8() {} @Test(priority = 9) void test_9_9() {} @Test(priority = 10) void test_9_10() {} @Test(priority = 1) void test_10_1() {} @Test(priority = 2) void test_10_2() {} @Test(priority = 3) void test_10_3() {} @Test(priority = 1) void test_10_4() {} @Test(priority = 2) void test_10_5() {} @Test(priority = 6) void test_10_6() {} @Test(priority = 7) void test_10_7() {} @Test(priority = 8) void test_10_8() {} @Test(priority = 9) void test_10_9() {} @Test(priority = 10) void test_10_10() {} } SequentialClassA.java000066400000000000000000000003461475274123300343470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class SequentialClassA { @Test public void testMethodOneSequentialClassA() {} @Test public void testMethodTwoSequentialClassA() {} } SequentialClassB.java000066400000000000000000000003461475274123300343500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class SequentialClassB { @Test public void testMethodOneSequentialClassB() {} @Test public void testMethodTwoSequentialClassB() {} } SoftDependencyTestClassSample.java000066400000000000000000000003261475274123300370460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraphpackage org.testng.internal.dynamicgraph; import org.testng.annotations.Test; public class SoftDependencyTestClassSample { @Test(priority = 1) public void a() {} @Test(priority = 2) public void b() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraph/testpackage/000077500000000000000000000000001475274123300326525ustar00rootroot00000000000000PackageTestClassA.java000066400000000000000000000002751475274123300367240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraph/testpackagepackage org.testng.internal.dynamicgraph.testpackage; import org.testng.annotations.Test; public class PackageTestClassA { @Test public void a1() {} @Test public void a2() {} } PackageTestClassBAbstract.java000066400000000000000000000002111475274123300403770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraph/testpackagepackage org.testng.internal.dynamicgraph.testpackage; public abstract class PackageTestClassBAbstract { public void neverMind() {} } PackageTestClassBB.java000066400000000000000000000002761475274123300370300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/dynamicgraph/testpackagepackage org.testng.internal.dynamicgraph.testpackage; import org.testng.annotations.Test; public class PackageTestClassBB { @Test public void b1() {} @Test public void b2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/invokers/000077500000000000000000000000001475274123300275515ustar00rootroot00000000000000ParameterHandlerTest.java000066400000000000000000000065121475274123300344170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/invokerspackage org.testng.internal.invokers; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import org.testng.DataProviderHolder; import org.testng.IDataProviderListener; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestObjectFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.internal.paramhandler.DataDrivenSampleTestClass; import org.testng.internal.paramhandler.ExceptionThrowingDataDrivenSampleTestClass; import org.testng.internal.paramhandler.FakeTestContext; import org.testng.internal.paramhandler.FakeTestNGMethod; import org.testng.internal.paramhandler.ParameterizedSampleTestClass; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class ParameterHandlerTest extends SimpleBaseTest { private ParameterHandler handler; @BeforeClass public void beforeClass() { Collection listeners = Collections.emptyList(); IAnnotationFinder finder = new JDK15AnnotationFinder(new DefaultAnnotationTransformer()); handler = new ParameterHandler(new ITestObjectFactory() {}, finder, new DataProviderHolder(), 0); } @Test public void testCreateParameters() { ITestNGMethod testNGMethod = new FakeTestNGMethod(ParameterizedSampleTestClass.class, "testMethod"); runTest(testNGMethod, ParameterHolder.ParameterOrigin.ORIGIN_XML); } @Test public void testCreateParametersUsingDataProvider() { XmlTest xmlTest = createXmlTest("suite", "test"); ITestNGMethod testNGMethod = new FakeTestNGMethod(DataDrivenSampleTestClass.class, "testMethod", xmlTest); runTest(testNGMethod, ParameterHolder.ParameterOrigin.ORIGIN_DATA_PROVIDER); } @Test public void testCreateParametersUsingDataProviderNegativeCase() { XmlTest xmlTest = createXmlTest("suite", "test"); Class clazz = ExceptionThrowingDataDrivenSampleTestClass.class; ITestNGMethod testNGMethod = new FakeTestNGMethod(clazz, "testMethod", xmlTest); ParameterHandler.ParameterBag params = invokeParameterCreation(testNGMethod); assertThat(params.parameterHolder).isNull(); assertThat(params.errorResult).isNotNull(); assertThat(params.errorResult.getThrowable()) .hasCauseInstanceOf(UnsupportedOperationException.class); } private void runTest(ITestNGMethod testNGMethod, ParameterHolder.ParameterOrigin origin) { ParameterHandler.ParameterBag params = invokeParameterCreation(testNGMethod); assertThat(params.parameterHolder).isNotNull(); assertThat(params.parameterHolder.origin).isEqualByComparingTo(origin); Iterator iterators = params.parameterHolder.parameters; assertThat(iterators).containsAll(Collections.singletonList(new Object[] {"bar"})); } private ParameterHandler.ParameterBag invokeParameterCreation(ITestNGMethod method) { ITestContext context = new FakeTestContext(method.getRealClass()); Map map = Maps.newHashMap(); return handler.createParameters(method, map, map, context); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1339/000077500000000000000000000000001475274123300273615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1339/BabyPanda.java000066400000000000000000000010651475274123300320470ustar00rootroot00000000000000package org.testng.internal.issue1339; public class BabyPanda extends LittlePanda { String name; @Override public String toString() { return "BabyPanda{" + "name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BabyPanda babyPanda = (BabyPanda) o; return name != null ? name.equals(babyPanda.name) : babyPanda.name == null; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1339/GrandpaBear.java000066400000000000000000000002441475274123300323720ustar00rootroot00000000000000package org.testng.internal.issue1339; public class GrandpaBear { private void secretMethod() {} public void announcer() {} public void inheritable() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1339/LittlePanda.java000066400000000000000000000001251475274123300324230ustar00rootroot00000000000000package org.testng.internal.issue1339; public class LittlePanda extends PapaBear {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1339/PapaBear.java000066400000000000000000000003231475274123300316750ustar00rootroot00000000000000package org.testng.internal.issue1339; public class PapaBear extends GrandpaBear { private void secretMethod(String foo) {} public void announcer(String foo) {} public void inheritable(String foo) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1456/000077500000000000000000000000001475274123300273615ustar00rootroot00000000000000TestClassSample.java000066400000000000000000000004441475274123300332160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue1456package org.testng.internal.issue1456; import org.testng.ITest; public class TestClassSample implements ITest { private String testname; public TestClassSample(String testname) { this.testname = testname; } @Override public String getTestName() { return testname; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue2195/000077500000000000000000000000001475274123300273625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue2195/BaseClass.java000066400000000000000000000005571475274123300320740ustar00rootroot00000000000000package org.testng.internal.issue2195; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class BaseClass { @BeforeMethod( alwaysRun = true, dependsOnMethods = {"dummyDependsOnMethod"}) public void dummyMethod() {} @BeforeMethod public void dummyDependsOnMethod() {} @Test public void dummyTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/issue2195/TestClass.java000066400000000000000000000002571475274123300321360ustar00rootroot00000000000000package org.testng.internal.issue2195; import org.testng.annotations.Test; @Test(groups = "issue2195") public class TestClass extends BaseClass { public TestClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listeners/000077500000000000000000000000001475274123300277215ustar00rootroot00000000000000DummyListenerFactory.java000066400000000000000000000007261475274123300346430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listenerspackage org.testng.internal.listeners; import org.testng.IExecutionListener; import org.testng.ITestNGListener; import org.testng.ITestNGListenerFactory; public class DummyListenerFactory implements ITestNGListenerFactory, IExecutionListener { @Override public ITestNGListener createListener(Class listenerClass) { return this; } @Override public void onExecutionStart() {} @Override public void onExecutionFinish() {} } EmptyExecutionListener.java000066400000000000000000000003671475274123300352030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listenerspackage org.testng.internal.listeners; import org.testng.IExecutionListener; public class EmptyExecutionListener implements IExecutionListener { @Override public void onExecutionStart() {} @Override public void onExecutionFinish() {} } TestClassDoublingupAsListenerFactory.java000066400000000000000000000006461475274123300377730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listenerspackage org.testng.internal.listeners; import org.testng.ITestNGListener; import org.testng.ITestNGListenerFactory; import org.testng.annotations.Test; public class TestClassDoublingupAsListenerFactory implements ITestNGListenerFactory { @Override public ITestNGListener createListener(Class listenerClass) { return new EmptyExecutionListener(); } @Test public void test() {} } TestClassWithCompositeListener.java000066400000000000000000000003631475274123300366410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listenerspackage org.testng.internal.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(DummyListenerFactory.class) public class TestClassWithCompositeListener { @Test public void testMethod() {} } TestClassWithListener.java000066400000000000000000000002411475274123300347510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listenerspackage org.testng.internal.listeners; import org.testng.annotations.Listeners; @Listeners(EmptyExecutionListener.class) public class TestClassWithListener {} TestClassWithMultipleListenerFactories.java000066400000000000000000000003161475274123300403300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listenerspackage org.testng.internal.listeners; import org.testng.annotations.Listeners; @Listeners({DummyListenerFactory.class, DummyListenerFactory.class}) public class TestClassWithMultipleListenerFactories {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listeners/parameterindex/000077500000000000000000000000001475274123300327315ustar00rootroot00000000000000ParameterIndexListenerTest.java000066400000000000000000000005471475274123300410010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listeners/parameterindexpackage org.testng.internal.listeners.parameterindex; import org.testng.TestNG; import org.testng.annotations.Test; public class ParameterIndexListenerTest { @Test public void listenerShouldReceiveRightParameterIndexTest() { TestNG testng = new TestNG(); testng.setTestClasses(new Class[] {TestWithProviderTest.class}); testng.run(); } } ParameterIndexTestListener.java000066400000000000000000000012361475274123300407750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listeners/parameterindexpackage org.testng.internal.listeners.parameterindex; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.internal.TestResult; public class ParameterIndexTestListener implements ITestListener { private List indexes = new ArrayList<>(); @Override public void onTestSuccess(ITestResult testResult) { indexes.add(((TestResult) testResult).getParameterIndex()); } @Override public void onFinish(ITestContext testContext) { assertThat(indexes).contains(0, 1, 2); } } TestWithProviderTest.java000066400000000000000000000010071475274123300376410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/listeners/parameterindexpackage org.testng.internal.listeners.parameterindex; import static org.testng.AssertJUnit.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ParameterIndexTestListener.class) public class TestWithProviderTest { @DataProvider public Object[] integerValues() { return new Object[] {1, 4, 4}; } @Test(dataProvider = "integerValues") public void ShouldBeLessThan5(int value) { assertTrue(value < 5); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamples/000077500000000000000000000000001475274123300277035ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamples/AbstractMoves.java000066400000000000000000000002501475274123300333200ustar00rootroot00000000000000package org.testng.internal.misamples; public abstract class AbstractMoves implements IDance { @Override public void dance() {} public abstract void walk(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamples/Batman.java000066400000000000000000000003341475274123300317500ustar00rootroot00000000000000package org.testng.internal.misamples; public class Batman implements SuperHeroCapabilities { @Override public void fly() {} @Override public void liftWeights() {} @Override public void yellSlogan() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamples/IDance.java000066400000000000000000000001371475274123300316720ustar00rootroot00000000000000package org.testng.internal.misamples; public interface IDance { default void dance() {} } JohnTravoltaMoves.java000066400000000000000000000002061475274123300341120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamplespackage org.testng.internal.misamples; public class JohnTravoltaMoves extends AbstractMoves { @Override public void walk() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamples/MickJagger.java000066400000000000000000000001741475274123300325530ustar00rootroot00000000000000package org.testng.internal.misamples; public class MickJagger implements IDance { @Override public void dance() {} } SuperHeroCapabilities.java000066400000000000000000000002311475274123300347110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/misamplespackage org.testng.internal.misamples; public interface SuperHeroCapabilities { default void yellSlogan() {} void fly(); void liftWeights(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/objects/000077500000000000000000000000001475274123300273425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/objects/GuiceHelperTest.java000066400000000000000000000036361475274123300332510ustar00rootroot00000000000000package org.testng.internal.objects; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import org.testng.Assert; import org.testng.IInjectorFactory; import org.testng.ITest; import org.testng.ITestObjectFactory; import org.testng.SampleIModule; import org.testng.annotations.Guice; import org.testng.annotations.Test; import org.testng.internal.ClassImpl; import org.testng.internal.paramhandler.FakeTestContext; import test.guice.FakeInjector; @Guice public final class GuiceHelperTest { private final GuiceHelper guiceHelper = new GuiceHelper(new FakeTestContext()); @Test(description = "GITHUB-2273") public void getInjector_spiModule_injectorHasModule() { MockInjector injector = (MockInjector) guiceHelper.getInjector(new MockClass(), new MockInjectorFactory()); assertNotNull(injector); Module[] modules = injector.getModules(); assertNotNull(modules); assertEquals(modules.length, 1); Assert.assertEquals(modules[0], new SampleIModule().getModule()); } private static final class MockInjectorFactory implements IInjectorFactory { @Override @SuppressWarnings("deprecation") public Injector getInjector(Stage stage, Module... modules) { return new MockInjector(modules); } } private static final class MockInjector extends FakeInjector { private final Module[] modules; public MockInjector(Module[] modules) { this.modules = modules; } public Module[] getModules() { return modules; } } private static final class MockClass extends ClassImpl { public MockClass() { super( new FakeTestContext(), GuiceHelperTest.class, null, (ITest) () -> "GITHUB-2273", null, null, new ITestObjectFactory() {}); } } } InstanceCreatorTest.java000066400000000000000000000025611475274123300340560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/objectspackage org.testng.internal.objects; import java.util.Map; import org.testng.Assert; import org.testng.IClass; import org.testng.ITest; import org.testng.ITestObjectFactory; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.internal.issue1456.TestClassSample; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class InstanceCreatorTest { private static final String GITHUB_1456 = "GITHUB-1456"; @Test(description = GITHUB_1456) public void testCreateInstance1WithOneArgStringParamForConstructor() { Class declaringClass = TestClassSample.class; Map, IClass> classes = Maps.newHashMap(); XmlTest xmlTest = new XmlTest(new XmlSuite()); xmlTest.setName(GITHUB_1456); IAnnotationFinder finder = new JDK15AnnotationFinder(new DefaultAnnotationTransformer()); ITestObjectFactory objectFactory = new ObjectFactoryImpl(); Object object = SimpleObjectDispenser.createInstance( declaringClass, classes, xmlTest, finder, objectFactory, false, ""); Assert.assertTrue(object instanceof ITest); Assert.assertEquals(((ITest) object).getTestName(), GITHUB_1456); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandler/000077500000000000000000000000001475274123300303475ustar00rootroot00000000000000DataDrivenSampleTestClass.java000066400000000000000000000006471475274123300361530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandlerpackage org.testng.internal.paramhandler; import org.assertj.core.api.Assertions; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataDrivenSampleTestClass { @Test(dataProvider = "dp") public void testMethod(String i) { Assertions.assertThat(i).isNotEmpty(); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{"bar"}}; } } ExceptionThrowingDataDrivenSampleTestClass.java000066400000000000000000000007311475274123300415460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandlerpackage org.testng.internal.paramhandler; import org.assertj.core.api.Assertions; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ExceptionThrowingDataDrivenSampleTestClass { @Test(dataProvider = "dp") public void testMethod(String i) { Assertions.assertThat(i).isNotEmpty(); } @DataProvider(name = "dp") public Object[][] getData() { throw new UnsupportedOperationException("unsupported-operation"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandler/FakeSuite.java000066400000000000000000000055451475274123300331030ustar00rootroot00000000000000package org.testng.internal.paramhandler; import com.google.inject.Injector; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.IInvokedMethod; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestNGListener; import org.testng.ITestNGMethod; import org.testng.ITestObjectFactory; import org.testng.SuiteRunState; import org.testng.collections.Maps; import org.testng.collections.Sets; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class FakeSuite implements ISuite { private XmlTest xmlTest; public FakeSuite(XmlTest xmlTest) { this.xmlTest = xmlTest; } @Override public String getName() { return ""; } @Override public Map getResults() { return Maps.newHashMap(); } @Override public ITestObjectFactory getObjectFactory() { return new ITestObjectFactory() {}; } @Override public String getOutputDirectory() { return ""; } @Override public String getParallel() { return ""; } @Override public String getParentModule() { return ""; } @Override public String getGuiceStage() { return ""; } @Override public String getParameter(String parameterName) { return ""; } @Override public Map> getMethodsByGroups() { return Maps.newHashMap(); } @Override public List getAllInvokedMethods() { return Collections.emptyList(); } @Override public Collection getExcludedMethods() { return Collections.emptyList(); } @Override public void run() {} @Override public String getHost() { return ""; } @Override public SuiteRunState getSuiteState() { return new SuiteRunState(); } @Override public IAnnotationFinder getAnnotationFinder() { return new JDK15AnnotationFinder(new DefaultAnnotationTransformer()); } @Override public XmlSuite getXmlSuite() { return this.xmlTest.getSuite(); } @Override public void addListener(ITestNGListener listener) {} @Override public Injector getParentInjector() { return null; } @Override public void setParentInjector(Injector injector) {} @Override public List getAllMethods() { return Collections.emptyList(); } @Override public Object getAttribute(String name) { return new Object(); } @Override public void setAttribute(String name, Object value) {} @Override public Set getAttributeNames() { return Sets.newHashSet(); } @Override public Object removeAttribute(String name) { return new Object(); } } FakeTestContext.java000066400000000000000000000053111475274123300342060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandlerpackage org.testng.internal.paramhandler; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.Set; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.collections.Maps; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class FakeTestContext implements ITestContext { private final XmlTest xmlTest; private final ISuite suite; public FakeTestContext(Class clazz) { this(new Class[] {clazz}); } public FakeTestContext(Class... classes) { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("xml_suite"); xmlTest = new XmlTest(xmlSuite); for (Class clazz : classes) { xmlTest.getXmlClasses().add(new XmlClass(clazz)); } Map map = Maps.newHashMap(); map.put("foo", "bar"); xmlTest.setParameters(map); suite = new FakeSuite(xmlTest); } @Override public String getName() { return null; } @Override public Date getStartDate() { return null; } @Override public Date getEndDate() { return null; } @Override public IResultMap getPassedTests() { return null; } @Override public IResultMap getSkippedTests() { return null; } @Override public IResultMap getFailedButWithinSuccessPercentageTests() { return null; } @Override public IResultMap getFailedTests() { return null; } @Override public String[] getIncludedGroups() { return new String[0]; } @Override public String[] getExcludedGroups() { return new String[0]; } @Override public String getOutputDirectory() { return null; } @Override public ISuite getSuite() { return suite; } @Override public ITestNGMethod[] getAllTestMethods() { return new ITestNGMethod[0]; } @Override public String getHost() { return null; } @Override public Collection getExcludedMethods() { return Collections.emptyList(); } @Override public IResultMap getPassedConfigurations() { return null; } @Override public IResultMap getSkippedConfigurations() { return null; } @Override public IResultMap getFailedConfigurations() { return null; } @Override public XmlTest getCurrentXmlTest() { return xmlTest; } @Override public Object getAttribute(String name) { return null; } @Override public void setAttribute(String name, Object value) {} @Override public Set getAttributeNames() { return Collections.emptySet(); } @Override public Object removeAttribute(String name) { return null; } } FakeTestNGMethod.java000066400000000000000000000144531475274123300342360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandlerpackage org.testng.internal.paramhandler; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.testng.IClass; import org.testng.IRetryAnalyzer; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.internal.ConstructorOrMethod; import org.testng.internal.MethodInstanceTest; import org.testng.internal.reflect.ReflectionHelper; import org.testng.xml.XmlClass; import org.testng.xml.XmlTest; public class FakeTestNGMethod implements ITestNGMethod { private final ConstructorOrMethod consMethod; private Class clazz; private XmlTest xmlTest; public FakeTestNGMethod(Class clazz, String methodName) { this(clazz, methodName, null); } public FakeTestNGMethod(Class clazz, String methodName, XmlTest xmlTest) { ConstructorOrMethod temp = null; Method[] methods = ReflectionHelper.getLocalMethods(clazz); for (Method method : methods) { if (method.getName().equalsIgnoreCase(methodName)) { temp = new ConstructorOrMethod(method); break; } } this.xmlTest = xmlTest; this.clazz = clazz; this.consMethod = temp; } @Override public Class getRealClass() { return clazz; } @Override public ITestClass getTestClass() { return new MethodInstanceTest.TestClassStub(this.xmlTest, new XmlClass(this.clazz)); } @Override public void setTestClass(ITestClass cls) {} @Override public String getMethodName() { return null; } @Override public Object getInstance() { return null; } @Override public long[] getInstanceHashCodes() { return new long[0]; } @Override public String[] getGroups() { return new String[0]; } @Override public String[] getGroupsDependedUpon() { return new String[0]; } @Override public String getMissingGroup() { return null; } @Override public void setMissingGroup(String group) {} @Override public String[] getBeforeGroups() { return new String[0]; } @Override public String[] getAfterGroups() { return new String[0]; } @Override public String[] getMethodsDependedUpon() { return new String[0]; } @Override public void addMethodDependedUpon(String methodName) {} @Override public boolean isTest() { return false; } @Override public boolean isBeforeMethodConfiguration() { return false; } @Override public boolean isAfterMethodConfiguration() { return false; } @Override public boolean isBeforeClassConfiguration() { return false; } @Override public boolean isAfterClassConfiguration() { return false; } @Override public boolean isBeforeSuiteConfiguration() { return false; } @Override public boolean isAfterSuiteConfiguration() { return false; } @Override public boolean isBeforeTestConfiguration() { return false; } @Override public boolean isAfterTestConfiguration() { return false; } @Override public boolean isBeforeGroupsConfiguration() { return false; } @Override public boolean isAfterGroupsConfiguration() { return false; } @Override public long getTimeOut() { return 0; } @Override public void setTimeOut(long timeOut) {} @Override public int getInvocationCount() { return 0; } @Override public void setInvocationCount(int count) {} @Override public int getSuccessPercentage() { return 0; } @Override public String getId() { return null; } @Override public void setId(String id) {} @Override public long getDate() { return 0; } @Override public void setDate(long date) {} @Override public boolean canRunFromClass(IClass testClass) { return false; } @Override public boolean isAlwaysRun() { return false; } @Override public int getThreadPoolSize() { return 0; } @Override public void setThreadPoolSize(int threadPoolSize) {} @Override public boolean getEnabled() { return false; } @Override public String getDescription() { return null; } @Override public void setDescription(String description) {} @Override public void incrementCurrentInvocationCount() {} @Override public int getCurrentInvocationCount() { return 0; } @Override public void setParameterInvocationCount(int n) {} @Override public int getParameterInvocationCount() { return 0; } @Override public void setMoreInvocationChecker(Callable moreInvocationChecker) {} @Override public boolean hasMoreInvocation() { return false; } @Override public ITestNGMethod clone() { throw new UnsupportedOperationException("Not supported"); } @Override public IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return null; } @Override public Class getRetryAnalyzerClass() { return null; } @Override public void setRetryAnalyzerClass(Class clazz) {} @Override public boolean skipFailedInvocations() { return false; } @Override public void setSkipFailedInvocations(boolean skip) {} @Override public long getInvocationTimeOut() { return 0; } @Override public boolean ignoreMissingDependencies() { return false; } @Override public void setIgnoreMissingDependencies(boolean ignore) {} @Override public List getInvocationNumbers() { return Collections.emptyList(); } @Override public void setInvocationNumbers(List numbers) {} @Override public void addFailedInvocationNumber(int number) {} @Override public List getFailedInvocationNumbers() { return Collections.emptyList(); } @Override public int getPriority() { return 0; } @Override public void setPriority(int priority) {} @Override public int getInterceptedPriority() { return 0; } @Override public void setInterceptedPriority(int priority) {} @Override public XmlTest getXmlTest() { return null; } @Override public ConstructorOrMethod getConstructorOrMethod() { return consMethod; } @Override public Map findMethodParameters(XmlTest test) { return test.getLocalParameters(); } @Override public String getQualifiedName() { return null; } } ParameterizedSampleTestClass.java000066400000000000000000000003551475274123300367220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/internal/paramhandlerpackage org.testng.internal.paramhandler; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ParameterizedSampleTestClass { @Test @Parameters("foo") public void testMethod(String foo) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/000077500000000000000000000000001475274123300265725ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/JarCreator.java000066400000000000000000000035561475274123300315020ustar00rootroot00000000000000package org.testng.jarfileutils; import java.io.File; import java.io.IOException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.testng.jarfileutils.org.testng.SampleTest1; import org.testng.jarfileutils.org.testng.SampleTest2; import org.testng.jarfileutils.org.testng.SampleTest3; import org.testng.jarfileutils.org.testng.SampleTest4; import org.testng.jarfileutils.org.testng.SampleTest5; public class JarCreator { private static final String PREFIX = "testng"; private static final String ARCHIVE_NAME = "testng-tests.jar"; public static File generateJar() throws IOException { return generateJar(getTestClasses(), getResources(), PREFIX, ARCHIVE_NAME); } public static File generateJar(Class[] classes) throws IOException { return generateJar(classes, new String[] {}, PREFIX, ARCHIVE_NAME); } public static File generateJar( Class[] classes, String[] resources, String prefix, String archiveName) throws IOException { File jarFile = File.createTempFile(prefix, ".jar"); JavaArchive archive = ShrinkWrap.create(JavaArchive.class, archiveName).addClasses(classes); for (String resource : resources) { archive = archive.addAsResource(resource); } archive.as(ZipExporter.class).exportTo(jarFile, true); return jarFile; } private static Class[] getTestClasses() { return new Class[] { SampleTest1.class, SampleTest2.class, SampleTest3.class, SampleTest4.class, SampleTest5.class }; } private static String[] getResources() { return new String[] { "jarfileutils/testng-tests.xml", "jarfileutils/child.xml", "jarfileutils/child/child.xml", "jarfileutils/child/childofchild/childofchild.xml", "jarfileutils/childofchild/childofchild.xml" }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/000077500000000000000000000000001475274123300273615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/testng/000077500000000000000000000000001475274123300306655ustar00rootroot00000000000000SampleTest1.java000066400000000000000000000002621475274123300336130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/testngpackage org.testng.jarfileutils.org.testng; import org.testng.annotations.Test; public class SampleTest1 { @Test public void test1() {} @Test public void test2() {} } SampleTest2.java000066400000000000000000000002621475274123300336140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/testngpackage org.testng.jarfileutils.org.testng; import org.testng.annotations.Test; public class SampleTest2 { @Test public void test1() {} @Test public void test2() {} } SampleTest3.java000066400000000000000000000002621475274123300336150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/testngpackage org.testng.jarfileutils.org.testng; import org.testng.annotations.Test; public class SampleTest3 { @Test public void test1() {} @Test public void test2() {} } SampleTest4.java000066400000000000000000000002621475274123300336160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/testngpackage org.testng.jarfileutils.org.testng; import org.testng.annotations.Test; public class SampleTest4 { @Test public void test1() {} @Test public void test2() {} } SampleTest5.java000066400000000000000000000002621475274123300336170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/jarfileutils/org/testngpackage org.testng.jarfileutils.org.testng; import org.testng.annotations.Test; public class SampleTest5 { @Test public void test1() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/log4testng/000077500000000000000000000000001475274123300261675ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/log4testng/LoggerTest.java000066400000000000000000000221561475274123300311170ustar00rootroot00000000000000package org.testng.log4testng; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Properties; import org.testng.Assert; import org.testng.annotations.Test; public class LoggerTest { /** * This method is for debugging purpose only. * * @param pProperties a properties bundle initialised as log4testng property file would be. * @param pOut the standard output stream to be used for logging. * @param pErr the standard error stream to be used for logging. */ private static synchronized void testInitialize( Properties pProperties, PrintStream pOut, PrintStream pErr) { Logger.initialized = true; Logger.loggers.clear(); Logger.rootLoggerLevel = Logger.WARN; Logger.debug = false; Logger.out = pOut; Logger.err = pErr; Logger.checkProperties(pProperties); } /** Makes sure the default debug value is false. */ @Test void testDebugDefault() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.rootLogger", "WARN"); testInitialize(props, out2, err2); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); } /** Makes sure the debug value can be turned on and actualls logs something. */ @Test void testDebugOn() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.debug", "true"); props.put("log4testng.rootLogger", "WARN"); testInitialize(props, out2, err2); Assert.assertTrue(out1.toString().startsWith("[log4testng][debug]")); Assert.assertEquals(err1.toString(), ""); } /** Makes sure the debug value can be turned off and logs nothing. */ @Test void testDebugOff() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.debug", "false"); props.put("log4testng.rootLogger", "WARN"); testInitialize(props, out2, err2); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); } /** Makes sure an illegal debug value throws an exception. */ @Test void testDebugError() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.debug", "unknown"); props.put("log4testng.rootLogger", "WARN"); try { testInitialize(props, out2, err2); throw new RuntimeException("failure"); } catch (IllegalArgumentException pEx) { // Normal case Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); } } /** * Tests that the root logger's default level is WARN and that loggers do not log bellow this * level and do log in the correct stream for levels equal to and above WARN. */ @Test void testRootLoggerDefault() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); testInitialize(props, out2, err2); Logger strLogger = Logger.getLogger(String.class); strLogger.trace("trace should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.debug("debug should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.info("info should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.warn("warn should appear"); int outlength = out1.toString().length(); Assert.assertTrue(out1.toString().startsWith("[java.lang.String] [WARN] warn should appear")); Assert.assertEquals(err1.toString(), ""); strLogger.error("error should appear"); Assert.assertEquals(out1.toString().length(), outlength); Assert.assertTrue(err1.toString().startsWith("[java.lang.String] [ERROR] error should appear")); strLogger.fatal("fatal should appear"); Assert.assertEquals(out1.toString().length(), outlength); Assert.assertTrue(err1.toString().contains("[java.lang.String] [FATAL] fatal should appear")); } /** Test setting the root logger level */ @Test void testRootLoggerSet() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.rootLogger", "DEBUG"); testInitialize(props, out2, err2); Logger strLogger = Logger.getLogger(String.class); strLogger.trace("trace should appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.debug("debug should appear"); Assert.assertTrue(out1.toString().startsWith("[java.lang.String] [DEBUG] debug should appear")); Assert.assertEquals(err1.toString(), ""); } /** Test setting the root logger to an illegal level value throws an exception. */ @Test void testRootLoggerSetError() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.rootLogger", "unknown"); try { testInitialize(props, out2, err2); throw new RuntimeException("failure"); } catch (IllegalArgumentException pEx) { // Normal case Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); } } /** Test setting a user logger level */ @Test void testUserLoggerSet() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.logger.java.lang.String", "DEBUG"); testInitialize(props, out2, err2); Logger strLogger = Logger.getLogger(String.class); strLogger.trace("trace should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.debug("debug should appear"); int outLength = out1.toString().length(); Assert.assertTrue(out1.toString().startsWith("[java.lang.String] [DEBUG] debug should appear")); Assert.assertEquals(err1.toString(), ""); Logger classLogger = Logger.getLogger(Class.class); classLogger.debug("debug should not appear"); Assert.assertEquals(out1.toString().length(), outLength); Assert.assertEquals(err1.toString(), ""); classLogger.warn("warn should appear"); Assert.assertTrue(out1.toString().contains("[java.lang.Class] [WARN] warn should appear")); Assert.assertEquals(err1.toString(), ""); } /** Test setting a user logger to an illegal level value throws an exception */ @Test void testUserLoggerSetError() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.logger.java.lang.String", "unknown"); try { testInitialize(props, out2, err2); throw new RuntimeException("failure"); } catch (IllegalArgumentException pEx) { // Normal case Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); } } /** Tests setting a partial logger name (a hierarchy scope) */ @Test void testUserLoggerSetHierarchy() { Properties props = new Properties(); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ByteArrayOutputStream err1 = new ByteArrayOutputStream(); PrintStream out2 = new PrintStream(out1); PrintStream err2 = new PrintStream(err1); props.put("log4testng.logger.java.lang", "DEBUG"); testInitialize(props, out2, err2); Logger strLogger = Logger.getLogger(String.class); strLogger.trace("trace should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.debug("debug should appear"); Assert.assertTrue(out1.toString().startsWith("[java.lang.String] [DEBUG] debug should appear")); Assert.assertEquals(err1.toString(), ""); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/reporters/000077500000000000000000000000001475274123300261225ustar00rootroot00000000000000FailedInformationOnConsoleReporter.java000066400000000000000000000056061475274123300356520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/reporterspackage org.testng.reporters; import java.util.Arrays; import java.util.List; import org.testng.IReporter; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.internal.Utils; import org.testng.util.Strings; import org.testng.xml.XmlSuite; public class FailedInformationOnConsoleReporter implements IReporter { @Override public void generateReport(List xmlSuites, List suites, String outDir) { suites.forEach(FailedInformationOnConsoleReporter::generateReport); } private static void generateReport(ISuite suite) { suite.getResults().forEach(FailedInformationOnConsoleReporter::generateReport); } private static void generateReport(String name, ISuiteResult suiteResult) { ITestContext ctx = suiteResult.getTestContext(); IResultMap failedConfigs = ctx.getFailedConfigurations(); boolean hasFailedConfigs = !failedConfigs.getAllMethods().isEmpty(); IResultMap failedTests = ctx.getFailedTests(); boolean hasFailedTests = !failedTests.getAllResults().isEmpty(); if (!hasFailedConfigs && !hasFailedTests) { return; } if (hasFailedConfigs) { System.err.println(Strings.repeat("=", 100)); System.err.println( "::::::Failed Configurations for Suite ::: [" + name + "] ::: Test name [" + ctx.getName() + "]::::::"); System.err.println(Strings.repeat("=", 100)); failedConfigs.getAllResults().forEach(FailedInformationOnConsoleReporter::generateReport); System.err.println(Strings.repeat("=", 100)); System.err.println("\n\n"); } if (hasFailedTests) { System.err.println(Strings.repeat("=", 100)); System.err.println( "::::::Failed Tests for Suite ::: [" + name + "] ::: Test name [" + ctx.getName() + "]::::::"); System.err.println(Strings.repeat("=", 100)); failedTests.getAllResults().forEach(FailedInformationOnConsoleReporter::generateReport); System.err.println(Strings.repeat("=", 100)); System.err.println("\n\n"); } } private static void generateReport(ITestResult result) { StringBuilder builder = new StringBuilder(); String clsname = result.getTestClass().getRealClass().getName() + "."; String methodname = result.getMethod().getMethodName() + "()"; builder.append(clsname).append(methodname); Object[] parameters = result.getParameters(); if (parameters != null && parameters.length != 0) { builder.append(" Parameters:").append(Arrays.toString(parameters)); } Throwable throwable = result.getThrowable(); builder.append("\nException:\n"); builder.append(Utils.shortStackTrace(throwable, false)); builder.append("\n\n"); System.err.println(builder.toString()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/reporters/jq/000077500000000000000000000000001475274123300265345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/reporters/jq/TimesPanelTest.java000066400000000000000000000021511475274123300322770ustar00rootroot00000000000000package org.testng.reporters.jq; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.List; import org.testng.ISuite; import org.testng.annotations.Test; import org.testng.internal.paramhandler.FakeSuite; import org.testng.reporters.XMLStringBuffer; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class TimesPanelTest extends SimpleBaseTest { private static final String GITHUB_1931 = "GITHUB-1931 [NPE] TimesPanel.maxTime(ISuite suite)"; @Test(description = GITHUB_1931) public void generateReportTimesPanelContentForSuiteWithoutStartedTests() { XmlTest xmlTest = createXmlTest("GITHUB_1931", "NPE", Object.class); ISuite iSuite = new FakeSuite(xmlTest); List suites = new ArrayList<>(); suites.add(iSuite); Model model = new Model(suites); TimesPanel panel = new TimesPanel(model); XMLStringBuffer buffer = new XMLStringBuffer(); panel.getContent(iSuite, buffer); assertTrue( "TimesPanel contains total running time", panel.getContent(iSuite, buffer).contains("Total running time: 0 ms")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/util/000077500000000000000000000000001475274123300250525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/util/StringsTest.java000066400000000000000000000011621475274123300302060ustar00rootroot00000000000000package org.testng.util; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; /** Unit tests for {@link Strings} */ public class StringsTest { @Test public void joinEmptyArray() { String[] emptyArray = new String[0]; assertEquals(Strings.join(",", emptyArray), ""); } @Test public void joinArrayWithOneElement() { String[] array = new String[] {"one"}; assertEquals(Strings.join(",", array), "one"); } @Test public void joinArrayWithTwoElements() { String[] array = new String[] {"one", "two"}; assertEquals(Strings.join(",", array), "one,two"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/000077500000000000000000000000001475274123300246755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/FakeHttpXmlParser.java000066400000000000000000000007551475274123300311130ustar00rootroot00000000000000package org.testng.xml; import java.io.InputStream; import org.testng.TestNGException; public class FakeHttpXmlParser implements ISuiteParser { @Override public boolean accept(String fileName) { return fileName.startsWith("https") || fileName.startsWith("http"); } @Override public XmlSuite parse(String filePath, InputStream is, boolean loadClasses) throws TestNGException { XmlSuite suite = new XmlSuite(); suite.setName("fake_suite"); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/Issue1716TestSample.java000066400000000000000000000002111475274123300311430ustar00rootroot00000000000000package org.testng.xml; import org.testng.annotations.Test; public class Issue1716TestSample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/ParserTest.java000066400000000000000000000014641475274123300276410ustar00rootroot00000000000000package org.testng.xml; import static org.testng.Assert.assertEquals; import java.io.File; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.internal.Parser; public class ParserTest { private static final String XML_FILE_NAME = "src/test/resources/a.xml"; @Test(dataProvider = "dp") public void testParsing(String file) throws Exception { Parser parser = new Parser(file); List suites = parser.parseToList(); assertEquals(suites.size(), 1); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { {XML_FILE_NAME}, {new File(XML_FILE_NAME).toURI().toString()}, {"https://localhost:4444/testng.xml"}, {"https://localhost:4444/testng.xml"} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/SuiteXmlParserTest.java000066400000000000000000000023111475274123300313240ustar00rootroot00000000000000package org.testng.xml; import static test.SimpleBaseTest.getPathToResource; import java.io.File; import java.io.FileInputStream; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SuiteXmlParserTest { private static final File PARENT = new File(getPathToResource("xml")); @DataProvider private static Object[][] dp() { return new Object[][] { {"goodWithDoctype.xml", true}, {"goodWithoutDoctype.xml", true}, {"badWithDoctype.xml", false}, // TestNGException -> SAXParseException {"badWithoutDoctype.xml", false}, // NullPointerException {"issue174.xml", true} }; } @Test(dataProvider = "dp") public void testParse(String fileName, boolean shouldWork) { SuiteXmlParser parser = new SuiteXmlParser(); try (FileInputStream stream = new FileInputStream(new File(PARENT, fileName))) { XmlSuite suite = parser.parse(fileName, stream, false); if (!shouldWork) { Assert.fail("Parsing of " + fileName + " is supposed to fail"); } } catch (Exception e) { if (shouldWork) { Assert.fail("Parsing of " + fileName + " is supposed to work"); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/XmlSuiteTest.java000066400000000000000000000103431475274123300301530ustar00rootroot00000000000000package org.testng.xml; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; public class XmlSuiteTest extends SimpleBaseTest { @Test public void testIncludedAndExcludedGroups() { XmlSuite suite = new XmlSuite(); suite.addIncludedGroup("foo"); suite.addExcludedGroup("bar"); assertThat(suite.getIncludedGroups()).containsExactly("foo"); assertThat(suite.getExcludedGroups()).containsExactly("bar"); } @Test public void testIncludedAndExcludedGroupsWithRun() { XmlRun xmlRun = new XmlRun(); xmlRun.onInclude("foo"); xmlRun.onExclude("bar"); XmlGroups groups = new XmlGroups(); groups.setRun(xmlRun); XmlSuite suite = new XmlSuite(); suite.setGroups(groups); assertThat(suite.getIncludedGroups()).containsExactly("foo"); assertThat(suite.getExcludedGroups()).containsExactly("bar"); } @Test(dataProvider = "dp", description = "GITHUB-778") public void testTimeOut(String timeout, int size, int lineNumber) { XmlSuite suite = new XmlSuite(); suite.setTimeOut(timeout); StringReader stringReader = new StringReader(suite.toXml()); List resultLines = Lists.newArrayList(); List lineNumbers = grep(stringReader, "time-out=\"1000\"", resultLines); assertThat(lineNumbers).size().isEqualTo(size); assertThat(resultLines).size().isEqualTo(size); if (size > 0) { assertThat(lineNumbers.get(size - 1)).isEqualTo(lineNumber); } } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { {"1000", 1, 2}, {"", 0, 0} }; } @Test(description = "GITHUB-1668") public void ensureNoExceptionsAreRaisedWhenMethodSelectorsDefinedAtSuiteLevel() throws IOException { Parser parser = new Parser("src/test/resources/xml/issue1668.xml"); List suites = parser.parseToList(); XmlSuite xmlsuite = suites.get(0); TestNG testNG = create(); testNG.setXmlSuites(suites); testNG.setUseDefaultListeners(false); testNG.run(); // Trigger a call to "toXml()" to ensure that there is no exception raised. assertThat(xmlsuite.toXml()).isNotEmpty(); } @Test(description = "GITHUB-435") public void ensureSuiteLevelPackageIsAppliedToAllTests() throws IOException { Parser parser = new Parser("src/test/resources/xml/issue435.xml"); List suites = parser.parseToList(); XmlSuite xmlsuite = suites.get(0); assertThat(xmlsuite.getTests().get(0).getClasses().size()).isEqualTo(0); TestNG testNG = create(); testNG.setXmlSuites(suites); testNG.setUseDefaultListeners(false); testNG.run(); assertThat(xmlsuite.getTests().get(0).getClasses().size()).isEqualTo(1); } @Test(description = "GITHUB-1674") public void ensureSuiteLevelBeanshellIsAppliedToAllTests() throws IOException { PrintStream current = System.out; StringOutputStream stream = new StringOutputStream(); try { System.setOut(new PrintStream(stream)); Parser parser = new Parser("src/test/resources/xml/issue1674.xml"); List suites = parser.parseToList(); XmlSuite xmlsuite = suites.get(0); assertThat(xmlsuite.getTests().get(0).getMethodSelectors().size()).isEqualTo(0); TestNG testNG = create(); testNG.setXmlSuites(suites); testNG.setUseDefaultListeners(false); testNG.run(); assertThat(xmlsuite.getTests().get(0).getMethodSelectors().size()).isEqualTo(1); assertThat(stream.toString()).contains(Arrays.asList("rajni", "kamal", "mgr")); } finally { System.setOut(current); } } static class StringOutputStream extends OutputStream { private StringBuilder string = new StringBuilder(); @Override public void write(int b) { this.string.append((char) b); } // Netbeans IDE automatically overrides this toString() public String toString() { return this.string.toString(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/XmlTestTest.java000066400000000000000000000035531475274123300300060ustar00rootroot00000000000000package org.testng.xml; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Maps; import test.SimpleBaseTest; import test.junitreports.SimpleTestSample; public class XmlTestTest extends SimpleBaseTest { @Test public void testNameMatchesAny() { XmlSuite xmlSuite = createDummySuiteWithTestNamesAs("test1"); XmlTest xmlTest = xmlSuite.getTests().get(0); assertThat(xmlTest.nameMatchesAny(Collections.singletonList("test1"))).isTrue(); assertThat(xmlTest.nameMatchesAny(Collections.singletonList("test2"))).isFalse(); } @Test(dataProvider = "dp", description = "GITHUB-1716") public void testNullOrEmptyParameter(Map data) { XmlTest test = createXmlTest("suite", "test", Issue1716TestSample.class); test.setParameters(data); test.toXml(" "); Assert.assertTrue(true, "No exceptions should have been thrown"); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{newSetOfParameters(null, "value")}, {newSetOfParameters("foo", null)}}; } @Test(description = "GITHUB-2467") public void testXMLClassesInCloneMethod() { XmlSuite xmlSuite = createXmlSuite("suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "test"); createXmlClass(xmlTest, SimpleTestSample.class); XmlTest copyXmlTest = (XmlTest) xmlTest.clone(); Assert.assertNotNull(copyXmlTest); Assert.assertNotNull(copyXmlTest.getXmlClasses()); Assert.assertEquals(xmlTest.getXmlClasses().size(), copyXmlTest.getXmlClasses().size()); } private static Map newSetOfParameters(String key, String value) { Map map = Maps.newHashMap(); map.put(key, value); return map; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/internal/000077500000000000000000000000001475274123300265115ustar00rootroot00000000000000TestNamesMatcherTest.java000066400000000000000000000106111475274123300333430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/internalpackage org.testng.xml.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.TestNGException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.CollectionUtils; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class TestNamesMatcherTest extends SimpleBaseTest { @Test public void testCloneIfContainsTestsWithNamesMatchingAny() { XmlSuite suite = createDummySuiteWithTestNamesAs("test1", "test2"); TestNamesMatcher testNamesMatcher = new TestNamesMatcher(suite, Collections.singletonList("test2")); List xmlTests = testNamesMatcher.getMatchedTests(); assertThat(suite.getTests()).hasSameElementsAs(xmlTests); } @Test(description = "GITHUB-1594", dataProvider = "getTestnames") public void testCloneIfContainsTestsWithNamesMatchingAnyChildSuites( String testname, boolean foundInParent, boolean foundInChildOfChild) { XmlSuite parentSuite = createDummySuiteWithTestNamesAs("test1", "test2"); parentSuite.setName("parent_suite"); XmlSuite childSuite = createDummySuiteWithTestNamesAs("test3", "test4"); childSuite.setName("child_suite"); parentSuite.getChildSuites().add(childSuite); XmlSuite childOfChildSuite = createDummySuiteWithTestNamesAs("test5", "test6"); childSuite.getChildSuites().add(childOfChildSuite); TestNamesMatcher testNamesMatcher = new TestNamesMatcher(parentSuite, Collections.singletonList(testname)); List xmlTests = testNamesMatcher.getMatchedTests(); if (foundInParent) { assertThat(xmlTests).hasSameElementsAs(parentSuite.getTests()); } else if (!foundInChildOfChild) { assertThat(xmlTests).hasSameElementsAs(childSuite.getTests()); } else { assertThat(xmlTests).hasSameElementsAs(childOfChildSuite.getTests()); } } @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = "\nPlease provide a valid list of names to check.", dataProvider = "getData") public void testCloneIfContainsTestsWithNamesMatchingAnyNegativeCondition( XmlSuite xmlSuite, List names) { TestNamesMatcher testNamesHelper = new TestNamesMatcher(xmlSuite, names); } @Test public void testIfTestnamesComesFromDifferentSuite() { XmlSuite parentSuite = createDummySuiteWithTestNamesAs("test1", "test2"); parentSuite.setName("parent_suite"); XmlSuite childSuite = createDummySuiteWithTestNamesAs("test3", "test4"); childSuite.setName("child_suite"); parentSuite.getChildSuites().add(childSuite); XmlSuite childOfChildSuite = createDummySuiteWithTestNamesAs("test5", "test6"); childSuite.getChildSuites().add(childOfChildSuite); TestNamesMatcher testNamesMatcher = new TestNamesMatcher( parentSuite, new ArrayList<>(Arrays.asList("test1", "test3", "test5"))); List matchedTestnames = Lists.newArrayList(); for (XmlTest xmlTest : testNamesMatcher.getMatchedTests()) { matchedTestnames.add(xmlTest.getName()); } assertThat(matchedTestnames).hasSameElementsAs(Arrays.asList("test1", "test3", "test5")); } @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = "\nThe test\\(s\\) \\<\\[test3\\]\\> cannot be found.") public void testCloneIfContainsTestsWithNamesMatchingAnyWithoutMatch() { XmlSuite xmlSuite = createDummySuiteWithTestNamesAs("test1", "test2"); TestNamesMatcher testNamesMatcher = new TestNamesMatcher(xmlSuite, Collections.singletonList("test3")); List clonedSuites = testNamesMatcher.getSuitesMatchingTestNames(); if (!CollectionUtils.hasElements(clonedSuites)) { throw new TestNGException( "The test(s) <" + Collections.singletonList("test3").toString() + "> cannot be found."); } } @DataProvider(name = "getTestnames") public Object[][] getTestnameToSearchFor() { return new Object[][] { {"test4", false, false}, {"test1", true, false}, {"test5", false, true} }; } @DataProvider(name = "getData") public Object[][] getTestData() { return new Object[][] { {new XmlSuite(), null}, {new XmlSuite(), Collections.emptyList()} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/internal/XmlSuiteUtilsTest.java000066400000000000000000000014711475274123300330120ustar00rootroot00000000000000package org.testng.xml.internal; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class XmlSuiteUtilsTest extends SimpleBaseTest { @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = "\nTwo tests in the same suite \\[random_suite\\] cannot have the same name: test1") public void testEnsureNoDuplicateTestsArePresentNegativeCondition() { XmlSuite suite = createDummySuiteWithTestNamesAs("test1", "test1"); XmlSuiteUtils.ensureNoDuplicateTestsArePresent(suite); } @Test public void testEnsureNoDuplicateTestsArePresent() { XmlSuite suite = createDummySuiteWithTestNamesAs("test1", "test2"); XmlSuiteUtils.ensureNoDuplicateTestsArePresent(suite); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/issue1668/000077500000000000000000000000001475274123300263525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/issue1668/TestClassSample.java000066400000000000000000000003111475274123300322570ustar00rootroot00000000000000package org.testng.xml.issue1668; import org.testng.Assert; import org.testng.annotations.Test; public class TestClassSample { @Test public void testMethod() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/issue1674/000077500000000000000000000000001475274123300263475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/issue1674/Testclass.java000066400000000000000000000002111475274123300311510ustar00rootroot00000000000000package org.testng.xml.issue1674; import org.testng.annotations.Test; public class Testclass { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/issue435/000077500000000000000000000000001475274123300262615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/org/testng/xml/issue435/Testclass.java000066400000000000000000000005151475274123300310720ustar00rootroot00000000000000package org.testng.xml.issue435; import org.testng.annotations.Test; public class Testclass { @Test(groups = "group1") public void testMethod1() {} @Test(groups = "group2") public void testMethod2() {} @Test(groups = "group3") public void testMethod3() {} @Test(groups = "group4") public void testMethod4() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/000077500000000000000000000000001475274123300227615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/BaseDistributedTest.java000066400000000000000000000025041475274123300275420ustar00rootroot00000000000000package test; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.ITestResult; import org.testng.collections.Maps; import org.testng.log4testng.Logger; public class BaseDistributedTest { private boolean m_verbose = false; protected void verifyTests(String title, String[] exp, Map> found) { Map expected = Maps.newHashMap(); for (String element : exp) { expected.put(element, element); } Assert.assertEquals( found.size(), expected.size(), "Verification for " + title + " tests failed:"); for (Object o : expected.values()) { String name = (String) o; if (null == found.get(name)) { dumpMap("Expected", expected); dumpMap("Found", found); } Assert.assertNotNull( found.get(name), "Expected to find method " + name + " in " + title + " but didn't find it."); } } protected void dumpMap(String title, Map m) { if (m_verbose) { Logger.getLogger(getClass()).info("==== " + title); for (Map.Entry entry : m.entrySet()) { log(entry.getKey() + " => " + entry.getValue()); } } } private void log(String s) { if (m_verbose) { Logger.getLogger(getClass()).info("[BaseDistributedTest] " + s); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/BaseTest.java000066400000000000000000000305431475274123300253430ustar00rootroot00000000000000package test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.Assert; import org.testng.IClassListener; import org.testng.IInvokedMethodListener; import org.testng.ISuite; import org.testng.ITestObjectFactory; import org.testng.ITestResult; import org.testng.ITestRunnerFactory; import org.testng.SuiteRunner; import org.testng.TestListenerAdapter; import org.testng.TestRunner; import org.testng.annotations.BeforeMethod; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.internal.Configuration; import org.testng.internal.IConfiguration; import org.testng.internal.Systematiser; import org.testng.reporters.JUnitXMLReporter; import org.testng.reporters.TestHTMLReporter; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlMethodSelector; import org.testng.xml.XmlPackage; import org.testng.xml.XmlScript; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; /** * Base class for tests * * @since May 5, 2004 */ public class BaseTest extends BaseDistributedTest { private static final String m_outputDirectory = "test-output-tests"; private XmlSuite m_suite = null; private final ITestRunnerFactory m_testRunnerFactory; private final IConfiguration m_configuration; private Integer m_verbose = null; public BaseTest() { m_configuration = new Configuration(); m_configuration.setObjectFactory(new ITestObjectFactory() {}); m_testRunnerFactory = new InternalTestRunnerFactory(this); } protected void setParallel(XmlSuite.ParallelMode parallel) { getTest().setParallel(parallel); } protected void setVerbose(int n) { m_verbose = n; } protected void setTestTimeOut(long n) { getTest().setTimeOut(n); } protected void setSuiteTimeOut(long n) { m_suite.setTimeOut(Long.toString(n)); } protected void setJUnit(boolean f) { getTest().setJUnit(f); } protected void setThreadCount(int count) { getTest().getSuite().setThreadCount(count); } private Map m_tests = new HashMap<>(); private Map>> m_passedTests = new HashMap<>(); private Map>> m_failedTests = new HashMap<>(); private Map>> m_skippedTests = new HashMap<>(); private Map>> m_passedConfigs = new HashMap<>(); private Map>> m_failedConfigs = new HashMap<>(); private Map>> m_skippedConfigs = new HashMap<>(); private Map>> m_failedButWithinSuccessPercentageTests = new HashMap<>(); protected Map> getTests(Map>> map) { return map.computeIfAbsent(getId(), k -> new HashMap<>()); } protected XmlTest getTest() { return m_tests.get(getId()); } protected void setTests( Map>> map, Map> m) { map.put(getId(), m); } public Map> getFailedTests() { return getTests(m_failedTests); } public Map> getFailedButWithinSuccessPercentageTests() { return getTests(m_failedButWithinSuccessPercentageTests); } public Map> getPassedTests() { return getTests(m_passedTests); } public Map> getSkippedTests() { return getTests(m_skippedTests); } public Map> getFailedConfigs() { return getTests(m_failedConfigs); } public Map> getPassedConfigs() { return getTests(m_passedConfigs); } public Map> getSkippedConfigs() { return getTests(m_skippedConfigs); } public void setSkippedTests(Map> m) { setTests(m_skippedTests, m); } public void setPassedTests(Map> m) { setTests(m_passedTests, m); } public void setFailedTests(Map> m) { setTests(m_failedTests, m); } public void setFailedButWithinSuccessPercentageTests(Map> m) { setTests(m_failedButWithinSuccessPercentageTests, m); } public void setSkippedConfigs(Map> m) { setTests(m_skippedConfigs, m); } public void setPassedConfigs(Map> m) { setTests(m_passedConfigs, m); } public void setFailedConfigs(Map> m) { setTests(m_failedConfigs, m); } protected void run() { assert null != getTest() : "Test wasn't set, maybe @Configuration methodSetUp() was never called"; setPassedTests(Maps.newHashMap()); setFailedTests(Maps.newHashMap()); setSkippedTests(Maps.newHashMap()); setPassedConfigs(Maps.newHashMap()); setFailedConfigs(Maps.newHashMap()); setSkippedConfigs(Maps.newHashMap()); setFailedButWithinSuccessPercentageTests(Maps.newHashMap()); m_suite.setVerbose(m_verbose != null ? m_verbose : 0); SuiteRunner suite = new SuiteRunner( m_configuration, m_suite, m_outputDirectory, m_testRunnerFactory, Systematiser.getComparator()); suite.run(); } protected void addMethodSelector(String className, int priority) { XmlMethodSelector methodSelector = new XmlMethodSelector(); methodSelector.setName(className); methodSelector.setPriority(priority); getTest().getMethodSelectors().add(methodSelector); } protected void addClasses(Class... classes) { for (Class clazz : classes) { addClass(clazz); } } protected XmlClass addClass(Class cls) { return addClass(cls.getName()); } protected XmlClass addClass(String className) { XmlClass result = new XmlClass(className); getTest().getXmlClasses().add(result); return result; } protected void setScript(String language, String expression) { XmlScript script = new XmlScript(); script.setExpression(expression); script.setLanguage(language); getTest().setScript(script); } protected void addPackage(String pkgName, String[] included, String[] excluded) { XmlPackage pkg = new XmlPackage(); pkg.setName(pkgName); pkg.getInclude().addAll(Arrays.asList(included)); pkg.getExclude().addAll(Arrays.asList(excluded)); getTest().getSuite().getXmlPackages().add(pkg); } private XmlClass findClass(String className) { for (XmlClass cl : getTest().getXmlClasses()) { if (cl.getName().equals(className)) { return cl; } } return addClass(className); } public void addIncludedMethod(String className, String m) { XmlClass xmlClass = findClass(className); xmlClass.getIncludedMethods().add(new XmlInclude(m)); getTest().getXmlClasses().add(xmlClass); } public void addExcludedMethod(String className, String m) { XmlClass xmlClass = findClass(className); xmlClass.getExcludedMethods().add(m); getTest().getXmlClasses().add(xmlClass); } public void addIncludedGroup(String g) { getTest().addIncludedGroup(g); } public void addExcludedGroup(String g) { getTest().addExcludedGroup(g); } @BeforeMethod(groups = {"init", "initTest"}) public void methodSetUp() { m_suite = new XmlSuite(); m_suite.setName("Internal_suite"); XmlTest xmlTest = new XmlTest(m_suite); xmlTest.setName("Internal_test_failures_are_expected"); m_tests.put(getId(), xmlTest); } private void addTest(Map> tests, ITestResult t) { List l = tests.computeIfAbsent(t.getMethod().getMethodName(), k -> new ArrayList<>()); l.add(t); } public void addPassedTest(ITestResult t) { addTest(getPassedTests(), t); } public void addFailedTest(ITestResult t) { addTest(getFailedTests(), t); } public void addFailedButWithinSuccessPercentageTest(ITestResult t) { addTest(getFailedButWithinSuccessPercentageTests(), t); } public void addSkippedTest(ITestResult t) { addTest(getSkippedTests(), t); } public void addPassedConfig(ITestResult t) { addTest(getPassedConfigs(), t); } public void addFailedConfig(ITestResult t) { addTest(getFailedConfigs(), t); } public void addSkippedConfig(ITestResult t) { addTest(getSkippedConfigs(), t); } protected Long getId() { return 42L; } public XmlSuite getSuite() { return m_suite; } public void setSuite(XmlSuite suite) { m_suite = suite; } /** * Used for instanceCount testing, when we need to look inside the TestResult to count the various * SUCCESS/FAIL/FAIL_BUT_OK */ protected void verifyResults(Map> tests, int expected, String message) { if (tests.size() > 0) { Set keys = tests.keySet(); Object firstKey = keys.iterator().next(); List passedResult = tests.get(firstKey); int n = passedResult.size(); assert n == expected : "Expected " + expected + " " + message + " but found " + n; } else { assert expected == 0 : "Expected " + expected + " " + message + " but found " + tests.size(); } } protected static void verifyInstanceNames( Map> actual, String[] expected) { List actualNames = Lists.newArrayList(); for (Map.Entry> es : actual.entrySet()) { for (ITestResult tr : es.getValue()) { Object instance = tr.getInstance(); actualNames.add(es.getKey() + "#" + (instance != null ? instance.toString() : "")); } } Assert.assertEqualsNoOrder(actualNames.toArray(), expected); } protected void verifyPassedTests(String... expectedPassed) { verifyTests("Passed", expectedPassed, getPassedTests()); } protected void verifyFailedTests(String... expectedFailed) { verifyTests("Failed", expectedFailed, getFailedTests()); } protected void verifySkippedTests(String... expectedSkipped) { verifyTests("Skipped", expectedSkipped, getSkippedTests()); } private static class InternalTestRunnerFactory implements ITestRunnerFactory { private final BaseTest m_baseTest; public InternalTestRunnerFactory(final BaseTest baseTest) { m_baseTest = baseTest; } @Override public TestRunner newTestRunner( ISuite suite, XmlTest test, Collection listeners, List classListeners) { TestRunner testRunner = new TestRunner( m_baseTest.m_configuration, suite, test, false, listeners, classListeners, Systematiser.getComparator()); testRunner.addListener(new TestHTMLReporter()); testRunner.addListener(new JUnitXMLReporter()); testRunner.addListener(new TestListener(m_baseTest)); if (listeners != null) { for (IInvokedMethodListener l : listeners) { testRunner.addListener(l); } } return testRunner; } } protected void runTest(String cls, String[] passed, String[] failed, String[] skipped) { addClass(cls); run(); verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } // BaseTest //////////////////////////// class TestListener extends TestListenerAdapter { private static BaseTest m_test = null; public TestListener(BaseTest t1) { m_test = t1; } @Override public void onTestSuccess(ITestResult tr) { m_test.addPassedTest(tr); } @Override public void onTestFailure(ITestResult tr) { m_test.addFailedTest(tr); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { m_test.addFailedButWithinSuccessPercentageTest(result); } @Override public void onTestSkipped(ITestResult tr) { m_test.addSkippedTest(tr); } @Override public void onConfigurationSuccess(ITestResult tr) { m_test.addPassedConfig(tr); } @Override public void onConfigurationFailure(ITestResult tr) { m_test.addFailedConfig(tr); } @Override public void onConfigurationSkip(ITestResult tr) { m_test.addSkippedConfig(tr); } } // TestListener jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/CheckSuitesInitializationTest.java000066400000000000000000000024441475274123300316120ustar00rootroot00000000000000package test; import java.util.Collections; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; /** * Check for a bug in how relative paths in suite files were being handled. * *

All paths were being resolved using the initial suite's location and not that of the current * suite being parsed/processed. * *

This test checks that TestNG can handle cases where we have the following set of files (all * linked using relative paths): * *

- parent-suite -> [child-suite-1, children/child-suite-3] - children/child-suite-3 -> * [../child-suite-2, child-suite-4, morechildren/child-suite-5] * *

Check the checksuitesinitialization folder under test resources * * @author Nalin Makar */ public class CheckSuitesInitializationTest extends SimpleBaseTest { /** Child suites and tests within different suites have same names */ @Test public void check() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); String testngXmlPath = getPathToResource("checksuitesinitialization/parent-suite.xml"); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 4); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ClassConfigurations.java000066400000000000000000000020641475274123300276060ustar00rootroot00000000000000package test; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ClassConfigurations { static int beforeCount = 0; static int afterCount = 0; @BeforeClass public void beforeTestClass() { ++beforeCount; // System.out.println("@@@@@@ beforeTestClass has been called " + beforeCount + " time(s)"); } @AfterTest public void afterTest() { beforeCount = 0; afterCount = 0; } @AfterTest public void afterTestClass() { ++afterCount; // System.out.println("@@@@@@@ afterTestClass has been called " + afterCount + " time(s)"); } @Test public void testOne() { // System.out.println("testOne"); assert beforeCount == 1; assert afterCount == 0; } @Test public void testTwo() { // System.out.println("testTwo"); assert beforeCount == 1; assert afterCount == 0; } @Test public void testThree() { // System.out.println("testThree"); assert beforeCount == 1; assert afterCount == 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/CommandLineTest.java000066400000000000000000000123631475274123300266570ustar00rootroot00000000000000package test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.CommandLineArgs; import org.testng.IInjectorFactory; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.internal.IConfiguration; import test.sample.JUnitSample1; import testhelper.OutputDirectoryPatch; public class CommandLineTest { /** Test -junit */ @Test(groups = {"current"}) public void junitParsing() { String[] argv = { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-junit", "-testclass", "test.sample.JUnitSample1" }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); List passed = tla.getPassedTests(); assertEquals(passed.size(), 2); String test1 = passed.get(0).getMethod().getMethodName(); String test2 = passed.get(1).getMethod().getMethodName(); assertTrue( JUnitSample1.EXPECTED1.equals(test1) && JUnitSample1.EXPECTED2.equals(test2) || JUnitSample1.EXPECTED1.equals(test2) && JUnitSample1.EXPECTED2.equals(test1)); } /** Test the absence of -junit */ @Test(groups = {"current"}) public void junitParsing2() { String[] argv = { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-testclass", "test.sample.JUnitSample1" }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); List passed = tla.getPassedTests(); assertEquals(passed.size(), 0); } /** Test the ability to override the default command line Suite name */ @Test(groups = {"current"}) public void suiteNameOverride() { String suiteName = "MySuiteName"; String[] argv = { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-junit", "-testclass", "test.sample.JUnitSample1", "-suitename", suiteName }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); List contexts = tla.getTestContexts(); assertTrue(contexts.size() > 0); for (ITestContext context : contexts) { assertEquals(context.getSuite().getName(), suiteName); } } /** Test the ability to override the default command line test name */ @Test(groups = {"current"}) public void testNameOverride() { String testName = "My Test Name"; String[] argv = { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-junit", "-testclass", "test.sample.JUnitSample1", "-testname", testName }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); List contexts = tla.getTestContexts(); assertTrue(contexts.size() > 0); for (ITestContext context : contexts) { assertEquals(context.getName(), testName); } } @Test public void testUseDefaultListenersArgument() { TestNG.privateMain( new String[] { "-log", "0", "-usedefaultlisteners", "false", "-testclass", "test.sample.JUnitSample1" }, null); } @Test public void testMethodParameter() { String[] argv = { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-methods", "test.sample.Sample2.method1,test.sample.Sample2.method3", }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); List passed = tla.getPassedTests(); Assert.assertEquals(passed.size(), 2); Assert.assertTrue( (passed.get(0).getName().equals("method1") && passed.get(1).getName().equals("method3")) || (passed.get(1).getName().equals("method1") && passed.get(0).getName().equals("method3"))); } @SuppressWarnings("deprecation") @Test(description = "GITHUB-2207") public void testInjectorFactoryCanBeConfiguredViaProperties() { Map params = new HashMap<>(); params.put(CommandLineArgs.DEPENDENCY_INJECTOR_FACTORY, TestInjectorFactory.class.getName()); TestNG testNG = new TestNG(); testNG.configure(params); IInjectorFactory resolvedInjectorFactory = retrieveInjectionMechanism(testNG); Assert.assertEquals(resolvedInjectorFactory.getClass(), TestInjectorFactory.class); } private static IInjectorFactory retrieveInjectionMechanism(TestNG testNG) { try { Field field = TestNG.class.getDeclaredField("m_configuration"); field.setAccessible(true); IConfiguration cfg = (IConfiguration) field.get(testNG); return cfg.getInjectorFactory(); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } public static class TestInjectorFactory implements IInjectorFactory { @Override @SuppressWarnings("deprecation") public Injector getInjector(Stage stage, Module... modules) { return null; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/CountSampleTest.java000066400000000000000000000020001475274123300267060ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.Test; /** * Use this test to show run/failed/skip result differences between testng-5.12 and testng-5-14 * * @author CA Technologies */ public class CountSampleTest { @Test(groups = {"functional"}) public void testInvokedAndSkipped() throws SkipException { // System.out.println("Skipping this test after it is invoked."); throw new SkipException("This test is skipped after invocation"); } @Test(groups = {"functional"}) public static void testInvokedAndFailed() { // System.out.println("Failing this test after it is invoked."); Assert.fail("Failing this test on purpose"); } @Test( groups = {"functional"}, dependsOnMethods = {"testInvokedAndFailed"}) public static void testWillNotBeInvokedOnlySkipped() { // System.out.println("This test will be skipped, " + // "but not invoked because its dependsOnMethod fails."); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/CountTest.java000066400000000000000000000017731475274123300255640ustar00rootroot00000000000000package test; import java.util.List; import org.testng.Assert; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; public class CountTest extends SimpleBaseTest { @Test(description = "Make sure that skipped methods are accurately counted") public void skippedMethodsShouldBeCounted() { TestNG tng = create(CountSampleTest.class); IReporter r = new IReporter() { @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { for (ISuite s : suites) { for (ISuiteResult sr : s.getResults().values()) { ITestContext ctx = sr.getTestContext(); Assert.assertEquals(2, ctx.getSkippedTests().size()); } } } }; tng.addListener(r); tng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/CtorCalledOnce.java000066400000000000000000000015261475274123300264510ustar00rootroot00000000000000package test; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; /** * this test verifys that the test class is instantiated exactly once regardless of how many test * methods we have, showing that TestNG semantics is quite different from JUnit */ public class CtorCalledOnce { public static int instantiated = 0; public CtorCalledOnce() { instantiated++; } @Test public void testMethod1() { assert instantiated == 1 : "Expected 1, was invoked " + instantiated + " times"; } @Test public void testMethod2() { assert instantiated == 1 : "Expected 1, was invoked " + instantiated + " times"; } @Test public void testMethod3() { assert instantiated == 1 : "Expected 1, was invoked " + instantiated + " times"; } @AfterTest public void afterTest() { instantiated = 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/EclipseTest.java000066400000000000000000000007611475274123300260540ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.Test; /** * Make sure that these test pass when run by the Eclipse plug-in. * * @author Cedric Beust */ public class EclipseTest { @Test public void xmlFileShouldBeRunAtItsPlaceAndNotCopied(ITestContext ctx) { String fileName = ctx.getSuite().getXmlSuite().getFileName().replace("\\", "/"); Assert.assertTrue(fileName.contains("src/test/resources")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/Exclude.java000066400000000000000000000016531475274123300252220ustar00rootroot00000000000000package test; import org.testng.annotations.Test; public class Exclude { private boolean m_included1 = false; private boolean m_included2 = false; private boolean m_excluded1 = true; private boolean m_excluded2 = true; @Test(groups = {"group1"}) public void included1() { m_included1 = true; } @Test(groups = {"group1"}) public void included2() { m_included2 = true; } @Test(groups = {"group1"}) public void excluded1() { m_excluded1 = false; } @Test(groups = {"group1"}) public void excluded2() { m_excluded2 = false; } @Test( dependsOnGroups = {"group1"}, groups = {"group2"}) public void verify() { assert m_included1 && m_included2 && m_excluded1 && m_excluded2 : "Should all be true: " + m_included1 + " " + m_included2 + " " + m_excluded1 + " " + m_excluded2; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/FileStringBufferTest.java000066400000000000000000000011571475274123300276700ustar00rootroot00000000000000package test; import org.testng.annotations.Test; import org.testng.reporters.FileStringBuffer; public class FileStringBufferTest { @Test public void basic() { { FileStringBuffer fsb = new FileStringBuffer(5); String s = "0123456789"; String s3 = s + s + s; fsb.append(s3); // Assert.assertEquals(s3, fsb.toString()); } { FileStringBuffer fsb = new FileStringBuffer(5); String s = "0123456789"; String s3 = s + s + s; fsb.append(s); fsb.append(s); fsb.append(s); // Assert.assertEquals(s3, fsb.toString()); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/GraphTest.java000066400000000000000000000141371475274123300255330ustar00rootroot00000000000000package test; import java.util.Comparator; import java.util.List; import org.testng.Assert; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.internal.Graph; import org.testng.internal.Graph.Node; import org.testng.internal.Tarjan; public class GraphTest { private static final Comparator> COMPARATOR = Comparator.comparing(Node::getObject); @Test public void sort() { Graph g = new Graph<>(COMPARATOR); g.addNode("3"); g.addNode("1"); g.addNode("2.2"); g.addNode("independent"); g.addNode("2.1"); g.addNode("2"); g.addPredecessor("3", "2"); g.addPredecessor("3", "2.1"); g.addPredecessor("3", "2.2"); g.addPredecessor("2", "1"); g.addPredecessor("2.1", "1"); g.addPredecessor("2.2", "1"); g.topologicalSort(); List l = g.getStrictlySortedNodes(); int i = 0; Assert.assertEquals("1", l.get(i)); i++; Assert.assertTrue("2".equals(l.get(i)) || "2.1".equals(l.get(i)) || "2.2".equals(l.get(i))); i++; Assert.assertTrue("2".equals(l.get(i)) || "2.1".equals(l.get(i)) || "2.2".equals(l.get(i))); i++; Assert.assertTrue("2".equals(l.get(i)) || "2.1".equals(l.get(i)) || "2.2".equals(l.get(i))); i++; Assert.assertEquals("3", l.get(i)); Assert.assertEquals(1, g.getIndependentNodes().size()); } @Test(expectedExceptions = org.testng.TestNGException.class) public void cycleShouldFail() { Graph g = createCyclicGraph(); g.topologicalSort(); } @Test public void cycleShouldBeCorrect() { Graph g = null; try { g = createCyclicGraph(); g.topologicalSort(); } catch (TestNGException ex) { Tarjan t = new Tarjan<>(g, "1"); Assert.assertEquals(t.getCycle().size(), 3); } } private Graph createCyclicGraph() { Graph g = new Graph<>(COMPARATOR); g.addNode("3"); g.addNode("2"); g.addNode("1"); g.addPredecessor("3", "2"); g.addPredecessor("2", "1"); g.addPredecessor("1", "3"); return g; } @Test public void findPredecessors() { Graph g = new Graph<>(COMPARATOR); g.addNode("3"); g.addNode("1"); g.addNode("2.2"); g.addNode("independent"); g.addNode("2.1"); g.addNode("2"); // 1 -> 2.1, 2.2, 2.3 --> 3 g.addPredecessor("3", "2"); g.addPredecessor("3", "2.1"); g.addPredecessor("3", "2.2"); g.addPredecessor("2", "1"); g.addPredecessor("2.1", "1"); g.addPredecessor("2.2", "1"); // Invoke sort to make sure there is no side effect g.topologicalSort(); // // Test findPredecessors // { List predecessors = g.findPredecessors("2"); Assert.assertEquals(1, predecessors.size()); Assert.assertEquals("1", predecessors.get(0)); } { List predecessors = g.findPredecessors("3"); Assert.assertEquals(4, predecessors.size()); Assert.assertEquals("1", predecessors.get(0)); Assert.assertTrue( predecessors.get(1).equals("2.1") || predecessors.get(1).equals("2.2") || predecessors.get(1).equals("2")); Assert.assertTrue( predecessors.get(2).equals("2.1") || predecessors.get(2).equals("2.2") || predecessors.get(2).equals("2")); Assert.assertTrue( predecessors.get(3).equals("2.1") || predecessors.get(3).equals("2.2") || predecessors.get(3).equals("2")); } } // Using an earlier implementation of Graph.findPrecessors, finding // predecessors in certain kinds of graphs where many nodes have the // same predecessors could be very slow, since the old implementation // would explore the same nodes repeatedly. This situation could // happen when test methods are organized in several groups, with // dependsOnGroups annotations so that each method in one group depends // on all of the methods in another group. If there were several // such groups depending on each other in a chain, the combinatorics // of the old method became excessive. This test builds a 72-node graph that // emulates this situation, then call Graph.findPredecessors. The old // implementation run this in 70+ seconds on my computer, the new implementation // takes a few milliseconds. In practice, with larger graphs, the former // slowness could get very extreme, taking hours or more to complete // in some real user situations. // @Test(timeOut = 5000) // If this takes more than 5 seconds we've definitely regressed. public void findPredecessorsTiming() { Graph g = new Graph<>(COMPARATOR); final String rootNode = "myroot"; final String independentNode = "independent"; g.addNode(rootNode); g.addNode(independentNode); final int maxDepth = 7; final int nodesPerDepth = 10; // must be < 100 // // Add maxDepth groups of new nodes, where each group contains nodesPerDepth // nodes, and each node in a group a depth N has each node in the group // at depth (N-1) as a predecessor. // for (int depth = 1; depth <= maxDepth; depth++) { for (int i = 0; i < nodesPerDepth; i++) { String newNode = String.valueOf(i + (100 * depth)); g.addNode(newNode); if (depth == 1) { continue; } for (int j = 0; j < nodesPerDepth; j++) { String prevNode = String.valueOf(j + (100 * (depth - 1))); g.addPredecessor(newNode, prevNode); } } } // Finally, make all of the nodes in the group at depth maxDepth // be predecessors of rootNode. // for (int i = 0; i < nodesPerDepth; i++) { String node = String.valueOf(i + (100 * maxDepth)); g.addPredecessor(rootNode, node); } // Now we're done building the graph, which has (maxDepth * nodesPerDepth) + 2 // nodes. rootNode has all of the other nodes except independentNode // as predecessors. // // Test findPredecessors // { List predecessors = g.findPredecessors(rootNode); Assert.assertEquals(predecessors.size(), (maxDepth * nodesPerDepth)); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/IndividualMethodsTest.java000066400000000000000000000011271475274123300301010ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test that if an individual method is specified on testng.xml, the @Configuration method still * runs. * *

Created on Aug 1, 2005 * * @author cbeust */ public class IndividualMethodsTest { private boolean m_setUpCalled = false; @BeforeMethod public void setUp() { m_setUpCalled = true; } @Test public void testMethod() { // this line causes the test to fail, showing that setUp() hadn't been run Assert.assertTrue(m_setUpCalled); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/InvocationAndSuccessPercentageTest.java000066400000000000000000000057341475274123300325600ustar00rootroot00000000000000package test; import org.testng.annotations.Test; /** * This class tests invocationCount and successPercentage * * @author cbeust */ public class InvocationAndSuccessPercentageTest extends BaseTest { @Test public void invocationCount() { addClass("test.sample.InvocationCountTest"); addIncludedGroup("invocationOnly"); run(); String[] passed = { "tenTimesShouldSucceed", }; String[] failed = {}; verifyResults(getPassedTests(), 10, "passed tests"); // Map passedTests = getPassedTests(); // Set keys = passedTests.keySet(); // Object firstKey = keys.iterator().next(); // ITestResult passedResult = (ITestResult) passedTests.get(firstKey); // int n = passedResult.getPassedMethods().size(); // assert n == 10 : // "Expected 10 tests to have passed, but only found " + n; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } /** Result expected: 8 passed 2 failed but within success percentage */ @Test public void successPercentageThatSucceeds() { addClass("test.sample.InvocationCountTest"); addIncludedGroup("successPercentageThatSucceedsOnly"); run(); String[] passed = { "successPercentageShouldSucceed", }; String[] failed = {}; String[] failedButWithinSuccessPercentage = { "successPercentageShouldSucceed", }; verifyTests( "FailedButWithinSuccessPercentage", failedButWithinSuccessPercentage, getFailedButWithinSuccessPercentageTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); // Should have 8 passed, 2 failed but within success percentage verifyResults(getPassedTests(), 8, "passed tests"); verifyResults( getFailedButWithinSuccessPercentageTests(), 2, "failed_but_within_success_percentage_tests"); } /** Result expected: 8 passed 1 failed but within success percentage 1 failed */ @Test public void successPercentageThatFails() { addClass(test.sample.InvocationCountTest.class); addIncludedGroup("successPercentageThatFailsOnly"); run(); String[] passed = { "successPercentageShouldFail", }; String[] failed = { "successPercentageShouldFail", }; String[] failedButWithinSuccessPercentage = { "successPercentageShouldFail", }; verifyTests( "FailedButWithinSuccessPercentage", failedButWithinSuccessPercentage, getFailedButWithinSuccessPercentageTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); // Should have 8 passed, 2 failed but within success percentage verifyResults(getPassedTests(), 8, "passed tests"); verifyResults(getFailedTests(), 1, "failed tests"); verifyResults( getFailedButWithinSuccessPercentageTests(), 1, "failed_but_within_success_percentage_tests"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/InvokedMethodListener.java000066400000000000000000000012031475274123300300660ustar00rootroot00000000000000package test; import java.util.ArrayList; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class InvokedMethodListener implements IInvokedMethodListener { private final List invokedMethods = new ArrayList<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { invokedMethods.add(method.getTestMethod().getMethodName()); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) {} public List getInvokedMethods() { return invokedMethods; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/InvokedMethodNameListener.java000066400000000000000000000153451475274123300307030ustar00rootroot00000000000000package test; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.collections.Lists; // TODO replace other test IInvokedMethodListener by this one public class InvokedMethodNameListener implements IInvokedMethodListener, ITestListener { private final Set testInstances = ConcurrentHashMap.newKeySet(); private final List foundMethodNames = Collections.synchronizedList(new ArrayList<>()); private final List invokedMethodNames = Collections.synchronizedList(new ArrayList<>()); private final List failedMethodNames = Collections.synchronizedList(new ArrayList<>()); private final List failedBeforeInvocationMethodNames = Collections.synchronizedList(new ArrayList<>()); private final List skippedMethodNames = Collections.synchronizedList(new ArrayList<>()); private final List skippedAfterInvocationMethodNames = Collections.synchronizedList(new ArrayList<>()); private final List succeedMethodNames = Collections.synchronizedList(new ArrayList<>()); private final Map results = new ConcurrentHashMap<>(); private final Map, List> mapping = new ConcurrentHashMap<>(); private final boolean skipConfiguration; private final boolean wantSkippedMethodAfterInvocation; public InvokedMethodNameListener() { this(false); } public InvokedMethodNameListener(boolean skipConfiguration) { this(skipConfiguration, false); } public InvokedMethodNameListener( boolean skipConfiguration, boolean wantSkippedMethodAfterInvocation) { this.skipConfiguration = skipConfiguration; this.wantSkippedMethodAfterInvocation = wantSkippedMethodAfterInvocation; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { if (!(skipConfiguration && method.isConfigurationMethod())) { invokedMethodNames.add(getName(testResult)); } testInstances.add(testResult.getInstance()); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { List methodNames = mapping.computeIfAbsent(testResult.getMethod().getRealClass(), k -> Lists.newArrayList()); methodNames.add(method.getTestMethod().getMethodName()); String name = getName(testResult); switch (testResult.getStatus()) { case ITestResult.FAILURE: if (!(skipConfiguration && method.isConfigurationMethod())) { failedMethodNames.add(name); } break; case ITestResult.SKIP: if (!(skipConfiguration && method.isConfigurationMethod())) { if (wantSkippedMethodAfterInvocation) { skippedAfterInvocationMethodNames.add(name); } } break; case ITestResult.SUCCESS: if (!(skipConfiguration && method.isConfigurationMethod())) { succeedMethodNames.add(name); } break; default: throw new AssertionError("Unexpected value: " + testResult.getStatus()); } } @Override public void onTestStart(ITestResult result) { foundMethodNames.add(getName(result)); } @Override public void onTestSuccess(ITestResult result) { String name = getName(result); results.put(name, result); if (!succeedMethodNames.contains(name)) { throw new IllegalStateException("A succeed test is supposed to be invoked"); } } @Override public void onTestFailure(ITestResult result) { String name = getName(result); results.put(name, result); if (!failedMethodNames.contains(name)) { failedBeforeInvocationMethodNames.add(name); } } @Override public void onTestSkipped(ITestResult result) { String name = getName(result); results.put(name, result); if (!skippedAfterInvocationMethodNames.contains(name)) { skippedMethodNames.add(name); } } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { String name = getName(result); results.put(name, result); if (!succeedMethodNames.contains(name) || !failedMethodNames.contains(name)) { throw new IllegalStateException( "A FailedButWithinSuccessPercentage test is supposed to be invoked"); } } @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} public Set getTestInstances() { return testInstances; } private static String getName(ITestResult result) { String testName = result.getName(); String methodName = result.getMethod().getConstructorOrMethod().getName(); String name; if (testName.contains(methodName)) { name = methodName; } else { name = testName + "#" + methodName; } if (result.getParameters().length != 0) { name = name + "(" + Joiner.on(",").useForNull("null").join(getParameterNames(result.getParameters())) + ")"; } return name; } private static List getParameterNames(Object[] parameters) { List result = new ArrayList<>(parameters.length); for (Object parameter : parameters) { if (parameter == null) { result.add("null"); } else { if (parameter instanceof Object[]) { result.add("[" + Joiner.on(",").useForNull("null").join((Object[]) parameter) + "]"); } else { result.add(parameter.toString()); } } } return result; } public List getInvokedMethodNames() { return Collections.unmodifiableList(invokedMethodNames); } public List getFailedMethodNames() { return Collections.unmodifiableList(failedMethodNames); } public List getSkippedMethodNames() { return Collections.unmodifiableList(skippedMethodNames); } public List getSucceedMethodNames() { return new ArrayList<>(succeedMethodNames); } public List getFailedBeforeInvocationMethodNames() { return Collections.unmodifiableList(failedBeforeInvocationMethodNames); } public List getSkippedAfterInvocationMethodNames() { return Collections.unmodifiableList(skippedAfterInvocationMethodNames); } public ITestResult getResult(String name) { return results.get(name); } public List getMethodsForTestClass(Class testClass) { return mapping.get(testClass); } public List getLogs(String name) { return Reporter.getOutput(getResult(name)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/JUnit4Test.java000066400000000000000000000037171475274123300256110ustar00rootroot00000000000000package test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.junit4.*; public class JUnit4Test extends BaseTest { @BeforeMethod(dependsOnGroups = {"initTest"}) public void initJUnitFlag() { getTest().setJUnit(true); } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] { new Class[] {JUnit4Sample2.class}, JUnit4Sample2.EXPECTED, JUnit4Sample2.FAILED, JUnit4Sample2.SKIPPED }, new Object[] { new Class[] {JUnit4SampleSuite.class}, JUnit4SampleSuite.EXPECTED, JUnit4SampleSuite.FAILED, JUnit4SampleSuite.SKIPPED }, new Object[] { new Class[] {JUnit4Child.class}, JUnit4Child.EXPECTED, new String[0], new String[0] }, new Object[] { new Class[] {InheritedTest.class, JUnit4Sample1.class}, new String[] {"t1", "t1"}, new String[0], new String[0] }, new Object[] { new Class[] {JUnit4ParameterizedTest.class}, JUnit4ParameterizedTest.EXPECTED, JUnit4ParameterizedTest.FAILED, JUnit4ParameterizedTest.SKIPPED }, new Object[] { new Class[] {BeforeClassJUnit4Sample.class}, new String[0], new String[0], new String[] {"myTest"} }, new Object[] { new Class[] {ClassRuleJUnit4Sample.class}, new String[0], new String[0], new String[] {"myTest"} } }; } @Test(dataProvider = "dp") public void testTests( Class[] classes, String[] expectedPassedTests, String[] expectedFailedTests, String[] expectedSkippedTests) { addClasses(classes); assert getTest().isJUnit(); run(); verifyPassedTests(expectedPassedTests); verifyFailedTests(expectedFailedTests); verifySkippedTests(expectedSkippedTests); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/JUnitTest1.java000066400000000000000000000056671475274123300256140ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import test.junit.SetNameTest; import test.sample.JUnitSample1; import test.sample.JUnitSample2; /** * This class * * @author Cedric Beust, May 5, 2004 */ public class JUnitTest1 extends BaseTest { @BeforeMethod(dependsOnGroups = {"initTest"}) public void initJUnitFlag() { getTest().setJUnit(true); } @Test public void methodsThatStartWithTest() { addClass("test.sample.JUnitSample1"); assert getTest().isJUnit(); run(); String[] passed = {JUnitSample1.EXPECTED1, JUnitSample1.EXPECTED2}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void methodsWithSetup() { addClass("test.sample.JUnitSample2"); run(); String[] passed = { "testSample2ThatSetUpWasRun", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void testSuite() { addClass("test.sample.AllJUnitTests"); run(); String[] passed = { JUnitSample1.EXPECTED1, /*JUnitSample1.EXPECTED2,*/ JUnitSample2.EXPECTED, }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void testNewInstance() { addClass("test.sample.JUnitSample3"); run(); String[] passed = {"test1", "test2"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void setUpFailingShouldCauseMethodsToBeSkipped() { addClass("test.junit.SetUpExceptionSampleTest"); run(); String[] passed = {}; String[] failed = {"testM1" /*, "testM1", "tearDown"*/}; String[] skipped = { /*"testM1", "tearDown"*/ }; verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void setNameShouldBeInvoked() { addClass("test.junit.SetNameTest"); SetNameTest.m_ctorCount = 0; run(); String[] passed = { "testFoo", "testBar", }; String[] failed = {}; String[] skipped = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); verifyTests("Failed", failed, getFailedTests()); Assert.assertEquals( SetNameTest.m_ctorCount, 2, "Expected 2 instances to be created, found " + SetNameTest.m_ctorCount); } @Test public void testAbstract() { addClass("test.sample.JUnitSample4"); run(); String[] passed = {"testXY", "testXY", "testXY"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/JUnitTestClassLoader.java000066400000000000000000000071601475274123300276360ustar00rootroot00000000000000package test; import static org.testng.Assert.*; import java.io.File; import java.util.List; import org.testng.*; import org.testng.annotations.Test; import testhelper.CompiledCode; import testhelper.SimpleCompiler; import testhelper.SourceCode; public class JUnitTestClassLoader extends ClassLoader { @Test public void testPassAndFail() throws Exception { String src = "import org.junit.Test;\n" + "import static org.junit.Assert.*;\n" + "public class SimpleTest1 {\n" + " @Test\n" + " public void test1() {\n" + " assertEquals(42, 42);\n" + " }\n" + " @Test\n" + " public void test2() {\n" + " assertEquals(42, 0);\n" + " }\n" + "}\n"; Listener listener = runJunitTest(src, "SimpleTest1"); assertEquals(1, listener.success); assertEquals(1, listener.failure); } @Test public void testFail() throws Exception { String src = "import org.junit.Test;\n" + "import static org.junit.Assert.*;\n" + "public class SimpleTest2 {\n" + " @Test\n" + " public void test() {\n" + " assertEquals(42, 0);\n" + " }\n" + "}\n"; Listener listener = runJunitTest(src, "SimpleTest2"); assertEquals(0, listener.success); assertEquals(1, listener.failure); } @Test public void testPass() throws Exception { String src = "import org.junit.Test;\n" + "import static org.junit.Assert.*;\n" + "public class SimpleTest3 {\n" + " @Test\n" + " public void test() {\n" + " assertEquals(42, 42);\n" + " }\n" + "}\n"; Listener listener = runJunitTest(src, "SimpleTest3"); assertEquals(1, listener.success); assertEquals(0, listener.failure); } private Listener runJunitTest(String src, String name) throws Exception { TestNG tng = new TestNG(false); Class testClass = compile(src, name); Listener listener = new Listener(); tng.setJUnit(true); tng.addClassLoader(testClass.getClassLoader()); assertNotEquals( testClass.getClassLoader(), this.getClass().getClassLoader(), "JUnit test must be loaded by a different classloader"); try { this.getClass().getClassLoader().loadClass(testClass.getName()); fail("it must be imposiible to load JUnit test by current classloader"); } catch (ClassNotFoundException c) { } tng.setTestClasses(new Class[] {testClass}); tng.addListener(listener); tng.run(); return listener; } private Class compile(String src, String name) throws Exception { File directory = SimpleCompiler.createTempDir(); SourceCode sourceCode = new SourceCode(name, src, directory, false); List compiledCode = SimpleCompiler.compileSourceCode(sourceCode); byte[] bytes = compiledCode.get(0).getByteCode(); return defineClass(name, bytes, 0, bytes.length); } private static class Listener implements ITestListener { public int success = 0; public int failure = 0; public void onTestSuccess(ITestResult result) { success++; } public void onTestFailure(ITestResult result) { failure++; } public void onTestStart(ITestResult result) {} public void onTestSkipped(ITestResult result) {} public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} public void onStart(ITestContext context) {} public void onFinish(ITestContext context) {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/MethodTest.java000066400000000000000000000025031475274123300257040ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.annotations.Test; import test.sample.Sample2; public class MethodTest extends BaseTest { private static final String CLASS_NAME = Sample2.class.getName(); @Test(groups = {"current"}) public void includeMethodsOnly() { addClass(CLASS_NAME); Assert.assertEquals(getTest().getXmlClasses().size(), 1); addIncludedMethod(CLASS_NAME, ".*method2"); run(); String[] passed = { "method2", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test(groups = {"current"}) public void excludeMethodsOnly() { addClass(CLASS_NAME); Assert.assertEquals(getTest().getXmlClasses().size(), 1); addExcludedMethod(CLASS_NAME, ".*method2"); run(); String[] passed = {"method1", "method3"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void excludePackage() { addClass(CLASS_NAME); assert 1 == getTest().getXmlClasses().size(); addExcludedMethod(CLASS_NAME, ".*"); run(); String[] passed = {}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/Misc.java000066400000000000000000000012161475274123300245170ustar00rootroot00000000000000package test; import org.testng.annotations.Test; /** * This class * * @author cbeust */ public class Misc extends BaseTest { @Test public void makeSureSetUpWithParameterWithNoParametersFails() { addClass("test.sample.SetUpWithParameterTest"); // setParallel(XmlSuite.PARALLEL_METHODS); run(); String[] passed = {}; // @Configuration failures are not reported in the ITestListener String[] failed = {}; String[] skipped = { "test", }; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Failed", skipped, getSkippedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/NestedStaticSampleTest.java000066400000000000000000000002751475274123300302240ustar00rootroot00000000000000package test; import org.testng.annotations.Test; public class NestedStaticSampleTest { @Test public void f() {} public class Nested { @Test public void nested() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/NestedStaticTest.java000066400000000000000000000016471475274123300270660ustar00rootroot00000000000000package test; import java.util.HashSet; import java.util.List; import java.util.Set; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Sets; public class NestedStaticTest extends SimpleBaseTest { @Test public void nestedClassShouldBeIncluded() { TestNG tng = create(NestedStaticSampleTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Set expected = new HashSet() { { add("nested"); add("f"); } }; Set actual = Sets.newHashSet(); List passedTests = tla.getPassedTests(); for (ITestResult t : passedTests) { actual.add(t.getMethod().getMethodName()); } Assert.assertEquals(actual, expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ParameterConstructorTest.java000066400000000000000000000023211475274123300306500ustar00rootroot00000000000000package test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * Test parameters passed to constructors * * @author cbeust */ public class ParameterConstructorTest { private String m_string; private int m_int; private boolean m_boolean; private byte m_byte; private char m_char; private double m_double; private float m_float; private long m_long; private short m_short; @Parameters({"string", "int", "boolean", "byte", "char", "double", "float", "long", "short"}) public ParameterConstructorTest( String s, int i, boolean bo, byte b, char c, double d, float f, long l, short sh) { m_string = s; m_int = i; m_boolean = bo; m_byte = b; m_char = c; m_double = d; m_float = f; m_long = l; m_short = sh; } @Test public void verify() { assertEquals("Cedric", m_string); assertEquals(42, m_int); assertTrue(m_boolean); assertEquals(43, m_byte); assertEquals('c', m_char); assertEquals(44.0, m_double, 0.1); assertEquals(45.0f, m_float, 0.1); assertEquals(46, m_long); assertEquals(47, m_short); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ReflectionHelperTest.java000066400000000000000000000041721475274123300277220ustar00rootroot00000000000000package test; import java.lang.reflect.Method; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.internal.reflect.ReflectionHelper; import test.github1405.TestClassSample; import test.github765.DuplicateCallsSample; public class ReflectionHelperTest { @Test public void testMethodCount() { // Testing exclusion of synthetic methods Refer https://stackoverflow.com/a/5007394 to learn // more Method[] methods = prune(ReflectionHelper.getLocalMethods(DuplicateCallsSample.class)); Assert.assertEquals(methods.length, 2); // Testing a straight forward use case of retrieving concrete methods methods = prune(ReflectionHelper.getLocalMethods(Dog.class)); Assert.assertEquals(methods.length, 1); // When class has no methods count should be zero. methods = prune(ReflectionHelper.getLocalMethods(Dinosaur.class)); Assert.assertEquals(methods.length, 0); // Abstract methods should be included. methods = prune(ReflectionHelper.getLocalMethods(Dragon.class)); Assert.assertEquals(methods.length, 2); // main methods should be pruned methods = prune(ReflectionHelper.getLocalMethods(TestClassSample.class)); Assert.assertEquals(methods.length, 1); } /** * @param methods - The list of methods extracted from a Class * @return - A {@link Method} array which excludes a special method named "jacocoInit" which is * getting injected into the test class only when the test is executed via Gradle. */ private static Method[] prune(Method[] methods) { List pruned = Lists.newArrayList(methods.length); for (Method method : methods) { if (!method.getName().contains("jacocoInit")) { pruned.add(method); } } return pruned.toArray(new Method[0]); } interface Animal { void makeSound(); } class Dog implements Animal { @Override public void makeSound() {} } abstract class Dinosaur implements Animal {} abstract class Dragon implements Animal { @Override public void makeSound() {} abstract void walk(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ReporterApiTest.java000066400000000000000000000005771475274123300267310ustar00rootroot00000000000000package test; import org.testng.Reporter; import org.testng.annotations.Test; /** * Make sure we don't remove public API's from Reporter. * * @author Cedric Beust */ public class ReporterApiTest { @Test public void testApi() { Reporter.log("foo"); Reporter.log("foo", false); Reporter.log("foo", 2); Reporter.log("foo", 2, false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ReturnValueSampleTest.java000066400000000000000000000002211475274123300300750ustar00rootroot00000000000000package test; import org.testng.annotations.Test; public class ReturnValueSampleTest { @Test public int shouldRun() { return 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ReturnValueTest.java000066400000000000000000000030121475274123300267340ustar00rootroot00000000000000package test; import java.util.Collections; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class ReturnValueTest extends SimpleBaseTest { private XmlSuite m_suite; private XmlTest m_test; @BeforeMethod public void before() { m_suite = createXmlSuite("suite"); m_test = createXmlTest(m_suite, "test", ReturnValueSampleTest.class.getName()); } @Test public void suiteReturnValueTestShouldBeRun() { m_suite.setAllowReturnValues(true); runTest(true); } @Test public void suiteReturnValueTestShouldNotBeRun() { runTest(false); } @Test public void testReturnValueTestShouldBeRun() { m_test.setAllowReturnValues(true); runTest(true); } private void runTest(boolean allowed) { TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(m_suite)); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); if (allowed) { Assert.assertEquals(tla.getFailedTests().size(), 0); Assert.assertEquals(tla.getSkippedTests().size(), 0); assertTestResultsEqual(tla.getPassedTests(), Collections.singletonList("shouldRun")); } else { Assert.assertEquals(tla.getFailedTests().size(), 0); Assert.assertEquals(tla.getPassedTests().size(), 0); Assert.assertEquals(tla.getSkippedTests().size(), 0); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/SampleInheritance.java000066400000000000000000000031331475274123300272170ustar00rootroot00000000000000package test; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import test.sample.BaseSampleInheritance; public class SampleInheritance extends BaseSampleInheritance { // Test dependency of configuration methods @BeforeClass(groups = {"configuration0"}) public void configuration0() { addConfiguration("configuration0"); // System.out.println("CONFIGURATION 0"); } @BeforeClass( groups = "final", dependsOnGroups = {"configuration1"}) public void configuration2() { assert m_configurations.size() == 2 : "Expected size 2 found " + m_configurations.size(); assert "configuration0".equals(m_configurations.get(0)) : "Expected configuration0 to be run"; assert "configuration1".equals(m_configurations.get(1)) : "Expected configuration1 to be run"; addConfiguration("configuration2"); } @Test( groups = "final", dependsOnGroups = {"inheritedTestMethod"}) public void inheritedMethodsWereCalledInOrder() { assert m_invokedBaseMethod : "Didn't invoke test method in base class"; assert m_invokedBaseConfiguration : "Didn't invoke configuration method in base class"; } @Test(groups = "final2", dependsOnGroups = "final") public void configurationsWereCalledInOrder() { assert m_configurations.size() == 3; assert "configuration0".equals(m_configurations.get(0)) : "Expected configuration0 to be run"; assert "configuration1".equals(m_configurations.get(1)) : "Expected configuration1 to be run"; assert "configuration2".equals(m_configurations.get(2)) : "Expected configuration1 to be run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/SerializationTest.java000066400000000000000000000015121475274123300273000ustar00rootroot00000000000000package test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import org.testng.ITestContext; import org.testng.annotations.Test; public class SerializationTest { @Test(groups = "broken") public void iSuiteShouldBeSerializable(ITestContext context) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(context.getSuite()); oos.close(); } @Test(groups = {"broken", "maven-broken"}) public void testngMethodShouldBeSerializable(ITestContext context) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(context.getAllTestMethods()[0]); oos.close(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/SimpleBaseTest.java000066400000000000000000000337531475274123300265230ustar00rootroot00000000000000package test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.testng.Assert; import org.testng.ITestNGMethod; import org.testng.ITestObjectFactory; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.ITestAnnotation; import org.testng.collections.Lists; import org.testng.internal.annotations.AnnotationHelper; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.xml.XmlClass; import org.testng.xml.XmlGroups; import org.testng.xml.XmlInclude; import org.testng.xml.XmlPackage; import org.testng.xml.XmlRun; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.testng.xml.internal.Parser; public class SimpleBaseTest { // System property specifying where the resources (e.g. xml files) can be found private static final String TEST_RESOURCES_DIR = "test.resources.dir"; public static InvokedMethodNameListener run(Class... testClasses) { return run(false, testClasses); } public static InvokedMethodNameListener run(boolean skipConfiguration, Class... testClasses) { TestNG tng = create(testClasses); return run(skipConfiguration, tng); } public static InvokedMethodNameListener run(XmlSuite... suites) { return run(false, suites); } public static InvokedMethodNameListener run(boolean skipConfiguration, XmlSuite... suites) { TestNG tng = create(suites); return run(skipConfiguration, tng); } private static InvokedMethodNameListener run(boolean skipConfiguration, TestNG tng) { InvokedMethodNameListener listener = new InvokedMethodNameListener(skipConfiguration); tng.addListener(listener); tng.run(); return listener; } public static TestNG create() { TestNG result = new TestNG(); result.setUseDefaultListeners(false); return result; } public static TestNG create(Class... testClasses) { TestNG result = create(); result.setTestClasses(testClasses); return result; } protected static TestNG create(Path outputDir, Class... testClasses) { TestNG result = create(testClasses); result.setOutputDirectory(outputDir.toAbsolutePath().toString()); return result; } protected static TestNG create(XmlSuite... suites) { return create(Arrays.asList(suites)); } protected static TestNG create(List suites) { TestNG result = create(); result.setXmlSuites(suites); return result; } protected static TestNG create(Path outputDir, XmlSuite... suites) { return create(outputDir, Arrays.asList(suites)); } protected static TestNG create(Path outputDir, List suites) { TestNG result = create(suites); result.setOutputDirectory(outputDir.toAbsolutePath().toString()); return result; } protected static TestNG createTests(String suiteName, Class... testClasses) { return createTests(null, suiteName, testClasses); } protected static TestNG createTests(Path outDir, String suiteName, Class... testClasses) { XmlSuite suite = createXmlSuite(suiteName); int i = 0; for (Class testClass : testClasses) { createXmlTest(suite, testClass.getName() + i, testClass); i++; } if (outDir == null) { return create(suite); } return create(outDir, suite); } protected static XmlSuite createDummySuiteWithTestNamesAs(String... tests) { XmlSuite suite = new XmlSuite(); suite.setName("random_suite"); for (String test : tests) { XmlTest xmlTest = new XmlTest(suite); xmlTest.setName(test); } return suite; } protected static XmlSuite createXmlSuite(String name) { XmlSuite result = new XmlSuite(); result.setName(name); return result; } protected static XmlSuite createXmlSuite(Map params) { XmlSuite result = createXmlSuite(UUID.randomUUID().toString()); result.setParameters(params); return result; } protected static XmlSuite createXmlSuite(String suiteName, String testName, Class... classes) { XmlSuite suite = createXmlSuite(suiteName); createXmlTest(suite, testName, classes); return suite; } protected static XmlSuite createXmlSuite(String suiteName, Map params) { XmlSuite suite = createXmlSuite(suiteName); suite.setParameters(params); return suite; } protected static XmlTest createXmlTestWithPackages( XmlSuite suite, String name, String... packageName) { XmlTest result = createXmlTest(suite, name); List xmlPackages = Lists.newArrayList(); for (String each : packageName) { XmlPackage xmlPackage = new XmlPackage(); xmlPackage.setName(each); xmlPackages.add(xmlPackage); } result.setPackages(xmlPackages); return result; } protected static XmlTest createXmlTestWithPackages( XmlSuite suite, String name, Class... packageName) { XmlTest result = createXmlTest(suite, name); List xmlPackages = Lists.newArrayList(); for (Class each : packageName) { XmlPackage xmlPackage = new XmlPackage(); xmlPackage.setName(each.getPackage().getName()); xmlPackages.add(xmlPackage); } result.setPackages(xmlPackages); return result; } protected static XmlTest createXmlTest(String suiteName, String testName) { XmlSuite suite = createXmlSuite(suiteName); return createXmlTest(suite, testName); } protected static XmlTest createXmlTest(String suiteName, String testName, Class... classes) { XmlSuite suite = createXmlSuite(suiteName); XmlTest xmlTest = createXmlTest(suite, testName); for (Class clazz : classes) { xmlTest.getXmlClasses().add(new XmlClass(clazz)); } return xmlTest; } protected static XmlTest createXmlTest(XmlSuite suite, String name) { XmlTest result = new XmlTest(suite); result.setName(name); return result; } protected static XmlTest createXmlTest(XmlSuite suite, String name, Map params) { XmlTest result = new XmlTest(suite); result.setName(name); result.setParameters(params); return result; } protected static XmlTest createXmlTest(XmlSuite suite, String name, Class... classes) { XmlTest result = createXmlTest(suite, name); int index = 0; for (Class c : classes) { XmlClass xc = new XmlClass(c.getName(), index++, true /* load classes */); result.getXmlClasses().add(xc); } return result; } protected static XmlClass createXmlClass(XmlTest test, Class testClass) { XmlClass clazz = new XmlClass(testClass); test.getXmlClasses().add(clazz); return clazz; } protected static XmlClass createXmlClass( XmlTest test, Class testClass, Map params) { XmlClass clazz = createXmlClass(test, testClass); clazz.setParameters(params); return clazz; } protected static XmlInclude createXmlInclude(XmlClass clazz, String method) { XmlInclude include = new XmlInclude(method); include.setXmlClass(clazz); clazz.getIncludedMethods().add(include); return include; } protected static XmlInclude createXmlInclude( XmlClass clazz, String method, Map params) { XmlInclude include = createXmlInclude(clazz, method); include.setParameters(params); return include; } protected static XmlInclude createXmlInclude( XmlClass clazz, String method, int index, Integer... list) { XmlInclude include = new XmlInclude(method, Arrays.asList(list), index); include.setXmlClass(clazz); clazz.getIncludedMethods().add(include); return include; } protected static XmlGroups createXmlGroups(XmlSuite suite, String... includedGroupNames) { XmlGroups xmlGroups = createGroupIncluding(includedGroupNames); suite.setGroups(xmlGroups); return xmlGroups; } protected static XmlGroups createXmlGroups(XmlTest test, String... includedGroupNames) { XmlGroups xmlGroups = createGroupIncluding(includedGroupNames); test.setGroups(xmlGroups); return xmlGroups; } private static XmlGroups createGroupIncluding(String... groupNames) { XmlGroups xmlGroups = new XmlGroups(); XmlRun xmlRun = new XmlRun(); for (String group : groupNames) { xmlRun.onInclude(group); } xmlGroups.setRun(xmlRun); return xmlGroups; } protected static XmlTest createXmlTest(XmlSuite suite, String name, String... classes) { XmlTest result = createXmlTest(suite, name); int index = 0; for (String c : classes) { XmlClass xc = new XmlClass(c, index++, true /* load classes */); result.getXmlClasses().add(xc); } return result; } protected static void addMethods(XmlClass cls, String... methods) { int index = 0; for (String method : methods) { XmlInclude include = new XmlInclude(method, index++); cls.getIncludedMethods().add(include); } } public static String getPathToResource(String fileName) { String result = System.getProperty(TEST_RESOURCES_DIR, "src/test/resources"); if (result == null) { throw new IllegalArgumentException( "System property " + TEST_RESOURCES_DIR + " was not defined."); } return result + File.separatorChar + fileName; } public static List extractTestNGMethods(Class... classes) { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "tests", classes); IAnnotationFinder annotationFinder = new JDK15AnnotationFinder(new DefaultAnnotationTransformer()); List methods = Lists.newArrayList(); for (Class clazz : classes) { methods.addAll( Arrays.asList( AnnotationHelper.findMethodsWithAnnotation( new ITestObjectFactory() {}, clazz, ITestAnnotation.class, annotationFinder, xmlTest))); } return methods; } /** Compare a list of ITestResult with a list of String method names, */ protected static void assertTestResultsEqual(List results, List methods) { List resultMethods = Lists.newArrayList(); for (ITestResult r : results) { resultMethods.add(r.getMethod().getMethodName()); } Assert.assertEquals(resultMethods, methods); } /** Deletes all files and subdirectories under dir. */ protected static void deleteDir(File dir) { try { Files.walkFileTree( dir.toPath(), new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } } protected static File createDirInTempDir(String dir) { File slashTmpDir = new File(System.getProperty("java.io.tmpdir")); File mTempDirectory = new File(slashTmpDir, dir); mTempDirectory.mkdirs(); mTempDirectory.deleteOnExit(); return mTempDirectory; } /** * @param fileName The filename to parse * @param regexp The regular expression * @param resultLines An out parameter that will contain all the lines that matched the regexp * @return A List containing the lines of all the matches *

Note that the size() of the returned valuewill always be equal to result.size() at the * end of this function. */ protected static List grep(File fileName, String regexp, List resultLines) { List resultLineNumbers = new ArrayList<>(); try (Reader reader = new FileReader(fileName)) { resultLineNumbers = grep(reader, regexp, resultLines); } catch (IOException e) { e.printStackTrace(); } return resultLineNumbers; } protected static List grep(Reader reader, String regexp, List resultLines) { List resultLineNumbers = new ArrayList<>(); try (BufferedReader fr = new BufferedReader(reader)) { String line; int currentLine = 0; Pattern p = Pattern.compile(".*" + regexp + ".*"); while ((line = fr.readLine()) != null) { if (p.matcher(line).matches()) { resultLines.add(line); resultLineNumbers.add(currentLine); } currentLine++; } } catch (IOException e) { e.printStackTrace(); } return resultLineNumbers; } protected static List getSuites(String... suiteFiles) { List suites = new ArrayList<>(); for (String suiteFile : suiteFiles) { try { suites.addAll(new Parser(suiteFile).parseToList()); } catch (IOException e) { throw new TestNGException(e); } } return suites; } protected static String getFailedResultMessage(List testResultList) { String methods = testResultList.stream() .map( r -> new AbstractMap.SimpleEntry<>( r.getMethod().getQualifiedName(), r.getThrowable())) .map(e -> String.format("%s: %s", e.getKey(), e.getValue())) .collect(Collectors.joining("\n")); return String.format("Failed methods should pass:\n %s\n", methods); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/StaticTest.java000066400000000000000000000003471475274123300257170ustar00rootroot00000000000000package test; import org.testng.annotations.Test; /** This used to create a StackOverflowError. */ public class StaticTest { @Test public void test() {} @Test public static class InnerStaticClass extends StaticTest {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/Test1.java000066400000000000000000000116031475274123300246250ustar00rootroot00000000000000package test; import static org.assertj.core.api.Assertions.assertThat; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.sample.Sample1; public class Test1 extends SimpleBaseTest { /** * This constructor is package protected on purpose, to test that TestNG can still instantiate the * class. */ Test1() {} @Test(groups = {"current"}) public void includedGroups() { XmlSuite suite = createXmlSuite("Internal_suite"); XmlTest test = createXmlTest(suite, "Internal_test_failures_are_expected", Sample1.class); Assert.assertEquals(test.getXmlClasses().size(), 1); test.addIncludedGroup("odd"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("method1", "method3"); assertThat(listener.getFailedMethodNames()).isEmpty(); } @Test public void groupsOfGroupsSimple() { XmlSuite suite = createXmlSuite("Internal_suite"); XmlTest test = createXmlTest(suite, "Internal_test_failures_are_expected", Sample1.class); Assert.assertEquals(test.getXmlClasses().size(), 1); // should match all methods belonging to group "odd" and "even" test.addIncludedGroup("evenodd"); test.addMetaGroup("evenodd", "even", "odd"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("method1", "method2", "method3"); assertThat(listener.getFailedMethodNames()).isEmpty(); } @Test public void groupsOfGroupsWithIndirections() { XmlSuite suite = createXmlSuite("Internal_suite"); XmlTest test = createXmlTest(suite, "Internal_test_failures_are_expected", Sample1.class); test.addIncludedGroup("all"); test.addMetaGroup("all", "methods", "broken"); test.addMetaGroup("methods", "odd", "even"); test.addMetaGroup("broken", "broken"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()) .containsExactly("method1", "broken", "method2", "method3"); assertThat(listener.getFailedMethodNames()).isEmpty(); } @Test public void groupsOfGroupsWithCycle() { XmlSuite suite = createXmlSuite("Internal_suite"); XmlTest test = createXmlTest(suite, "Internal_test_failures_are_expected", Sample1.class); test.addIncludedGroup("all"); test.addMetaGroup("all", "all2"); test.addMetaGroup("all2", "methods"); test.addMetaGroup("methods", "all"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).isEmpty(); } @Test public void excludedGroups() { XmlSuite suite = createXmlSuite("Internal_suite"); XmlTest test = createXmlTest(suite, "Internal_test_failures_are_expected", Sample1.class); test.addExcludedGroup("odd"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(true); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()) .containsExactly( "broken", "method2", "throwExpectedException1ShouldPass", "throwExpectedException2ShouldPass"); assertThat(listener.getFailedMethodNames()) .containsExactly("throwExceptionShouldFail", "verifyLastNameShouldFail"); } @Test public void regexp() { XmlSuite suite = createXmlSuite("Internal_suite"); XmlTest test = createXmlTest(suite, "Internal_test_failures_are_expected", Sample1.class); // should matches all methods belonging to group "odd" test.addIncludedGroup("o.*"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("method1", "method3"); assertThat(listener.getFailedMethodNames()).isEmpty(); } @Test(groups = {"currentold"}) public void logger() { Logger logger = Logger.getLogger(""); for (Handler handler : logger.getHandlers()) { handler.setLevel(Level.WARNING); handler.setFormatter(new org.testng.log.TextFormatter()); } logger.setLevel(Level.SEVERE); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/Test2.java000066400000000000000000000037561475274123300246400ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** @author Cedric Beust, May 5, 2004 */ public class Test2 extends BaseTest { private boolean m_initializedCorrectly = false; @BeforeMethod public void correctSetup() { m_initializedCorrectly = true; } // Shouldn't be called @BeforeMethod(groups = {"excludeThisGroup"}) public void incorrectSetup() { throw new RuntimeException("Should never be run"); } @Test public void noGroups() { addClass("test.sample.Sample1"); run(); String[] passed = { "method1", "method2", "method3", "broken", "throwExpectedException1ShouldPass", "throwExpectedException2ShouldPass" }; String[] failed = {"throwExceptionShouldFail", "verifyLastNameShouldFail"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void setUpWithGroups() { run(); Assert.assertTrue(m_initializedCorrectly, "Should have run the correctSetup method"); } @Test public void partialGroupsClass() { addClass("test.sample.PartialGroupTest"); addIncludedGroup("classGroup"); run(); String[] passed = {"testMethodGroup", "testClassGroup"}; String[] failed = {"testMethodGroupShouldFail", "testClassGroupShouldFail"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); // ppp("@@@@@@@@@@@@@@@@@@ PASSED TESTS"); // for (Object o : getPassedTests().values()) { // ppp("@@@@@@@@@@ PASSED:" + o); // } } @Test public void partialGroupsMethod() { addClass("test.sample.PartialGroupTest"); addIncludedGroup("methodGroup"); run(); String[] passed = { "testMethodGroup", }; String[] failed = {"testMethodGroupShouldFail"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/TestClassContainerForGitHubIssue1360.java000066400000000000000000000021061475274123300324700ustar00rootroot00000000000000package test; import org.testng.Assert; import org.testng.annotations.Test; public class TestClassContainerForGitHubIssue1360 { public static class TestNG1 { @Test(priority = 1) public void test1TestNG1() { Assert.assertTrue(true); } @Test(priority = 2) public void test2TestNG1() { Assert.assertTrue(true); } @Test(priority = 3) public void test3TestNG1() { Assert.assertTrue(true); } } public static class TestNG2 { @Test(priority = 1) public void test1TestNG2() { Assert.assertTrue(true); } @Test(priority = 2) public void test2TestNG2() { Assert.assertTrue(true); } @Test(priority = 3) public void test3TestNG2() { Assert.assertTrue(true); } } public static class TestNG3 { @Test(priority = 1) public void test1TestNG3() { Assert.assertTrue(true); } @Test(priority = 2) public void test2TestNG3() { Assert.assertTrue(true); } @Test(priority = 3) public void test3TestNG3() { Assert.assertTrue(true); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/TestHelper.java000066400000000000000000000031651475274123300257100ustar00rootroot00000000000000package test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import org.testng.TestNG; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class TestHelper { /* * TestNG issues a warning if the XML misses DOCTYPE, so here's a common header for * xml suites generated in the tests. */ public static final String SUITE_XML_HEADER = "\n" + "\n"; public static XmlSuite createSuite(String cls, String suiteName) { XmlSuite result = new XmlSuite(); result.setName(suiteName); XmlTest test = new XmlTest(result); test.setName("TmpTest"); test.setXmlClasses(Collections.singletonList(new XmlClass(cls))); return result; } public static TestNG createTestNG() throws IOException { return createTestNG(createRandomDirectory()); } public static TestNG createTestNG(XmlSuite suite) throws IOException { return createTestNG(suite, createRandomDirectory()); } public static TestNG createTestNG(XmlSuite suite, Path outputDir) { TestNG result = createTestNG(outputDir); result.setXmlSuites(Collections.singletonList(suite)); return result; } private static TestNG createTestNG(Path outputDir) { TestNG result = new TestNG(); result.setOutputDirectory(outputDir.toAbsolutePath().toString()); return result; } public static Path createRandomDirectory() throws IOException { return Files.createTempDirectory("testng-tmp-"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractconfmethod/000077500000000000000000000000001475274123300266335ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractconfmethod/B.java000066400000000000000000000003641475274123300276620ustar00rootroot00000000000000package test.abstractconfmethod; import org.testng.annotations.BeforeMethod; import test.abstractconfmethod.foo.A; public abstract class B extends A { @BeforeMethod(dependsOnMethods = {"testSetup"}) public void doSomethingInMiddle() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractconfmethod/C.java000066400000000000000000000005041475274123300276570ustar00rootroot00000000000000package test.abstractconfmethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class C extends B { @Override @BeforeMethod public void testSetup() {} @Test(description = "Test depends on a config method that has implements an abstract methods") public void test1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractconfmethod/foo/000077500000000000000000000000001475274123300274165ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractconfmethod/foo/A.java000066400000000000000000000001461475274123300304420ustar00rootroot00000000000000package test.abstractconfmethod.foo; public abstract class A { public abstract void testSetup(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractmethods/000077500000000000000000000000001475274123300261505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractmethods/AbstractTest.java000066400000000000000000000010571475274123300314210ustar00rootroot00000000000000package test.abstractmethods; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class AbstractTest extends SimpleBaseTest { @Test(description = "Abstract methods defined in a superclass should be run") public void abstractShouldRun() { TestNG tng = create(CRUDTest2.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractmethods/CRUDTest.java000066400000000000000000000003261475274123300304110ustar00rootroot00000000000000package test.abstractmethods; import org.testng.annotations.Test; public abstract class CRUDTest { @Test public abstract void create(); @Test(dependsOnMethods = "create") public abstract void read(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/abstractmethods/CRUDTest2.java000066400000000000000000000002271475274123300304730ustar00rootroot00000000000000package test.abstractmethods; public class CRUDTest2 extends CRUDTest { @Override public void create() {} @Override public void read() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/access/000077500000000000000000000000001475274123300242225ustar00rootroot00000000000000BasePrivateAccessConfigurationMethods.java000066400000000000000000000010251475274123300344070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/accesspackage test.access; import org.testng.annotations.BeforeMethod; public class BasePrivateAccessConfigurationMethods { protected boolean m_baseProtected = false; protected boolean m_baseDefault = false; protected boolean m_basePrivate = true; @BeforeMethod void baseDefaultConfBeforeMethod() { m_baseDefault = true; } @BeforeMethod protected void baseProtectedConfBeforeMethod() { m_baseProtected = true; } @BeforeMethod private void basePrivateConfBeforeMethod() { m_basePrivate = false; } } PrivateAccessConfigurationMethods.java000066400000000000000000000027051475274123300336220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/accesspackage test.access; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test that private and protected @Configuration methods are run * * @author cbeust */ public class PrivateAccessConfigurationMethods extends BasePrivateAccessConfigurationMethods { private boolean m_private = false; private boolean m_default = false; private boolean m_protected = false; private boolean m_public = false; @BeforeMethod private void privateConfBeforeMethod() { m_private = true; } @BeforeMethod void defaultConfBeforeMethod() { m_default = true; } @BeforeMethod protected void protectedConfBeforeMethod() { m_protected = true; } @BeforeMethod public void publicConfBeforeMethod() { m_public = true; } @Test public void allAccessModifiersConfiguration() { Assert.assertTrue(m_private, "private @Configuration should have been run"); Assert.assertTrue(m_default, "default @Configuration should have been run"); Assert.assertTrue(m_protected, "protected @Configuration should have been run"); Assert.assertTrue(m_public, "public @Configuration should have been run"); Assert.assertTrue(m_baseProtected, "protected base @Configuration should have been run"); Assert.assertTrue(m_baseDefault, "default base @Configuration should have been run"); Assert.assertTrue(m_basePrivate, "private base @Configuration should not have been run"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/000077500000000000000000000000001475274123300253225ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/AfterGroupsBehaviorTest.java000066400000000000000000000033021475274123300327440ustar00rootroot00000000000000package test.aftergroups; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.FailurePolicy; import test.SimpleBaseTest; import test.aftergroups.issue165.TestclassSampleWithFailedMember; import test.aftergroups.issue165.TestclassSampleWithSkippedMember; import test.aftergroups.issue1880.LocalConfigListener; import test.aftergroups.issue1880.TestClassSample; public class AfterGroupsBehaviorTest extends SimpleBaseTest { @Test(description = "GITHUB-1880") public void ensureAfterGroupsAreInvokedWithAlwaysRunAttribute() { runTest(TestClassSample.class, "123", true, "after"); } @Test(dataProvider = "dp", description = "GITHUB-165") public void ensureAfterGroupsInvoked(Class clazz, String expected) { runTest(clazz, "A", false, expected); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { {TestclassSampleWithSkippedMember.class, "afterGroupsMethod"}, {TestclassSampleWithFailedMember.class, "afterGroupsMethod"}, }; } private static void runTest( Class clazz, String groups, boolean shouldContinue, String expected) { XmlSuite xmlsuite = createXmlSuite("sample_suite", "sample_test", clazz); xmlsuite.addIncludedGroup(groups); TestNG testng = create(xmlsuite); if (shouldContinue) { testng.setConfigFailurePolicy(FailurePolicy.CONTINUE); } LocalConfigListener listener = new LocalConfigListener(); testng.addListener(listener); testng.run(); assertThat(listener.getMessages()).containsExactly(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/issue165/000077500000000000000000000000001475274123300267065ustar00rootroot00000000000000TestclassSampleWithFailedMember.java000066400000000000000000000006161475274123300356750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/issue165package test.aftergroups.issue165; import org.testng.annotations.AfterGroups; import org.testng.annotations.Test; public class TestclassSampleWithFailedMember { @Test(groups = "A") public void a1() {} @Test(groups = "A", dependsOnMethods = "a1") public void a2() { throw new org.testng.SkipException("skip"); } @AfterGroups(groups = "A") public void afterGroupsMethod() {} } TestclassSampleWithSkippedMember.java000066400000000000000000000006171475274123300361110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/issue165package test.aftergroups.issue165; import org.testng.annotations.AfterGroups; import org.testng.annotations.Test; public class TestclassSampleWithSkippedMember { @Test(groups = "A") public void a1() { throw new org.testng.SkipException("skip"); } @Test(groups = "A", dependsOnMethods = "a1") public void a2() {} @AfterGroups(groups = "A") public void afterGroupsMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/issue1880/000077500000000000000000000000001475274123300267735ustar00rootroot00000000000000LocalConfigListener.java000066400000000000000000000007471475274123300334550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/issue1880package test.aftergroups.issue1880; import java.util.List; import org.testng.IConfigurationListener; import org.testng.ITestResult; import org.testng.collections.Lists; public class LocalConfigListener implements IConfigurationListener { private List messages = Lists.newLinkedList(); @Override public void onConfigurationSuccess(ITestResult itr) { messages.add(itr.getMethod().getMethodName()); } public List getMessages() { return messages; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/aftergroups/issue1880/TestClassSample.java000066400000000000000000000006731475274123300327130ustar00rootroot00000000000000package test.aftergroups.issue1880; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class TestClassSample { @BeforeGroups(groups = "123") public void before() throws Exception { throw new Exception("forcing a failure"); } @Test(groups = "123") public void test() {} @AfterGroups(groups = "123", alwaysRun = true) public void after() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/alwaysrun/000077500000000000000000000000001475274123300250065ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/alwaysrun/AlwaysRunAfter1.java000066400000000000000000000011011475274123300306320ustar00rootroot00000000000000package test.alwaysrun; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class AlwaysRunAfter1 { private static boolean m_success = false; @BeforeClass public void setUpShouldFail() { throw new RuntimeException("Failing in setUp"); } @AfterClass(alwaysRun = true) public void tearDown() { m_success = true; } // Adding this method or @Configuration will never be invoked @Test public void dummy() {} public static boolean success() { return m_success; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/alwaysrun/AlwaysRunAfter2.java000066400000000000000000000007011475274123300306400ustar00rootroot00000000000000package test.alwaysrun; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class AlwaysRunAfter2 { private static boolean m_success = true; @BeforeClass public void setUpShouldFail() { throw new RuntimeException("Failing in setUp"); } // Should not be run @AfterClass public void tearDown() { m_success = false; } public static boolean success() { return m_success; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/alwaysrun/AlwaysRunAfter3.java000066400000000000000000000010271475274123300306430ustar00rootroot00000000000000package test.alwaysrun; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class AlwaysRunAfter3 { private static boolean m_success = false; @BeforeMethod public void setUpShouldFail() { throw new RuntimeException("Failing in setUp"); } @AfterMethod(alwaysRun = true) public void afterMethodShouldBeCalled() { m_success = true; } @Test public void dummy() {} public static boolean success() { return m_success; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/alwaysrun/AlwaysRunBefore1.java000066400000000000000000000026441475274123300310100ustar00rootroot00000000000000package test.alwaysrun; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** Tests alwaysRun on a before Configuration method. Invoke this test by running group "A" */ public class AlwaysRunBefore1 { private static boolean m_beforeSuiteSuccess = false; private static boolean m_beforeTestSuccess = false; private static boolean m_beforeTestClassSuccess = false; private static boolean m_beforeTestMethodSuccess = false; @BeforeSuite(alwaysRun = true) public void initSuite() { m_beforeSuiteSuccess = true; } @BeforeTest(alwaysRun = true) public void initTest() { m_beforeTestSuccess = true; } @BeforeClass(alwaysRun = true) public void initTestClass() { m_beforeTestClassSuccess = true; } @BeforeMethod(alwaysRun = true) public void initTestMethod() { m_beforeTestMethodSuccess = true; } @Test(groups = "A") public void foo() { Assert.assertTrue(m_beforeSuiteSuccess); Assert.assertTrue(m_beforeTestSuccess); Assert.assertTrue(m_beforeTestClassSuccess); Assert.assertTrue(m_beforeTestMethodSuccess); } public static boolean success() { return m_beforeSuiteSuccess && m_beforeTestSuccess && m_beforeTestClassSuccess && m_beforeTestMethodSuccess; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/alwaysrun/AlwaysRunTest.java000066400000000000000000000036361475274123300304460ustar00rootroot00000000000000package test.alwaysrun; import static org.testng.Assert.assertTrue; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; import testhelper.OutputDirectoryPatch; public class AlwaysRunTest extends SimpleBaseTest { @Test public void withAlwaysRunAfter() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = create(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(new Class[] {AlwaysRunAfter1.class}); testng.addListener(tla); testng.run(); assertTrue(AlwaysRunAfter1.success(), "afterTestMethod should have run"); } @Test public void withAlwaysRunAfterMethod() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = create(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(new Class[] {AlwaysRunAfter3.class}); testng.addListener(tla); testng.run(); assertTrue(AlwaysRunAfter3.success(), "afterMethod should have run"); } @Test public void withoutAlwaysRunAfter() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = create(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(new Class[] {AlwaysRunAfter2.class}); testng.addListener(tla); testng.run(); assertTrue(AlwaysRunAfter2.success(), "afterTestMethod should not have run"); } @Test public void withoutAlwaysRunBefore() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = create(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(new Class[] {AlwaysRunBefore1.class}); testng.setGroups("A"); testng.addListener(tla); testng.run(); assertTrue(AlwaysRunBefore1.success(), "before alwaysRun methods should have been run"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/000077500000000000000000000000001475274123300274165ustar00rootroot00000000000000AnnotationTransformerClassInvocationSampleTest.java000066400000000000000000000003231475274123300415570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import org.testng.annotations.Test; @Test(invocationCount = 3) public class AnnotationTransformerClassInvocationSampleTest { public void f1() {} public void f2() {} } AnnotationTransformerClassSampleTest.java000066400000000000000000000007411475274123300375310ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * This test will fail unless a time out transformer is applied to it. * * @author cbeust */ @Test(timeOut = 1000) @Listeners(MySuiteListener.class) public class AnnotationTransformerClassSampleTest { public void one() { try { Thread.sleep(2000); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } } AnnotationTransformerDataProviderSampleTest.java000066400000000000000000000006651475274123300410550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class AnnotationTransformerDataProviderSampleTest { @DataProvider public Object[][] dp() { return new Integer[][] { new Integer[] {42}, }; } @Test(dataProvider = "dataProvider") public void f(Integer n) { Assert.assertEquals(n, Integer.valueOf(42)); } } AnnotationTransformerFactorySampleTest.java000066400000000000000000000006321475274123300400720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; public class AnnotationTransformerFactorySampleTest { @DataProvider public Object[][] dataProvider() { return new Integer[][] { new Integer[] {42}, }; } @Factory(dataProvider = "dp") public Object[] init(int n) { return new Object[] {new SimpleTest(n)}; } } AnnotationTransformerInTestngXml.java000066400000000000000000000010701475274123300366720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; import org.testng.annotations.Test; public class AnnotationTransformerInTestngXml implements IAnnotationTransformer { @Test(enabled = false) public void shouldRunAfterTransformation() {} @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.setEnabled(true); } } AnnotationTransformerInvocationCountTest.java000066400000000000000000000016041475274123300404430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; import org.testng.annotations.Test; public class AnnotationTransformerInvocationCountTest { public static class InvocationCountTransformer implements IAnnotationTransformer { private final int invocationCount; public InvocationCountTransformer(int invocationCount) { this.invocationCount = invocationCount; } @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { if ("concurrencyTest".equals(testMethod.getName())) { annotation.setInvocationCount(invocationCount); } } } @Test(invocationCount = 3) public void concurrencyTest() {} } AnnotationTransformerSampleTest.java000066400000000000000000000013601475274123300365410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import org.testng.Assert; import org.testng.annotations.Test; public class AnnotationTransformerSampleTest { private int m_two = 0; private int m_five = 0; private int m_three = 0; private int m_four = 0; @Test(invocationCount = 2) public void two() { m_two++; } @Test(invocationCount = 5) public void four() { m_four++; } @Test(invocationCount = 5) public void three() { m_three++; } @Test public void five() { m_five++; } @Test(dependsOnMethods = {"two", "three", "four", "five"}) public void verify() { Assert.assertEquals(m_two, 2); Assert.assertEquals(m_three, 3); Assert.assertEquals(m_four, 4); Assert.assertEquals(m_five, 5); } } AnnotationTransformerTest.java000066400000000000000000000262361475274123300354100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.assertj.core.api.iterable.Extractor; import org.testng.Assert; import org.testng.IAnnotationTransformer; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlPackage; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; import test.TestHelper; import test.annotationtransformer.issue1790.TestClassSample1; import test.annotationtransformer.issue1790.TestClassSample2; import test.annotationtransformer.issue1790.TransformerImpl; import test.annotationtransformer.issue2312.RetryListener; import test.annotationtransformer.issue2312.SampleTestClass; import test.annotationtransformer.issue2536.data.nested.ClassContainer; import test.annotationtransformer.issue2536.data.nested.ClassContainer.NonGroupClass3; import test.annotationtransformer.issue2536.listeners.ExternalGroupManager; public class AnnotationTransformerTest extends SimpleBaseTest { private static final Extractor NAME_EXTRACTOR = ITestResult::getName; /** * Make sure that without a transformer in place, a class-level annotation invocationCount is * correctly used. */ @Test public void verifyAnnotationWithoutTransformer() { TestNG tng = create(AnnotationTransformerSampleTest.class); tng.setPreserveOrder(true); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); assertThat(tla.getPassedTests()) .extracting(NAME_EXTRACTOR) .containsExactly( "five", "four", "four", "four", "four", "four", "three", "three", "three", "three", "three", "two", "two"); assertThat(tla.getFailedTests()).extracting(NAME_EXTRACTOR).containsExactly("verify"); } /** Test a transformer on a method-level @Test */ @Test public void verifyAnnotationTransformerMethod() { TestNG tng = create(AnnotationTransformerSampleTest.class); tng.setPreserveOrder(true); MyTransformer transformer = new MyTransformer(); tng.addListener(transformer); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); assertThat(transformer.getMethodNames()).contains("two", "three", "four", "five", "verify"); assertThat(tla.getPassedTests()) .extracting(NAME_EXTRACTOR) .containsExactly( "five", "five", "five", "five", "five", "four", "four", "four", "four", "three", "three", "three", "two", "two", "verify"); assertThat(tla.getFailedTests()).isEmpty(); } @Test public void verifyAnnotationTransformerHasOnlyOneNonNullArgument() { TestNG tng = create(AnnotationTransformerSampleTest.class); MyParamTransformer transformer = new MyParamTransformer(); tng.addListener(transformer); tng.run(); assertThat(transformer.isSuccess()).isTrue(); } @Test public void verifyMyParamTransformerOnlyOneNonNull() { assertThat(MyParamTransformer.onlyOneNonNull(null, null, null)).isFalse(); assertThat( MyParamTransformer.onlyOneNonNull( MyParamTransformer.class, MyParamTransformer.class.getConstructors()[0], null)) .isFalse(); assertThat(MyParamTransformer.onlyOneNonNull(MyParamTransformer.class, null, null)).isTrue(); } /** * Without an annotation transformer, we should have zero passed tests and one failed test called * "one". */ @Test public void verifyAnnotationTransformerClass2() { runTest(null, null, "one"); } /** * With an annotation transformer, we should have one passed test called "one" and zero failed * tests. */ @Test public void verifyAnnotationTransformerClass() { runTest(new MyTimeOutTransformer(), "one", null); } private void runTest(IAnnotationTransformer transformer, String passedName, String failedName) { MySuiteListener.triggered = false; MySuiteListener2.triggered = false; TestNG tng = new TestNG(); if (transformer != null) { tng.addListener(transformer); } tng.setTestClasses(new Class[] {AnnotationTransformerClassSampleTest.class}); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); List results = passedName != null ? tla.getPassedTests() : tla.getFailedTests(); String name = passedName != null ? passedName : failedName; Assert.assertEquals(results.size(), 1); Assert.assertEquals(name, results.get(0).getMethod().getMethodName()); Assert.assertTrue(MySuiteListener.triggered); Assert.assertFalse(MySuiteListener2.triggered); } @Test public void verifyListenerAnnotationTransformerClass() { MySuiteListener.triggered = false; MySuiteListener2.triggered = false; TestNG tng = new TestNG(); tng.addListener(new MyListenerTransformer()); tng.setTestClasses(new Class[] {AnnotationTransformerClassSampleTest.class}); tng.run(); Assert.assertFalse(MySuiteListener.triggered); Assert.assertTrue(MySuiteListener2.triggered); } @Test public void verifyConfigurationTransformer() { TestNG tng = new TestNG(); tng.addListener(new ConfigurationTransformer()); tng.setTestClasses(new Class[] {ConfigurationSampleTest.class}); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(ConfigurationSampleTest.getBefore(), "correct"); } @Test public void verifyDataProviderTransformer() { TestNG tng = create(); tng.addListener(new DataProviderTransformer()); tng.setTestClasses(new Class[] {AnnotationTransformerDataProviderSampleTest.class}); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } public static class CustomizedTestListenerAdaptor extends TestListenerAdapter {} @Test(description = "GITHUB-2138") public void verifyAnnotationTransformerInvocationForAllApplicableEvents() { TestNG tng = create(); FactoryTransformer transformer = new FactoryTransformer(); tng.addListener(transformer); tng.setTestClasses(new Class[] {AnnotationTransformerFactorySampleTest.class}); CustomizedTestListenerAdaptor tla = new CustomizedTestListenerAdaptor(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); String[] expectedLogs = new String[] { "transform_data_provider", "transform_factory", "transform_test", "transform_config", "transform_listener" }; assertThat(transformer.getLogs()).containsExactly(expectedLogs); } @Test(description = "Test for issue #605") public void verifyInvocationCountTransformer() { TestNG tng = create(); tng.setTestClasses(new Class[] {AnnotationTransformerInvocationCountTest.class}); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 3); tng = create(); tng.addListener(new AnnotationTransformerInvocationCountTest.InvocationCountTransformer(5)); tng.setTestClasses(new Class[] {AnnotationTransformerInvocationCountTest.class}); tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 5); } @Test public void annotationTransformerInXmlShouldBeRun() throws Exception { String xml = TestHelper.SUITE_XML_HEADER + "" + " " + " " + " " + " " + " " + " " + " " + " " + ""; ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); Collection suites = new Parser(is).parse(); TestNG tng = create(); tng.setXmlSuites(Arrays.asList(suites.toArray(new XmlSuite[0]))); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } @Test(description = "GITHUB-1790") public void ensureAnnotationTransformerInvokedForClassLevelTestAnnotations() { TestNG testng = create(TestClassSample1.class, TestClassSample2.class); TransformerImpl transformer = new TransformerImpl(); testng.addListener(transformer); testng.run(); assertThat(transformer.getClasses()).hasSize(2); assertThat(transformer.getConstructors()).isEmpty(); assertThat(transformer.getMethods()).hasSize(2); } @Test(description = "GITHUB-2312") public void ensureAnnotationTransformerIsNotInvokedMultipleTimes() { XmlTest myTest = createXmlTest("sample_suite", "sample_test", SampleTestClass.class); myTest.getSuite().addListener(RetryListener.class.getName()); TestNG myTestNG = create(myTest.getSuite()); myTestNG.run(); int retried = RetryListener.getExecutionCount(); assertThat(retried).isEqualTo(1); } @Test(description = "GITHUB-2536", dataProvider = "getXmlPackages") public void testNestedTestClass_packageIncludesNormalTestClasses(List xmlPackages) { ExternalGroupManager groupManager = new ExternalGroupManager(); String group = "run-me-dynamically"; String container = ClassContainer.class.getName(); String inner = NonGroupClass3.class.getSimpleName(); groupManager.addGroupDefinition(container + "$" + inner, group); TestListenerAdapter tla = new TestListenerAdapter(); XmlSuite xmlSuite = createXmlSuite("2536_suite"); XmlTest myTest = createXmlTest(xmlSuite, "2536_test"); myTest.addIncludedGroup(group); TestNG testng = create(xmlSuite); testng.addListener(tla); testng.addListener(groupManager); myTest.setXmlPackages(xmlPackages); testng.run(); assertThat(tla.getFailedTests()).withFailMessage("We should have no failed tests").isEmpty(); assertThat(tla.getPassedTests()).withFailMessage("We should have 2 passed tests").hasSize(2); long count = tla.getPassedTests().stream() .filter(m -> m.getInstance().getClass().equals(NonGroupClass3.class)) .count(); assertThat(count) .withFailMessage("We should have tests that only belong to " + NonGroupClass3.class) .isEqualTo(2); } @DataProvider public Object[][] getXmlPackages() { return new Object[][] { {Collections.singletonList(new XmlPackage("test.annotationtransformer.issue2536.data.*"))}, { Arrays.asList( new XmlPackage("test.annotationtransformer.issue2536.data.normal"), new XmlPackage("test.annotationtransformer.issue2536.data.nested")) } }; } } ConfigurationSampleTest.java000066400000000000000000000013101475274123300350060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ConfigurationSampleTest { private static String m_before = "uninitialized"; @BeforeClass public void beforeClass() { m_before = "correct"; } @BeforeMethod(enabled = false) public void testingEnabledOnConfiguration() { m_before = "this method is not enabled, we should not be here"; } // will be disabled by the configuration transformer @BeforeMethod public void beforeMethod() { m_before = "incorrect"; } @Test public void f() {} public static String getBefore() { return m_before; } } ConfigurationTransformer.java000066400000000000000000000020121475274123300352270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.ITestAnnotation; public class ConfigurationTransformer implements IAnnotationTransformer { @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} @Override public void transform( IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { if (annotation.getBeforeTestMethod()) { annotation.setEnabled(false); } } @Override public void transform(IDataProviderAnnotation annotation, Method testMethod) {} @Override public void transform(IFactoryAnnotation annotation, Method testMethod) {} } DataProviderTransformer.java000066400000000000000000000017331475274123300350150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.ITestAnnotation; public class DataProviderTransformer implements IAnnotationTransformer { @Override public void transform( IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} @Override public void transform(IDataProviderAnnotation annotation, Method testMethod) { annotation.setName("dataProvider"); } @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} @Override public void transform(IFactoryAnnotation annotation, Method testMethod) {} } FactoryTransformer.java000066400000000000000000000027051475274123300340400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Set; import org.testng.IAnnotationTransformer; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.IListenersAnnotation; import org.testng.annotations.ITestAnnotation; import org.testng.collections.Sets; public class FactoryTransformer implements IAnnotationTransformer { private final Set logs = Sets.newLinkedHashSet(); public Set getLogs() { return logs; } @Override public void transform( IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { logs.add("transform_config"); } @Override public void transform(IDataProviderAnnotation annotation, Method testMethod) { logs.add("transform_data_provider"); } @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { logs.add("transform_test"); } @Override public void transform(IFactoryAnnotation annotation, Method testMethod) { annotation.setDataProvider("dataProvider"); logs.add("transform_factory"); } @Override public void transform(IListenersAnnotation annotation, Class testClass) { logs.add("transform_listener"); } } MyListenerTransformer.java000066400000000000000000000021661475274123300345250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.IListenersAnnotation; import org.testng.annotations.ITestAnnotation; public class MyListenerTransformer implements IAnnotationTransformer { @Override public void transform(IListenersAnnotation annotation, Class testClass) { annotation.setValue(new Class[] {MySuiteListener2.class}); } @Override public void transform( IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} @Override public void transform(IDataProviderAnnotation annotation, Method method) {} @Override public void transform(IFactoryAnnotation annotation, Method method) {} @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} } MyParamTransformer.java000066400000000000000000000016771475274123300340060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class MyParamTransformer implements IAnnotationTransformer { private boolean success = true; @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { if (!onlyOneNonNull(testClass, testConstructor, testMethod)) { success = false; } } public static boolean onlyOneNonNull( Class testClass, Constructor testConstructor, Method testMethod) { return ((testClass != null && testConstructor == null && testMethod == null) || (testClass == null && testConstructor != null && testMethod == null) || (testClass == null && testConstructor == null && testMethod != null)); } public boolean isSuccess() { return success; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/MySuiteListener.java000066400000000000000000000005131475274123300333650ustar00rootroot00000000000000package test.annotationtransformer; import org.testng.ISuite; import org.testng.ISuiteListener; public class MySuiteListener implements ISuiteListener { public static boolean triggered = false; @Override public void onStart(ISuite suite) { triggered = true; } @Override public void onFinish(ISuite suite) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/MySuiteListener2.java000066400000000000000000000005141475274123300334500ustar00rootroot00000000000000package test.annotationtransformer; import org.testng.ISuite; import org.testng.ISuiteListener; public class MySuiteListener2 implements ISuiteListener { public static boolean triggered = false; @Override public void onStart(ISuite suite) { triggered = true; } @Override public void onFinish(ISuite suite) {} } MyTimeOutTransformer.java000066400000000000000000000007131475274123300343220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformerpackage test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class MyTimeOutTransformer implements IAnnotationTransformer { @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.setTimeOut(5000); // 5 seconds } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/MyTransformer.java000066400000000000000000000020101475274123300330620ustar00rootroot00000000000000package test.annotationtransformer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class MyTransformer implements IAnnotationTransformer { private final List methodNames = new ArrayList<>(); @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.setTimeOut(10000); if (testMethod != null) { switch (testMethod.getName()) { case "three": annotation.setInvocationCount(3); break; case "four": annotation.setInvocationCount(4); break; case "five": annotation.setInvocationCount(5); break; default: break; } methodNames.add(testMethod.getName()); } } public List getMethodNames() { return methodNames; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/SimpleTest.java000066400000000000000000000007321475274123300323540ustar00rootroot00000000000000package test.annotationtransformer; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(TestListenerAdapter.class) public class SimpleTest { private int m_n; public SimpleTest(int n) { m_n = n; } @BeforeMethod public void beforeMethod() {} @Test public void run() { Assert.assertEquals(m_n, 42); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue1790/000077500000000000000000000000001475274123300310675ustar00rootroot00000000000000TestClassSample1.java000066400000000000000000000002361475274123300350040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue1790package test.annotationtransformer.issue1790; import org.testng.annotations.Test; @Test public class TestClassSample1 { @Test public void test11() {} } TestClassSample2.java000066400000000000000000000002361475274123300350050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue1790package test.annotationtransformer.issue1790; import org.testng.annotations.Test; @Test public class TestClassSample2 { @Test public void test21() {} } TransformerImpl.java000066400000000000000000000020111475274123300347710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue1790package test.annotationtransformer.issue1790; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Set; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; import org.testng.collections.Sets; public class TransformerImpl implements IAnnotationTransformer { private Set> classes = Sets.newHashSet(); private Set> constructors = Sets.newHashSet(); private Set methods = Sets.newHashSet(); @Override public void transform( ITestAnnotation iTestAnnotation, Class aClass, Constructor constructor, Method method) { if (aClass != null) { classes.add(aClass); } if (constructor != null) { constructors.add(constructor); } if (method != null) { methods.add(method); } } public Set> getClasses() { return classes; } public Set> getConstructors() { return constructors; } public Set getMethods() { return methods; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2312/000077500000000000000000000000001475274123300310565ustar00rootroot00000000000000RetryListener.java000066400000000000000000000010471475274123300344570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2312package test.annotationtransformer.issue2312; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class RetryListener implements IAnnotationTransformer { private static int executedNrOfTimes = 0; public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { executedNrOfTimes++; } public static int getExecutionCount() { return executedNrOfTimes; } } SampleTestClass.java000066400000000000000000000003301475274123300347050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2312package test.annotationtransformer.issue2312; import org.testng.Assert; import org.testng.annotations.Test; public class SampleTestClass { @Test public void testMethod() { Assert.assertEquals(1, 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/000077500000000000000000000000001475274123300310665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/data/000077500000000000000000000000001475274123300317775ustar00rootroot00000000000000nested/000077500000000000000000000000001475274123300332025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/dataClassContainer.java000066400000000000000000000003451475274123300367570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/data/nestedpackage test.annotationtransformer.issue2536.data.nested; import org.testng.annotations.Test; public class ClassContainer { @Test public class NonGroupClass3 { public void step1() {} public void step2() {} } } normal/000077500000000000000000000000001475274123300332105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/dataNonGroupClass1.java000066400000000000000000000003041475274123300366660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/data/normalpackage test.annotationtransformer.issue2536.data.normal; import org.testng.annotations.Test; public class NonGroupClass1 { @Test public void step1() {} @Test public void step2() {} } NonGroupClass2.java000066400000000000000000000002721475274123300366730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/data/normalpackage test.annotationtransformer.issue2536.data.normal; import org.testng.annotations.Test; @Test public class NonGroupClass2 { public void step1() {} public void step2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/listeners/000077500000000000000000000000001475274123300330765ustar00rootroot00000000000000ExternalGroupManager.java000066400000000000000000000033001475274123300377500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/annotationtransformer/issue2536/listenerspackage test.annotationtransformer.issue2536.listeners; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class ExternalGroupManager implements IAnnotationTransformer { private final Map> groupDefinitions = new HashMap<>(); public Map> getGroupDefinitions() { return groupDefinitions; } @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { String fullName = null; if (testMethod != null) { fullName = testMethod.getDeclaringClass().getTypeName() + "." + testMethod.getName(); } else if (testClass != null) { fullName = testClass.getTypeName(); } if (fullName != null) { if (groupDefinitions.containsKey(fullName)) { Set data = new HashSet<>(groupDefinitions.get(fullName)); data.addAll(Arrays.asList(annotation.getGroups())); String[] fullGroup = data.toArray(new String[0]); annotation.setGroups(fullGroup); } else { Set data = new HashSet<>(Arrays.asList(annotation.getGroups())); data.add("egm-notselected"); String[] fullGroup = data.toArray(new String[0]); annotation.setGroups(fullGroup); } } } public void addGroupDefinition(String in_methodFullName, String in_groupName) { getGroupDefinitions() .computeIfAbsent(in_methodFullName, k -> new HashSet<>()) .add(in_groupName); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ant/000077500000000000000000000000001475274123300235435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ant/AntSystemPropertySet.java000066400000000000000000000016761475274123300305700ustar00rootroot00000000000000package test.ant; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import org.testng.annotations.Test; /** * Test whether nested propertysets are passed passed from the ant task. Executed by the * "run:antprop" target in test/build.xml. * * @author Todd Wells */ public class AntSystemPropertySet { @Test public void outputTestProperties() { assertNotNull(System.getProperty("syspropset1"), "syspropset1 not found"); assertEquals(System.getProperty("syspropset1"), "value 1", "Wrong value for syspropset1"); assertNotNull(System.getProperty("syspropset2"), "syspropset2 not found"); assertEquals(System.getProperty("syspropset2"), "value 2", "Wrong value for syspropset2"); assertNotNull(System.getProperty("sysprop1"), "sysprop1 not found"); assertEquals(System.getProperty("sysprop1"), "value 3", "Wrong value for sysprop1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ant/DontOverrideSuiteNameTest.java000066400000000000000000000003301475274123300314610ustar00rootroot00000000000000package test.ant; import org.testng.annotations.Test; @Test public class DontOverrideSuiteNameTest { private boolean m_run = false; @Test(groups = {"nopackage"}) public void test() { m_run = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ant/MultipleThreadTest.java000066400000000000000000000047601475274123300302000ustar00rootroot00000000000000package test.ant; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests that more than one thread is used for running tests * * @author micheb10 2 Oct 2006 */ public class MultipleThreadTest { public static Set _threads; @BeforeClass public void prepareHashSet() { _threads = Collections.synchronizedSet(new HashSet<>()); } @Test public void recordThread00() { _threads.add(Thread.currentThread()); } @Test public void recordThread01() { _threads.add(Thread.currentThread()); } @Test public void recordThread02() { _threads.add(Thread.currentThread()); } @Test public void recordThread03() { _threads.add(Thread.currentThread()); } @Test public void recordThread04() { _threads.add(Thread.currentThread()); } @Test public void recordThread05() { _threads.add(Thread.currentThread()); } @Test public void recordThread06() { _threads.add(Thread.currentThread()); } @Test public void recordThread07() { _threads.add(Thread.currentThread()); } @Test public void recordThread08() { _threads.add(Thread.currentThread()); } @Test public void recordThread09() { _threads.add(Thread.currentThread()); } @Test public void recordThread10() { _threads.add(Thread.currentThread()); } @Test public void recordThread11() { _threads.add(Thread.currentThread()); } @Test public void recordThread12() { _threads.add(Thread.currentThread()); } @Test public void recordThread13() { _threads.add(Thread.currentThread()); } @Test public void recordThread14() { _threads.add(Thread.currentThread()); } @Test public void recordThread15() { _threads.add(Thread.currentThread()); } @Test public void recordThread16() { _threads.add(Thread.currentThread()); } @Test public void recordThread17() { _threads.add(Thread.currentThread()); } @Test public void recordThread18() { _threads.add(Thread.currentThread()); } @Test public void recordThread19() { _threads.add(Thread.currentThread()); } @AfterClass public void confirmMultipleThreads() { Assert.assertTrue( _threads.size() > 1, "More than one thread should have been used for running the tests - " + _threads.size() + " was used"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ant/NoPackageTest.java000066400000000000000000000006041475274123300270760ustar00rootroot00000000000000package test.ant; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** @author Filippo Diotalevi */ public class NoPackageTest { private boolean m_run = false; @Test(groups = {"nopackage"}) public void test() { m_run = true; } @AfterMethod(groups = {"nopackage"}) public void after() { assert m_run : "test method was not run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ant/TestCommandLineArgs.java000066400000000000000000000015741475274123300302600ustar00rootroot00000000000000package test.ant; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import org.testng.annotations.Test; public class TestCommandLineArgs { @Test public void testUnixPathResolution() { String path = "/wee/wom/flibble.txt"; String[] segments = path.split("[/\\\\]", -1); assertEquals(4, segments.length); assertEquals("wee", segments[1]); } @Test public void testDOSPathResolution() { String path = "c:\\\\com\\pants\\wibble.txt"; String[] segments = path.split("[/\\\\]", -1); assertEquals(5, segments.length); assertEquals("com", segments[2]); // because c: is actually \\ which will be split twice } @Test public void testPathResolution() { File file = new File("../CHANGES.txt"); assert file.exists(); String path = file.getAbsolutePath(); assert path.split("[/\\\\]", -1).length > 1; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/000077500000000000000000000000001475274123300251475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/AttributeTest.java000066400000000000000000000016541475274123300306230ustar00rootroot00000000000000package test.attributes; import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class AttributeTest { @BeforeClass public void bc(ITestContext ctx) { ctx.setAttribute("test", "1"); } @Test public void f1(ITestContext ctx) { Set names = ctx.getAttributeNames(); assertThat(names).hasSize(1); assertThat(names).contains("test"); assertThat(ctx.getAttribute("test")).isEqualTo("1"); Object v = ctx.removeAttribute("test"); assertThat(v).isNotNull(); ctx.setAttribute("test2", "2"); } @Test(dependsOnMethods = "f1") public void f2(ITestContext ctx) { Set names = ctx.getAttributeNames(); assertThat(names).hasSize(1); assertThat(names).contains("test2"); assertThat(ctx.getAttribute("test2")).isEqualTo("2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/issue2346/000077500000000000000000000000001475274123300266165ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/issue2346/BaseTest.java000066400000000000000000000013051475274123300311720ustar00rootroot00000000000000package test.attributes.issue2346; import java.util.UUID; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; @Listeners(LocalTestListener.class) public class BaseTest { @BeforeMethod(alwaysRun = true) public void setUp(ITestResult result) { String session = UUID.randomUUID().toString(); result.setAttribute("session", session); } @AfterMethod(alwaysRun = true) public void tearDown(ITestResult iTestResult) { String key = "tearDown_" + iTestResult.getMethod().getQualifiedName(); LocalTestListener.data.putIfAbsent(key, iTestResult.getAttributeNames().isEmpty()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/issue2346/IssueTest.java000066400000000000000000000013341475274123300314120ustar00rootroot00000000000000package test.attributes.issue2346; import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void ensureAttributesAreIntactForSkippedMethods() { TestNG tng = createTests("sample_test", SingleTest.class); String cls = SingleTest.class.getCanonicalName() + ".test"; tng.run(); Map actual = LocalTestListener.data; assertThat(actual.get("onTestSkipped_" + cls)).isEqualTo(false); assertThat(actual.get("onTestStart_" + cls)).isEqualTo(false); assertThat(actual.get("tearDown_" + cls)).isEqualTo(false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/issue2346/LocalTestListener.java000066400000000000000000000021221475274123300330560ustar00rootroot00000000000000package test.attributes.issue2346; import java.util.HashMap; import java.util.Map; import org.testng.ITestListener; import org.testng.ITestResult; public class LocalTestListener implements ITestListener { public static Map data = new HashMap<>(); public void onTestStart(ITestResult iTestResult) { String key = "onTestStart_" + iTestResult.getMethod().getQualifiedName(); data.putIfAbsent(key, iTestResult.getAttributeNames().isEmpty()); } public void onTestSuccess(ITestResult iTestResult) { String key = "onTestSuccess_" + iTestResult.getMethod().getQualifiedName(); data.putIfAbsent(key, iTestResult.getAttributeNames().isEmpty()); } public void onTestFailure(ITestResult iTestResult) { String key = "onTestFailure_" + iTestResult.getMethod().getQualifiedName(); data.putIfAbsent(key, iTestResult.getAttributeNames().isEmpty()); } public void onTestSkipped(ITestResult iTestResult) { String key = "onTestSkipped_" + iTestResult.getMethod().getQualifiedName(); data.putIfAbsent(key, iTestResult.getAttributeNames().isEmpty()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/attributes/issue2346/SingleTest.java000066400000000000000000000004421475274123300315420ustar00rootroot00000000000000package test.attributes.issue2346; import static org.testng.Assert.fail; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SingleTest extends BaseTest { @BeforeMethod public void start() { fail(); } @Test public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/000077500000000000000000000000001475274123300254635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/BeforeGroupsTest.java000066400000000000000000000126241475274123300315750ustar00rootroot00000000000000package test.beforegroups; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.internal.ClassHelper; import org.testng.internal.PackageUtils; import org.testng.xml.XmlClass; import org.testng.xml.XmlGroups; import org.testng.xml.XmlRun; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.beforegroups.issue118.TestclassSample; import test.beforegroups.issue1694.BaseClassWithBeforeGroups; import test.beforegroups.issue2229.AnotherTestClassSample; import test.beforegroups.issue2229.TestClassSample; import test.beforegroups.issue346.SampleTestClass; public class BeforeGroupsTest extends SimpleBaseTest { @Test public void testInSequentialMode() throws IOException { runTest(XmlSuite.ParallelMode.NONE); } @Test public void testParallelMode() throws IOException { runTest(XmlSuite.ParallelMode.CLASSES); } @Test(description = "GITHUB-118") public void ensureInheritedAttributeWorksForBeforeGroups() { XmlSuite xmlSuite = createXmlSuite("suite", "test", TestclassSample.class); xmlSuite.addIncludedGroup("group1"); TestNG testng = create(xmlSuite); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); assertThat(listener.getFailedTests()).isEmpty(); } @Test(description = "GITHUB-346") public void ensureBeforeGroupsAreInvokedWhenCoupledWithAfterGroups() { String TEST_1 = "A"; String TEST_2 = "B"; XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("346_suite"); createXmlTest(xmlSuite, TEST_1, "A"); createXmlTest(xmlSuite, TEST_2, "B"); TestNG testng = new TestNG(); testng.setXmlSuites(Collections.singletonList(xmlSuite)); testng.run(); Map> expected = new HashMap<>(); expected.put(TEST_1, Collections.singletonList("beforeGroups:" + TEST_1 + TEST_1)); expected.put(TEST_2, Collections.singletonList("afterGroups:" + TEST_2 + TEST_2)); assertThat(SampleTestClass.logs).isEqualTo(expected); } @Test(description = "GITHUB-2229") public void ensureBeforeGroupsAreInvokedByDefaultEvenWithoutGrouping() { TestNG testng = create(TestClassSample.class, AnotherTestClassSample.class); testng.run(); assertThat(testng.getStatus()).isEqualTo(0); List expectedLogs = Arrays.asList( "TestA", "TestB", "TestC", "beforeGroupA", "testGroupA1", "testGroupA2", "testGroupA3", "afterGroupA", "beforeGroupB", "testGroupB", "afterGroupB"); assertThat(TestClassSample.logs).containsExactlyElementsOf(expectedLogs); expectedLogs = Arrays.asList( "beforeGroups1", "test1_testGroup1", "beforeGroups2", "test2_testGroup2", "test3_testGroup1", "afterGroups1", "test4_testGroup2", "afterGroups2"); assertThat(AnotherTestClassSample.logs).containsExactlyElementsOf(expectedLogs); } private static void createXmlTest(XmlSuite xmlSuite, String name, String group) { XmlTest xmlTest = new XmlTest(xmlSuite); xmlTest.setName(name); xmlTest.setClasses(Collections.singletonList(new XmlClass(SampleTestClass.class))); xmlTest.setGroups(groups(group)); } private static XmlGroups groups(String group) { XmlGroups xmlGroups = new XmlGroups(); XmlRun xmlRun = new XmlRun(); xmlRun.onInclude(group); xmlGroups.setRun(xmlRun); return xmlGroups; } private static void runTest(XmlSuite.ParallelMode mode) throws IOException { XmlSuite suite = createXmlSuite("sample_suite"); String pkg = BaseClassWithBeforeGroups.class.getPackage().getName(); Class[] classes = findClassesInPackage(pkg); XmlTest xmlTest = createXmlTestWithPackages(suite, "sample_test", classes); xmlTest.addIncludedGroup("regression"); xmlTest.setParallel(mode); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); List beforeGroups = Lists.newArrayList(); List afterGroups = Lists.newArrayList(); for (String name : listener.getInvokedMethodNames()) { if (name.equalsIgnoreCase(BaseClassWithBeforeGroups.BEFORE_GROUPS)) { beforeGroups.add(name); } if (name.equalsIgnoreCase(BaseClassWithBeforeGroups.AFTER_GROUPS)) { afterGroups.add(name); } } assertThat(beforeGroups).containsOnly(BaseClassWithBeforeGroups.BEFORE_GROUPS); assertThat(afterGroups).containsOnly(BaseClassWithBeforeGroups.AFTER_GROUPS); } private static Class[] findClassesInPackage(String packageName) throws IOException { String[] classes = PackageUtils.findClassesInPackage(packageName, new ArrayList<>(), new ArrayList<>()); List> loadedClasses = new ArrayList<>(); for (String clazz : classes) { loadedClasses.add(ClassHelper.forName(clazz)); } return loadedClasses.toArray(new Class[0]); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue118/000077500000000000000000000000001475274123300270455ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue118/TestclassSample.java000066400000000000000000000007161475274123300330230ustar00rootroot00000000000000package test.beforegroups.issue118; import org.testng.Assert; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @Test(groups = "group1") public class TestclassSample { private Object testObject; @BeforeGroups(inheritGroups = true) public void setUpGroup() { testObject = new Object(); } public void test1() { Assert.assertNotNull(testObject, "@BeforeGroups not invoked if nothing explicitly specified"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/000077500000000000000000000000001475274123300271375ustar00rootroot00000000000000BaseClassWithBeforeGroups.java000066400000000000000000000006551475274123300347500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694package test.beforegroups.issue1694; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; public class BaseClassWithBeforeGroups { public static final String BEFORE_GROUPS = "beforeGroups"; public static final String AFTER_GROUPS = "afterGroups"; @BeforeGroups(value = "regression") public void beforeGroups() {} @AfterGroups(value = "regression") public void afterGroups() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/ChildClassA.java000066400000000000000000000003101475274123300321060ustar00rootroot00000000000000package test.beforegroups.issue1694; import org.testng.annotations.Test; public class ChildClassA extends BaseClassWithBeforeGroups { @Test(groups = "regression") public void testMethodA() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/ChildClassB.java000066400000000000000000000003101475274123300321070ustar00rootroot00000000000000package test.beforegroups.issue1694; import org.testng.annotations.Test; public class ChildClassB extends BaseClassWithBeforeGroups { @Test(groups = "regression") public void testMethodB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/ChildClassC.java000066400000000000000000000003101475274123300321100ustar00rootroot00000000000000package test.beforegroups.issue1694; import org.testng.annotations.Test; public class ChildClassC extends BaseClassWithBeforeGroups { @Test(groups = "regression") public void testMethodC() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/ChildClassD.java000066400000000000000000000003101475274123300321110ustar00rootroot00000000000000package test.beforegroups.issue1694; import org.testng.annotations.Test; public class ChildClassD extends BaseClassWithBeforeGroups { @Test(groups = "regression") public void testMethodD() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/ChildClassE.java000066400000000000000000000003101475274123300321120ustar00rootroot00000000000000package test.beforegroups.issue1694; import org.testng.annotations.Test; public class ChildClassE extends BaseClassWithBeforeGroups { @Test(groups = "regression") public void testMethodE() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue1694/ChildClassF.java000066400000000000000000000003101475274123300321130ustar00rootroot00000000000000package test.beforegroups.issue1694; import org.testng.annotations.Test; public class ChildClassF extends BaseClassWithBeforeGroups { @Test(groups = "regression") public void testMethodF() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue2229/000077500000000000000000000000001475274123300271325ustar00rootroot00000000000000AnotherTestClassSample.java000066400000000000000000000021231475274123300343040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue2229package test.beforegroups.issue2229; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class AnotherTestClassSample { public static List logs = new ArrayList<>(); @BeforeGroups(groups = "testGroup1") public void beforeGroups1() { logs.add("beforeGroups1"); } @BeforeGroups(groups = "testGroup2") public void beforeGroups2() { logs.add("beforeGroups2"); } @AfterGroups(groups = "testGroup1") public void afterGroups1() { logs.add("afterGroups1"); } @AfterGroups(groups = "testGroup2") public void afterGroups2() { logs.add("afterGroups2"); } @Test(groups = "testGroup1") public void test1() { logs.add("test1_testGroup1"); } @Test(groups = "testGroup2") public void test2() { logs.add("test2_testGroup2"); } @Test(groups = "testGroup1") public void test3() { logs.add("test3_testGroup1"); } @Test(groups = "testGroup2") public void test4() { logs.add("test4_testGroup2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue2229/TestClassSample.java000066400000000000000000000037551475274123300330560ustar00rootroot00000000000000package test.beforegroups.issue2229; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class TestClassSample { public static List logs = new ArrayList<>(); boolean valueA = false; boolean valueB = false; @BeforeGroups(groups = "groupA") public void beforeGroupA() { logs.add("beforeGroupA"); valueA = true; } @BeforeGroups(groups = "groupB") public void beforeGroupB() { valueB = true; logs.add("beforeGroupB"); } @BeforeGroups(groups = "groupC") public void beforeGroupC() { logs.add("beforeGroupC No Test exist, should not run."); } @Test public void testA() { logs.add("TestA"); } @Test public void testB() { logs.add("TestB"); } @Test public void testC() { logs.add("TestC"); } @Test(groups = "groupA") public void testGroupA1() { logs.add("testGroupA1"); assertTrue(valueA, "BeforeGroupA was not executed"); } @Test(groups = "groupA") public void testGroupA2() { logs.add("testGroupA2"); assertTrue(valueA, "BeforeGroupA was not executed"); } @Test(groups = "groupA") public void testGroupA3() { logs.add("testGroupA3"); assertTrue(valueA, "BeforeGroupA was not executed"); } @Test(groups = "groupB") public void testGroupB() { logs.add("testGroupB"); assertTrue(valueB, "BeforeGroupB was not executed"); } @AfterGroups(groups = "groupA") public void afterGroupA() { logs.add("afterGroupA"); valueA = false; } @AfterGroups(groups = "groupB") public void afterGroupB() { logs.add("afterGroupB"); valueB = false; } @AfterClass public void afterClass() { assertFalse(valueA, "AfterGroupsA was not executed"); assertFalse(valueB, "AfterGroupsB was not executed"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue346/000077500000000000000000000000001475274123300270505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/beforegroups/issue346/SampleTestClass.java000066400000000000000000000021001475274123300327530ustar00rootroot00000000000000package test.beforegroups.issue346; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class SampleTestClass { public static Map> logs = new HashMap<>(); @BeforeGroups(groups = "A") @AfterGroups(groups = "B") public void setEnvironment() { ITestResult itr = Reporter.getCurrentTestResult(); String type = itr.getMethod().isBeforeGroupsConfiguration() ? "beforeGroups" : "afterGroups"; String[] groups = itr.getTestContext().getIncludedGroups(); String testName = itr.getTestContext().getName(); List data = Arrays.stream(groups).map(g -> type + ":" + testName + g).collect(Collectors.toList()); logs.put(itr.getTestContext().getName(), data); } @Test(groups = "A") public void test1() {} @Test(groups = "B") public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug90/000077500000000000000000000000001475274123300237075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug90/Bug90Test.java000066400000000000000000000015621475274123300263040ustar00rootroot00000000000000package test.bug90; import java.util.Collections; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class Bug90Test extends SimpleBaseTest { @Test(description = "Fix for https://github.com/cbeust/testng/issues/90") public void afterClassShouldRun() { XmlSuite s = createXmlSuite("Bug90"); XmlTest t = createXmlTest(s, "Bug90 test", Sample.class.getName()); XmlClass c = t.getClasses().get(0); c.setIncludedMethods(Collections.singletonList(new XmlInclude("test1"))); TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(s)); Sample.m_afterClassWasRun = false; tng.run(); Assert.assertTrue(Sample.m_afterClassWasRun); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug90/Sample.java000066400000000000000000000004741475274123300260000ustar00rootroot00000000000000package test.bug90; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class Sample { static boolean m_afterClassWasRun = false; @Test public void test1() {} @Test public void test2() {} @AfterClass public void afterClass() { m_afterClassWasRun = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug92/000077500000000000000000000000001475274123300237115ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug92/Bug92Test.java000066400000000000000000000015641475274123300263120ustar00rootroot00000000000000package test.bug92; import java.util.Collections; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class Bug92Test extends SimpleBaseTest { @Test(description = "Fix for https://github.com/cbeust/testng/issues/92") public void BeforeTestShouldRunOnce() { XmlSuite s = createXmlSuite("Bug92"); XmlTest t = createXmlTest(s, "Bug92 test", TestAlpha.class.getName(), TestBravo.class.getName()); s.setTests(Collections.singletonList(t)); TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(s)); TestBase.beforeTestCount = 0; TestBase.beforeTestAlwaysCount = 0; tng.run(); Assert.assertEquals(TestBase.beforeTestCount, 1); Assert.assertEquals(TestBase.beforeTestAlwaysCount, 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug92/TestAlpha.java000066400000000000000000000002521475274123300264400ustar00rootroot00000000000000package test.bug92; import org.testng.annotations.Test; public class TestAlpha extends TestBase { @Test public void test1() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug92/TestBase.java000066400000000000000000000005411475274123300262660ustar00rootroot00000000000000package test.bug92; import org.testng.annotations.BeforeTest; public class TestBase { static int beforeTestCount = 0; static int beforeTestAlwaysCount = 0; @BeforeTest public void baseTestBeforeTest() { beforeTestCount++; } @BeforeTest(alwaysRun = true) public void baseTestBeforeTestAlways() { beforeTestAlwaysCount++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/bug92/TestBravo.java000066400000000000000000000002521475274123300264640ustar00rootroot00000000000000package test.bug92; import org.testng.annotations.Test; public class TestBravo extends TestBase { @Test public void test1() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/classgroup/000077500000000000000000000000001475274123300251435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/classgroup/First.java000066400000000000000000000005761475274123300271050ustar00rootroot00000000000000package test.classgroup; import org.testng.annotations.Test; @Test(groups = {"first"}) public class First { private static boolean m_first1 = false; private static boolean m_first2 = false; @Test public void first1() { m_first1 = true; } @Test public void first2() { m_first2 = true; } static boolean allRun() { return m_first1 && m_first2; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/classgroup/Second.java000066400000000000000000000003671475274123300272270ustar00rootroot00000000000000package test.classgroup; import org.testng.annotations.Test; @Test(dependsOnGroups = {"first"}) public class Second { @Test public void verify() { assert First.allRun() : "Methods for class First should have been invoked first."; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cli/000077500000000000000000000000001475274123300235305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cli/github1517/000077500000000000000000000000001475274123300253305ustar00rootroot00000000000000ExitCodeListenerBehaviorTest.java000066400000000000000000000013201475274123300336420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cli/github1517package test.cli.github1517; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ExitCodeListenerBehaviorTest extends SimpleBaseTest { @Test(dataProvider = "getData") public void testMethod(Class clazz, int expectedStatus) { TestNG testNG = create(clazz); testNG.run(); Assert.assertEquals(testNG.getStatus(), expectedStatus); } @DataProvider public Object[][] getData() { return new Object[][] { {TestClassWithConfigFailureSample.class, 3}, {TestClassWithConfigSkipSample.class, 2}, {TestClassWithConfigSkipAndFailureSample.class, 3} }; } } TestClassWithConfigFailureSample.java000066400000000000000000000005701475274123300344570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cli/github1517package test.cli.github1517; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestClassWithConfigFailureSample { @BeforeClass public void beforeClass() { throw new RuntimeException("Simulating a configuration failure"); } @Test public void testMethod() { Assert.assertTrue(true); } } TestClassWithConfigSkipAndFailureSample.java000066400000000000000000000007771475274123300357420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cli/github1517package test.cli.github1517; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestClassWithConfigSkipAndFailureSample { @BeforeClass public void beforeClass() { throw new RuntimeException("Simulating a configuration failure"); } @BeforeMethod public void beforeMethod() { // Intentionally left empty } @Test public void testMethod() { Assert.assertTrue(true); } } TestClassWithConfigSkipSample.java000066400000000000000000000006201475274123300337720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cli/github1517package test.cli.github1517; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestClassWithConfigSkipSample { @BeforeClass public void beforeClass() { throw new SkipException("Simulating a configuration skip"); } @Test public void testMethod() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/000077500000000000000000000000001475274123300252475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/CommandLineOverridesXml.java000066400000000000000000000074411475274123300326520ustar00rootroot00000000000000package test.commandline; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.jarfileutils.JarCreator; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; import test.TestHelper; import test.commandline.issue341.LocalLogAggregator; import test.commandline.issue341.TestSampleA; import test.commandline.issue341.TestSampleB; public class CommandLineOverridesXml extends SimpleBaseTest { @Test(description = "Specifying -groups on the command line should override testng.xml") public void commandLineGroupsShouldOverrideXml() { runTest("go", null, Collections.singletonList("f2")); } @Test(description = "Specifying -excludegroups on the command line should override testng.xml") public void commandLineExcludedGroupsShouldOverrideXml() { runTest(null, "go", Collections.singletonList("f1")); } @Test public void shouldRunBothMethods() { runTest(null, null, Arrays.asList("f1", "f2")); } private void runTest(String group, String excludedGroups, List methods) { XmlSuite s = createXmlSuite(getClass().getName()); createXmlTest(s, "Test", OverrideSampleTest.class.getName()); TestNG tng = create(); if (group != null) tng.setGroups(group); if (excludedGroups != null) tng.setExcludedGroups(excludedGroups); tng.setXmlSuites(Collections.singletonList(s)); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); assertTestResultsEqual(tla.getPassedTests(), methods); } @Test public void ensureThatParallelismAndThreadCountAreRallied() { TestNG testng = create(); testng.setTestSuites(Collections.singletonList("src/test/resources/987.xml")); testng.setThreadCount(2); testng.setParallel(XmlSuite.ParallelMode.METHODS); testng.run(); assertThat(Issue987TestSample.maps).hasSize(2); assertThat(Issue987TestSample.maps.values()).contains("method2", "method1"); } @Test(description = "GITHUB-341") public void ensureParallelismIsHonoredWhenOnlyClassesSpecifiedInJar() throws IOException { Class[] classes = new Class[] {TestSampleA.class, TestSampleB.class}; File jarfile = JarCreator.generateJar(classes); String[] args = new String[] { "-parallel", "classes", "-testjar", jarfile.getAbsolutePath(), "-listener", LocalLogAggregator.class.getCanonicalName() }; TestNG.privateMain(args, null); Set logs = LocalLogAggregator.getLogs(); assertThat(logs).hasSize(2); } @Test(description = "GITHUB-1810") public void ensureNoNullPointerExceptionIsThrown() throws IOException { TestNG testng = TestNG.privateMain(new String[] {createTemporarySuiteAndGetItsPath()}, null); assertThat(testng.getStatus()).isEqualTo(8); } private static String createTemporarySuiteAndGetItsPath() throws IOException { Path file = Files.createTempFile("testng", ".xml"); org.testng.reporters.Files.writeFile( buildSuiteContentThatRefersToInvalidTestClass(), file.toFile()); return file.toFile().getAbsolutePath(); } private static String buildSuiteContentThatRefersToInvalidTestClass() { return TestHelper.SUITE_XML_HEADER + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/Issue987TestSample.java000066400000000000000000000006551475274123300314620ustar00rootroot00000000000000package test.commandline; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.testng.annotations.Test; public class Issue987TestSample { public static Map maps = new ConcurrentHashMap<>(); @Test public void method1() { maps.put(Thread.currentThread().getId(), "method1"); } @Test public void method2() { maps.put(Thread.currentThread().getId(), "method2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/OverrideSampleTest.java000066400000000000000000000002611475274123300316720ustar00rootroot00000000000000package test.commandline; import org.testng.annotations.Test; public class OverrideSampleTest { @Test public void f1() {} @Test(groups = "go") public void f2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/issue341/000077500000000000000000000000001475274123300266275ustar00rootroot00000000000000LocalLogAggregator.java000066400000000000000000000011671475274123300331170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/issue341package test.commandline.issue341; import java.util.Collections; import java.util.Set; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.collections.Maps; public class LocalLogAggregator implements IInvokedMethodListener { private static final Set logs = Collections.newSetFromMap(Maps.newConcurrentMap()); @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { logs.addAll(Reporter.getOutput(testResult)); } public static Set getLogs() { return logs; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/issue341/TestSampleA.java000066400000000000000000000003431475274123300316540ustar00rootroot00000000000000package test.commandline.issue341; import org.testng.Reporter; import org.testng.annotations.Test; public class TestSampleA { @Test public void a() { Reporter.log(Long.toString(Thread.currentThread().getId())); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/commandline/issue341/TestSampleB.java000066400000000000000000000003441475274123300316560ustar00rootroot00000000000000package test.commandline.issue341; import org.testng.Reporter; import org.testng.annotations.Test; public class TestSampleB { @Test public void aa() { Reporter.log(Long.toString(Thread.currentThread().getId())); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailure/000077500000000000000000000000001475274123300252565ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailure/ClassWithFailedBeforeSuite.java000066400000000000000000000003351475274123300332650ustar00rootroot00000000000000package test.conffailure; import org.testng.annotations.BeforeSuite; public class ClassWithFailedBeforeSuite { @BeforeSuite public void setUpShouldFail() { throw new RuntimeException("Failing in setUp"); } } ClassWithFailedBeforeSuiteVerification.java000066400000000000000000000011441475274123300355500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailurepackage test.conffailure; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class ClassWithFailedBeforeSuiteVerification { private static boolean m_success1 = true; private static boolean m_success2 = true; // Should not be run because beforeSuite failed on the other class @BeforeClass public void setUp() { m_success1 = false; } // Should not be run because beforeSuite failed on the other class @AfterClass public void tearDown() { m_success2 = false; } public static boolean success() { return m_success1 && m_success2; } } ClassWithFailedBeforeTestClass.java000066400000000000000000000005461475274123300340260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailurepackage test.conffailure; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ClassWithFailedBeforeTestClass { @BeforeClass public void setUpShouldFail() { throw new RuntimeException("Failing in setUp"); } // Adding this method or @Configuration will never be invoked @Test public void dummy() {} } ClassWithFailedBeforeTestClassVerification.java000066400000000000000000000014431475274123300363660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailurepackage test.conffailure; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ClassWithFailedBeforeTestClassVerification { private static boolean m_success1 = false; private static boolean m_success2 = false; // Should be run even though ClassWithFailedBeforeTestClass failed in its configuration @BeforeClass public void setUpShouldPass() { m_success1 = true; } // Should be run even though ClassWithFailedBeforeTestClass failed in its configuration @AfterClass public void tearDown() { m_success2 = true; } // Adding this method or @Configuration will never be invoked @Test public void dummy() {} public static boolean success() { return m_success1 && m_success2; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailure/ConfigurationFailure.java000066400000000000000000000033501475274123300322410ustar00rootroot00000000000000package test.conffailure; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertTrue; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; import test.conffailure.github990.AbstractBaseSample; import test.conffailure.github990.ChildClassSample; import testhelper.OutputDirectoryPatch; /** * Test various cases where the @Configuration methods fail * *

Created on Jul 20, 2005 * * @author cbeust */ public class ConfigurationFailure extends SimpleBaseTest { @Test public void beforeTestClassFails() { runTest(ClassWithFailedBeforeTestClass.class, ClassWithFailedBeforeTestClassVerification.class); assertTrue( ClassWithFailedBeforeTestClassVerification.success(), "Not all the @Configuration methods of Run2 were run"); } @Test public void beforeTestSuiteFails() { runTest(ClassWithFailedBeforeSuite.class, ClassWithFailedBeforeSuiteVerification.class); assertTrue( ClassWithFailedBeforeSuiteVerification.success(), "No @Configuration methods should have run"); } private static void runTest(Class... classes) { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = create(classes); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.addListener(tla); testng.run(); } @Test(description = "GITHUB-990") public void ensureConfigurationRunsFromBaseClass() { TestNG testng = create(ChildClassSample.class); testng.setConfigFailurePolicy(XmlSuite.FailurePolicy.CONTINUE); testng.run(); assertThat(AbstractBaseSample.messages).containsExactly("cleanup"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailure/github990/000077500000000000000000000000001475274123300270025ustar00rootroot00000000000000AbstractBaseSample.java000066400000000000000000000010441475274123300332650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailure/github990package test.conffailure.github990; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public abstract class AbstractBaseSample { public static List messages = new ArrayList<>(); @BeforeTest protected void setup() { throw new RuntimeException("Fail the test."); } @Test protected abstract void execute(); @AfterTest(alwaysRun = true) protected void cleanup() { messages.add("cleanup"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/conffailure/github990/ChildClassSample.java000066400000000000000000000002141475274123300330150ustar00rootroot00000000000000package test.conffailure.github990; public class ChildClassSample extends AbstractBaseSample { @Override protected void execute() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/000077500000000000000000000000001475274123300256305ustar00rootroot00000000000000AfterMethodWithGroupFiltersSampleTest.java000066400000000000000000000014171475274123300360250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; public class AfterMethodWithGroupFiltersSampleTest { static final String[] EXPECTED_INVOCATIONS = { "g1m1", "afterGroup1", "g1m2", "afterGroup1", "g2m1", "afterGroup2", "g2m2", "afterGroup2", "g2m3", "afterGroup2", }; @AfterMethod(onlyForGroups = {"group1"}) public void afterGroup1() {} @Test(groups = "group1") public void g1m1() {} @Test(groups = "group1") public void g1m2() {} @AfterMethod(onlyForGroups = {"group2"}) public void afterGroup2() {} @Test(groups = "group2") public void g2m1() {} @Test(groups = "group2") public void g2m2() {} @Test(groups = "group2") public void g2m3() {} } AfterMethodWithGroupFiltersTest.java000066400000000000000000000011151475274123300346560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import static org.assertj.core.api.Assertions.assertThat; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class AfterMethodWithGroupFiltersTest extends SimpleBaseTest { @Test public void beforeMethodWithBeforeGroupsShouldOnlyRunBeforeGroupMethods() { InvokedMethodNameListener nameListener = run(AfterMethodWithGroupFiltersSampleTest.class); assertThat(nameListener.getInvokedMethodNames()) .containsExactly(AfterMethodWithGroupFiltersSampleTest.EXPECTED_INVOCATIONS); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/Base.java000066400000000000000000000005531475274123300273500ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @Test(groups = {"base"}) public class Base { static int m_count; @BeforeTest public void init() { m_count = 0; } @BeforeGroups(groups = "foo") public void beforeGroups() { m_count++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/Base3.java000066400000000000000000000006741475274123300274370ustar00rootroot00000000000000package test.configuration; import org.testng.Assert; import org.testng.annotations.BeforeGroups; public class Base3 { private static boolean m_before = false; /** @return the m_before */ public static boolean getBefore() { return m_before; } @BeforeGroups("cg34-1") public void anotherBefore1() { Assert.assertFalse(m_before); Assert.assertFalse(ConfigurationGroups3SampleTest.getF1()); m_before = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BaseBeforeTestOrdering.java000066400000000000000000000002171475274123300330220ustar00rootroot00000000000000package test.configuration; public class BaseBeforeTestOrdering { public void log(String s) { BeforeTestOrderingTest.addTest(s); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BaseGroupsASampleTest.java000066400000000000000000000003161475274123300326500ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.Test; public class BaseGroupsASampleTest extends Base { @Test(groups = "foo") public void a() { // System.out.println( "a" ); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BaseGroupsBSampleTest.java000066400000000000000000000002431475274123300326500ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.Test; public class BaseGroupsBSampleTest extends Base { @Test(groups = "foo") public void b() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BaseGroupsTest.java000066400000000000000000000035131475274123300314070ustar00rootroot00000000000000package test.configuration; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.configuration.github1338.FirstGitHub1338Sample; import test.configuration.github1338.SecondGitHub1338Sample; import test.configuration.github1338.ThirdGitHub1338Sample; public class BaseGroupsTest extends SimpleBaseTest { @Test( description = "Verify that a base class with a BeforeGroups method only gets invoked once, " + "no matter how many subclasses it has") public void verifySingleInvocation() { TestNG tng = create(BaseGroupsASampleTest.class, BaseGroupsBSampleTest.class); tng.setGroups("foo"); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).containsOnlyOnce("beforeGroups"); } @Test(description = "https://github.com/cbeust/testng/issues/1338") public void verifyBeforeGroupUseAppropriateInstance() { XmlSuite suite = createXmlSuite("Suite"); XmlTest test = createXmlTest( suite, "Test", SecondGitHub1338Sample.class, FirstGitHub1338Sample.class, ThirdGitHub1338Sample.class); createXmlGroups(test, "group1"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).isEmpty(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeClassTest.java000066400000000000000000000035661475274123300315350ustar00rootroot00000000000000package test.configuration; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import test.SimpleBaseTest; import test.configuration.issue1035.InvocationTracker; import test.configuration.issue1035.MyFactory; public class BeforeClassTest extends SimpleBaseTest { @Test public void beforeClassMethodsShouldRunInParallel() { TestNG tng = create(BeforeClassThreadA.class, BeforeClassThreadB.class); tng.setParallel(XmlSuite.ParallelMode.METHODS); tng.run(); assertThat(Math.abs(BeforeClassThreadA.WHEN - BeforeClassThreadB.WHEN)).isLessThan(1000); } @Test public void afterClassShouldRunEvenWithDisabledMethods() { TestNG tng = create(ConfigurationDisabledSampleTest.class); assertThat(ConfigurationDisabledSampleTest.m_afterWasRun).isFalse(); tng.run(); assertThat(ConfigurationDisabledSampleTest.m_afterWasRun).isTrue(); } @Test(description = "GITHUB-1035") public void ensureBeforeClassGetsCalledConcurrentlyWhenWorkingWithFactories() { TestNG testng = create(MyFactory.class); testng.setParallel(ParallelMode.INSTANCES); testng.setGroupByInstances(true); testng.run(); List sorted = new ArrayList<>(MyFactory.TRACKER); assertThat(sorted).hasSize(5); long previousTimestamp = sorted.get(0).getTime(); long previousThreadId = sorted.get(0).getThreadId(); for (int i = 1; i < sorted.size(); i++) { InvocationTracker current = sorted.get(i); assertThat(current.getTime() - previousTimestamp).isLessThanOrEqualTo(100); previousTimestamp = current.getTime(); assertThat(current.getThreadId()).isNotEqualTo(previousThreadId); previousThreadId = current.getThreadId(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeClassThreadA.java000066400000000000000000000005511475274123300321150ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BeforeClassThreadA { public static long WHEN; @BeforeClass(alwaysRun = true) public void setup() throws InterruptedException { WHEN = System.currentTimeMillis(); Thread.sleep(2000); } @Test public void execute() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeClassThreadB.java000066400000000000000000000005511475274123300321160ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BeforeClassThreadB { public static long WHEN; @BeforeClass(alwaysRun = true) public void setup() throws InterruptedException { WHEN = System.currentTimeMillis(); Thread.sleep(2000); } @Test public void execute() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeMethodTest.java000066400000000000000000000013261475274123300317000ustar00rootroot00000000000000package test.configuration; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class BeforeMethodTest { private Method m_method; private ITestContext m_context; @BeforeMethod public void before(Method m, ITestContext ctx) { m_method = m; m_context = ctx; } @Test public void mainTest() { Assert.assertEquals(m_method.getName(), "mainTest"); ITestNGMethod[] methods = m_context.getAllTestMethods(); Assert.assertEquals(1, methods.length); Assert.assertEquals(methods[0].getConstructorOrMethod().getName(), "mainTest"); } } BeforeMethodWithGroupFiltersSampleTest.java000066400000000000000000000014321475274123300361630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class BeforeMethodWithGroupFiltersSampleTest { static final String[] EXPECTED_INVOCATIONS = { "beforeGroup1", "g1m1", "beforeGroup1", "g1m2", "beforeGroup2", "g2m1", "beforeGroup2", "g2m2", "beforeGroup2", "g2m3" }; @BeforeMethod(onlyForGroups = {"group1"}) public void beforeGroup1() {} @Test(groups = "group1") public void g1m1() {} @Test(groups = "group1") public void g1m2() {} @BeforeMethod(onlyForGroups = {"group2"}) public void beforeGroup2() {} @Test(groups = "group2") public void g2m1() {} @Test(groups = "group2") public void g2m2() {} @Test(groups = "group2") public void g2m3() {} } BeforeMethodWithGroupFiltersTest.java000066400000000000000000000011201475274123300350130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import static org.assertj.core.api.Assertions.assertThat; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class BeforeMethodWithGroupFiltersTest extends SimpleBaseTest { @Test public void beforeMethodWithBeforeGroupsShouldOnlyRunBeforeGroupMethods() { InvokedMethodNameListener nameListener = run(BeforeMethodWithGroupFiltersSampleTest.class); assertThat(nameListener.getInvokedMethodNames()) .containsExactly(BeforeMethodWithGroupFiltersSampleTest.EXPECTED_INVOCATIONS); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeTestOrdering1Test.java000066400000000000000000000005771475274123300331610ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class BeforeTestOrdering1Test extends BaseBeforeTestOrdering { @BeforeTest public void bt1() { log("bt1"); } @AfterTest public void at1() { log("at1"); } @Test public void f1() { log("f1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeTestOrdering2Test.java000066400000000000000000000005771475274123300331620ustar00rootroot00000000000000package test.configuration; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class BeforeTestOrdering2Test extends BaseBeforeTestOrdering { @BeforeTest public void bt2() { log("bt2"); } @AfterTest public void at2() { log("at2"); } @Test public void f2() { log("f2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/BeforeTestOrderingTest.java000066400000000000000000000027111475274123300330700ustar00rootroot00000000000000package test.configuration; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.Reporter; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.TestHelper; public class BeforeTestOrderingTest { private static final List m_testNames = new ArrayList<>(); @BeforeSuite public void init() { m_testNames.clear(); } static void addTest(String testName) { m_testNames.add(testName); } private static final List expected = Arrays.asList("bt1", "f1", "at1", "bt2", "f2", "at2"); @Test public void verifyBeforeTestOrdering() throws IOException { XmlSuite s = new XmlSuite(); Reporter.log("BEFORE"); XmlTest t1 = new XmlTest(s); XmlClass c1 = new XmlClass(BeforeTestOrdering1Test.class); t1.getXmlClasses().add(c1); XmlTest t2 = new XmlTest(s); XmlClass c2 = new XmlClass(BeforeTestOrdering2Test.class); t2.getXmlClasses().add(c2); TestNG tng = TestHelper.createTestNG(); TestListenerAdapter tl = new TestListenerAdapter(); tng.addListener(tl); tng.setXmlSuites(Collections.singletonList(s)); tng.run(); Assert.assertEquals(m_testNames, expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/ConfigurationBaseTest.java000066400000000000000000000016341475274123300327410ustar00rootroot00000000000000package test.configuration; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import test.SimpleBaseTest; public abstract class ConfigurationBaseTest extends SimpleBaseTest { protected void testConfiguration(Class... classes) { TestNG tng = create(classes); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals( tla.getConfigurationFailures().size(), 0, getFailedResultMessage(tla.getConfigurationFailures())); Assert.assertEquals( tla.getFailedTests().size(), 0, getFailedResultMessage(tla.getFailedTests())); Assert.assertEquals( tla.getSkippedTests().size(), 0, getFailedResultMessage(tla.getSkippedTests())); Assert.assertFalse(tla.getPassedTests().isEmpty(), "All tests should pass"); } } ConfigurationDisabledSampleTest.java000066400000000000000000000007601475274123300346600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ConfigurationDisabledSampleTest { public static boolean m_afterWasRun; @BeforeClass(alwaysRun = true) public void before() { m_afterWasRun = false; } @AfterClass(alwaysRun = true) public void after() { m_afterWasRun = true; } @Test public void f1() {} @Test(enabled = false) public void f2() {} } ConfigurationGroupBothSampleTest.java000066400000000000000000000017561475274123300350700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ConfigurationGroupBothSampleTest { static List m_list = Collections.synchronizedList(new ArrayList<>()); private static synchronized void addToList(Integer n) { m_list.add(n); } @BeforeGroups( groups = {"twice"}, value = {"twice"}) public void a() { addToList(1); } @Test( groups = {"twice"}, dataProvider = "MyData", invocationCount = 2, threadPoolSize = 2) public void b(int a, int b) { addToList(2); } @AfterGroups( groups = {"twice"}, value = {"twice"}) public void c() { addToList(3); } @DataProvider(name = "MyData") public Object[][] input() { return new Object[][] {{1, 1}, {2, 2}, {3, 3}}; } } ConfigurationGroupDataProviderSampleTest.java000066400000000000000000000014661475274123300365560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ConfigurationGroupDataProviderSampleTest { static List m_list = new ArrayList<>(); @BeforeGroups( groups = {"twice"}, value = {"twice"}) public void a() { m_list.add(1); } @Test( groups = {"twice"}, dataProvider = "MyData") public void b(int a, int b) { m_list.add(2); } @AfterGroups( groups = {"twice"}, value = {"twice"}) public void c() { m_list.add(3); } @DataProvider(name = "MyData") public Object[][] input() { return new Object[][] {{1, 1}, {2, 2}, {3, 3}}; } } ConfigurationGroupInvocationCountSampleTest.java000066400000000000000000000012051475274123300373030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class ConfigurationGroupInvocationCountSampleTest { static List m_list = new ArrayList<>(); @BeforeGroups( groups = {"twice"}, value = {"twice"}) public void a() { m_list.add(1); } @Test( groups = {"twice"}, invocationCount = 3) public void b() { m_list.add(2); } @AfterGroups( groups = {"twice"}, value = {"twice"}) public void c() { m_list.add(3); } } ConfigurationGroupIteratorDataProviderSampleTest.java000066400000000000000000000016521475274123300402650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ConfigurationGroupIteratorDataProviderSampleTest { static List m_list = new ArrayList<>(); @BeforeGroups( groups = {"twice"}, value = {"twice"}) public void a() { m_list.add(1); } @Test( groups = {"twice"}, dataProvider = "MyData") public void b(int a, int b) { m_list.add(2); } @AfterGroups( groups = {"twice"}, value = {"twice"}) public void c() { m_list.add(3); } @DataProvider(name = "MyData") public Iterator input() { return Arrays.asList(new Object[] {1, 1}, new Object[] {2, 2}, new Object[] {3, 3}).iterator(); } } ConfigurationGroups1SampleTest.java000066400000000000000000000016711475274123300345130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; /** * Simple beforeGroups test: 1 before method and 2 test method * * @author cbeust * @date Mar 3, 2006 */ public class ConfigurationGroups1SampleTest { private boolean m_before = false; private boolean m_f1 = false; @BeforeGroups("cg1-1") public void before1() { Assert.assertFalse(m_before); Assert.assertFalse(m_f1); m_before = true; } @Test(groups = "cg1-a") public void fa() {} @Test(groups = "cg1-1") public void f1() { Assert.assertTrue(m_before); m_f1 = true; } private List m_list = new ArrayList<>(); @Test(dependsOnGroups = {"cg1-a", "cg1-1"}) public void verify() { Assert.assertTrue(m_before); Assert.assertTrue(m_f1); } private void log(String s) { m_list.add(s); } } ConfigurationGroups2SampleTest.java000066400000000000000000000023541475274123300345130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; /** * beforeGroups test: make sure that the beforeGroups method is invoked only once even if two test * methods belong to the group * * @author cbeust */ public class ConfigurationGroups2SampleTest { private boolean m_before = false; private boolean m_f1 = false; private boolean m_g1 = false; @BeforeGroups("cg2-1") public void before1() { Assert.assertFalse(m_before); Assert.assertFalse(m_f1); Assert.assertFalse(m_g1); m_before = true; log("before1"); } @Test(groups = "cg2-a") public void fa() { log("fa"); } @Test(groups = "cg2-1") public void f1() { Assert.assertTrue(m_before); m_f1 = true; log("f1"); } @Test(groups = "cg2-1") public void g1() { Assert.assertTrue(m_before); m_g1 = true; log("g1"); } private List m_list = new ArrayList<>(); @Test(dependsOnGroups = {"cg2-a", "cg2-1"}) public void verify() { Assert.assertTrue(m_before); Assert.assertTrue(m_f1); Assert.assertTrue(m_g1); } private void log(String s) { m_list.add(s); } } ConfigurationGroups3SampleTest.java000066400000000000000000000023021475274123300345050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; /** * beforeGroups test: make sure that if before methods are scattered on more than one class, they * are still taken into account * * @author cbeust */ public class ConfigurationGroups3SampleTest extends Base3 { private boolean m_before = false; private static boolean m_f1 = false; @BeforeGroups("cg34-1") public void before1() { Assert.assertFalse(m_before); Assert.assertFalse(m_f1); m_before = true; log("before1"); } @Test(groups = "cg34-a") public void fa() { log("fa"); } @Test(groups = "cg34-1") public void f1() { Assert.assertTrue(m_before); Assert.assertTrue(Base3.getBefore()); m_f1 = true; log("f1"); } private List m_list = new ArrayList<>(); @Test(dependsOnGroups = {"cg34-a", "cg34-1"}) public void verify() { Assert.assertTrue(m_before); Assert.assertTrue(Base3.getBefore()); Assert.assertTrue(m_f1); } private void log(String s) { m_list.add(s); } public static boolean getF1() { return m_f1; } } ConfigurationGroups4SampleTest.java000066400000000000000000000014021475274123300345060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.Test; /** * Simple afterGroups test * * @author cbeust * @date Mar 7, 2006 */ public class ConfigurationGroups4SampleTest { private boolean m_after = false; private boolean m_run = false; @Test public void f() {} @Test(groups = "cg4-1") public void run() { Assert.assertFalse(m_after); m_run = true; } @AfterGroups("cg4-1") public void after1() { Assert.assertTrue(m_run); Assert.assertFalse(m_after); m_after = true; } @Test(dependsOnGroups = "cg4-1") public void verify() { Assert.assertTrue(m_run, "run() wasn't run"); Assert.assertTrue(m_after, "after1() wasn't run"); } } ConfigurationGroups5SampleTest.java000066400000000000000000000022611475274123300345130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.Test; /** * afterGroups test with more than one group * * @author cbeust */ public class ConfigurationGroups5SampleTest { private boolean m_after = false; private boolean m_run1 = false; private boolean m_run2 = false; private int m_afterCount = 0; @Test public void f() {} @Test(groups = "cg5-1") public void run1() { if (m_afterCount == 0) { Assert.assertFalse(m_after); } m_run1 = true; } @Test(groups = "cg5-2") public void run2() { if (m_afterCount == 0) { Assert.assertFalse(m_after); } m_run2 = true; } @AfterGroups({"cg5-1", "cg5-2"}) public void after() { m_afterCount++; Assert.assertTrue(m_run1 || m_run2); if (m_afterCount == 0) { Assert.assertFalse(m_after); } m_after = true; } @Test(dependsOnGroups = {"cg5-1", "cg5-2"}) public void verify() { Assert.assertTrue(m_run1, "run1() wasn't run"); Assert.assertTrue(m_run2, "run2() wasn't run"); Assert.assertTrue(m_after, "after1() wasn't run"); Assert.assertEquals(2, m_afterCount); } } ConfigurationGroups6SampleTest.java000066400000000000000000000017711475274123300345210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.Test; /** * afterGroups test when the group contains more than one method * * @author cbeust */ public class ConfigurationGroups6SampleTest { private boolean m_after = false; private boolean m_run1 = false; private boolean m_run2 = false; @Test public void f() {} @Test(groups = "cg6-1") public void run1() { Assert.assertFalse(m_after); m_run1 = true; } @Test(groups = "cg6-1") public void run2() { Assert.assertFalse(m_after); m_run2 = true; } @AfterGroups("cg6-1") public void after() { Assert.assertTrue(m_run1); Assert.assertTrue(m_run2); Assert.assertFalse(m_after); m_after = true; } @Test(dependsOnGroups = {"cg6-1"}) public void verify() { Assert.assertTrue(m_run1, "run1() wasn't run"); Assert.assertTrue(m_run2, "run2() wasn't run"); Assert.assertTrue(m_after, "after1() wasn't run"); } } ConfigurationGroups7SampleTest.java000066400000000000000000000014331475274123300345150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class ConfigurationGroups7SampleTest { private List m_log = new ArrayList<>(); @BeforeGroups({"A"}) private void initA() { m_log.add("1"); } @Test(groups = {"A"}) public void testSomething() { m_log.add("2"); } @Test(groups = {"A"}) public void testSomethingMore() { m_log.add("2"); } @AfterGroups({"A"}) private void cleanUpA() { m_log.add("3"); } @Test(dependsOnGroups = "A") public void verify() { Assert.assertEquals(Arrays.asList("1", "2", "2", "3"), m_log); } } ConfigurationGroups8SampleTest.java000066400000000000000000000020131475274123300345110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Run with group "A" and "B" Make sure that only methods and configurations belonging to that group * get invoked. * * @author cbeust * @date Mar 9, 2006 */ public class ConfigurationGroups8SampleTest { private List m_log = new ArrayList<>(); @Test public void dummy() { m_log.add("should not be invoked"); } @Test(groups = {"A"}) public void testSomething() { m_log.add("1"); } @Test(groups = {"A"}) public void testSomethingMore() { m_log.add("1"); } @AfterMethod private void cleanUpDummy() { m_log.add("should not be invoked"); } @AfterMethod(groups = "A") private void cleanUpA() { m_log.add("a"); } @Test(dependsOnGroups = "A", groups = "B") public void verify() { Assert.assertEquals(Arrays.asList("1", "a", "1", "a"), m_log); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/ConfigurationGroupsTest.java000066400000000000000000000023321475274123300333420ustar00rootroot00000000000000package test.configuration; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ConfigurationGroupsTest extends SimpleBaseTest { @Test public void multipleBeforeGroupTest() { TestNG testng = create(MultipleBeforeGroupTest.class); testng.setGroups("foo"); testng.run(); assertThat(testng.getStatus()).isEqualTo(0); } @Test(dataProvider = "getTestData") public void runTest(Class testClass, String groupName) { TestNG testng = create(testClass); testng.setGroups(groupName); testng.run(); assertThat(testng.getStatus()).isEqualTo(0); } @DataProvider public Object[][] getTestData() { return new Object[][] { {ConfigurationGroups1SampleTest.class, "cg1-a, cg1-1"}, {ConfigurationGroups2SampleTest.class, "cg2-a,cg2-1"}, {ConfigurationGroups3SampleTest.class, "cg34-a, cg34-1"}, {ConfigurationGroups4SampleTest.class, "cg4-1"}, {ConfigurationGroups5SampleTest.class, "cg5-1, cg5-2"}, {ConfigurationGroups6SampleTest.class, "cg6-1"}, {ConfigurationGroups7SampleTest.class, "A"} }; } } ConfigurationInheritGroupsSampleTest.java000066400000000000000000000005611475274123300357520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = {"group1"}) public class ConfigurationInheritGroupsSampleTest { private boolean m_ok = false; @BeforeMethod public void setUp() { m_ok = true; } public void test1() { Assert.assertTrue(m_ok); } } ConfigurationListenerSampleTest.java000066400000000000000000000012551475274123300347360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.configuration.ConfigurationListenerSampleTest.MyTLA; @Listeners(MyTLA.class) public class ConfigurationListenerSampleTest { static boolean m_passed = false; public static class MyTLA extends TestListenerAdapter { @Override public void onConfigurationFailure(ITestResult itr) { m_passed = true; } } @BeforeClass public void bm() { m_passed = false; throw new RuntimeException(); } @Test public void f1() {} } ConfigurationListenerTest.java000066400000000000000000000007341475274123300335750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ConfigurationListenerTest extends SimpleBaseTest { @Test public void listenerShouldBeCalled() { TestNG tng = create(ConfigurationListenerSampleTest.class); Assert.assertFalse(ConfigurationListenerSampleTest.m_passed); tng.run(); Assert.assertTrue(ConfigurationListenerSampleTest.m_passed); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/ConfigurationTest.java000066400000000000000000000015651475274123300321510ustar00rootroot00000000000000package test.configuration; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.Test; import test.configuration.sample.ConfigurationTestSample; import test.configuration.sample.ExternalConfigurationClassSample; import test.configuration.sample.MethodCallOrderTestSample; import test.configuration.sample.SuiteTestSample; /** * Test @Configuration * * @author cbeust */ public class ConfigurationTest extends ConfigurationBaseTest { @Test public void testConfiguration() { testConfiguration(ConfigurationTestSample.class); } @Test public void testMethodCallOrder() { testConfiguration(MethodCallOrderTestSample.class, ExternalConfigurationClassSample.class); } @Test public void testSuite() { testConfiguration(SuiteTestSample.class); Assert.assertEquals(Arrays.asList(1, 2, 3, 4, 5), SuiteTestSample.m_order); } } ConfigurationWithParameters.java000066400000000000000000000007271475274123300341110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ConfigurationWithParameters { private String m_param; @Parameters({"param"}) @BeforeTest public void testInit(String param) { m_param = param; } @Parameters({"param"}) @Test public void testMethod(String param) { Assert.assertEquals(m_param, param); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/GroupsTest.java000066400000000000000000000027221475274123300306150ustar00rootroot00000000000000package test.configuration; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class GroupsTest { private TestNG m_testNg; @BeforeMethod public void setUp() { m_testNg = new TestNG(); } @Test public void verifyDataProviderAfterGroups() { runTest( ConfigurationGroupDataProviderSampleTest.class, ConfigurationGroupDataProviderSampleTest.m_list, Arrays.asList(1, 2, 2, 2, 3)); } @Test public void verifyIteratorDataProviderAfterGroups() { runTest( ConfigurationGroupIteratorDataProviderSampleTest.class, ConfigurationGroupIteratorDataProviderSampleTest.m_list, Arrays.asList(1, 2, 2, 2, 3)); } @Test public void verifyParametersAfterGroups() { runTest( ConfigurationGroupInvocationCountSampleTest.class, ConfigurationGroupInvocationCountSampleTest.m_list, Arrays.asList(1, 2, 2, 2, 3)); } @Test public void verifyBothAfterGroups() { runTest( ConfigurationGroupBothSampleTest.class, ConfigurationGroupBothSampleTest.m_list, Arrays.asList(1, 2, 2, 2, 2, 2, 2, 3)); } private void runTest(Class cls, List list, List expected) { m_testNg.setTestClasses(new Class[] {cls}); m_testNg.setGroups("twice"); m_testNg.run(); Assert.assertEquals(list, expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/MultipleBeforeGroupTest.java000066400000000000000000000006651475274123300332750ustar00rootroot00000000000000package test.configuration; import org.testng.Assert; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @Test(groups = "foo") public class MultipleBeforeGroupTest { private int m_count = 0; @BeforeGroups("foo") public void beforeGroups() { m_count++; } @Test() public void test() {} @Test(dependsOnMethods = "test") public void verify() { Assert.assertEquals(1, m_count); } } ReflectMethodParametrizedConfigurationMethodTest.java000066400000000000000000000026421475274123300402460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** This class/interface */ public class ReflectMethodParametrizedConfigurationMethodTest { private Map m_before = new HashMap<>(); private Map m_after = new HashMap<>(); @BeforeMethod public void beforeMethod(Method tobeInvokedTestMethod) { m_before.put(tobeInvokedTestMethod.getName(), tobeInvokedTestMethod.getName()); } @Test public void test1() {} @Test public void test2() {} @AfterMethod public void afterMethod(Method invokedTestMethod) { m_after.put(invokedTestMethod.getName(), invokedTestMethod.getName()); } @AfterClass public void assertBeforeAfterMethodsInvocations() { Assert.assertTrue( m_before.containsKey("test1"), "@Test method should have been passed to @BeforeMethod"); Assert.assertTrue( m_before.containsKey("test2"), "@Test method should have been passed to @BeforeMethod"); Assert.assertTrue( m_after.containsKey("test1"), "@Test method should have been passed to @AfterMethod"); Assert.assertTrue( m_before.containsKey("test2"), "@Test method should have been passed to @AfterMethod"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/SingleConfigurationTest.java000066400000000000000000000013651475274123300333110ustar00rootroot00000000000000package test.configuration; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Make sure that @BeforeTest is only called once if a factory is used * * @author Cedric Beust */ public class SingleConfigurationTest { private static int m_before; @Factory(dataProvider = "dp") public SingleConfigurationTest(int n) {} @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {42}, new Object[] {43}, }; } @BeforeTest public void bt() { m_before++; } @Test public void verify() { Assert.assertEquals(m_before, 1); } } SuiteFactoryOnceSample1Test.java000066400000000000000000000006261475274123300337310ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class SuiteFactoryOnceSample1Test { public static int m_before = 0; public static int m_after = 0; @BeforeSuite public void bs() { m_before++; } @AfterSuite public void as() { m_after++; } @Test public void g1() {} } SuiteFactoryOnceSample2Test.java000066400000000000000000000004001475274123300337200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationpackage test.configuration; import org.testng.annotations.Factory; public class SuiteFactoryOnceSample2Test { @Factory public Object[] factory() { return new Object[] {new SuiteFactoryOnceSample1Test(), new SuiteFactoryOnceSample1Test()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/SuiteFactoryOnceTest.java000066400000000000000000000011311475274123300325550ustar00rootroot00000000000000package test.configuration; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class SuiteFactoryOnceTest extends SimpleBaseTest { @Test public void suiteMethodsShouldOnlyRunOnce() { TestNG tng = create(SuiteFactoryOnceSample2Test.class); SuiteFactoryOnceSample1Test.m_before = 0; SuiteFactoryOnceSample1Test.m_after = 0; tng.run(); assertThat(SuiteFactoryOnceSample1Test.m_before).isEqualTo(1); assertThat(SuiteFactoryOnceSample1Test.m_after).isEqualTo(1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1338/000077500000000000000000000000001475274123300274315ustar00rootroot00000000000000BaseGitHub1338Sample.java000066400000000000000000000007611475274123300336570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1338package test.configuration.github1338; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; public class BaseGitHub1338Sample { private String someObject = null; @BeforeClass(alwaysRun = true) public void classSetUp() { someObject = "not null"; } @BeforeGroups( groups = {"group1"}, alwaysRun = true) public void groupSetUp() { if (someObject == null) { throw new NullPointerException("someObject is null"); } } } FirstGitHub1338Sample.java000066400000000000000000000003141475274123300340660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1338package test.configuration.github1338; import org.testng.annotations.Test; public class FirstGitHub1338Sample extends BaseGitHub1338Sample { @Test(groups = {"group1"}) public void firstTest() {} } SecondGitHub1338Sample.java000066400000000000000000000003161475274123300342140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1338package test.configuration.github1338; import org.testng.annotations.Test; public class SecondGitHub1338Sample extends BaseGitHub1338Sample { @Test(groups = {"group2"}) public void secondTest() {} } ThirdGitHub1338Sample.java000066400000000000000000000003141475274123300340510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1338package test.configuration.github1338; import org.testng.annotations.Test; public class ThirdGitHub1338Sample extends BaseGitHub1338Sample { @Test(groups = {"group1"}) public void thirdTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1625/000077500000000000000000000000001475274123300274305ustar00rootroot00000000000000TestRunnerIssue1625.java000066400000000000000000000013471475274123300336610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1625package test.configuration.github1625; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class TestRunnerIssue1625 extends SimpleBaseTest { @Test(dataProvider = "dp") public void testMethod(Class clazz) { TestNG testNG = create(clazz); testNG.setParallel(XmlSuite.ParallelMode.METHODS); testNG.run(); assertThat(testNG.getStatus()).isEqualTo(0); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { {TestclassSampleUsingMocks.class}, {TestclassSampleWithoutUsingMocks.class} }; } } TestclassSampleUsingMocks.java000066400000000000000000000012621475274123300353270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1625package test.configuration.github1625; import java.util.List; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestclassSampleUsingMocks { @Mock List list; AutoCloseable mocks; @BeforeClass public void beforeClass() { mocks = MockitoAnnotations.openMocks(this); } @AfterClass public void closeMocks() throws Exception { mocks.close(); } @Test public void first() { Assert.assertNotNull(list); } @Test public void second() { Assert.assertNotNull(list); } } TestclassSampleWithoutUsingMocks.java000066400000000000000000000007601475274123300367150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1625package test.configuration.github1625; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestclassSampleWithoutUsingMocks { private List list; @BeforeClass public void beforeClass() { list = new ArrayList<>(); } @Test public void first() { Assert.assertNotNull(list); } @Test public void second() { Assert.assertNotNull(list); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1700/000077500000000000000000000000001475274123300274225ustar00rootroot00000000000000BaseClassSample.java000066400000000000000000000010131475274123300332030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1700package test.configuration.github1700; import java.lang.reflect.Method; import java.util.List; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.collections.Lists; public class BaseClassSample { public static List messages = Lists.newArrayList(); @BeforeMethod(alwaysRun = true) public void setUp(Method method) { if (method.getName().endsWith("test1")) { Assert.assertEquals(2, 1); } messages.add(getClass().getCanonicalName() + ".setup()"); } } ChildClassTestSample1.java000066400000000000000000000003561475274123300343060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1700package test.configuration.github1700; import org.testng.annotations.Test; public class ChildClassTestSample1 extends BaseClassSample { @Test public void test1() { messages.add(getClass().getCanonicalName() + ".test1()"); } } ChildClassTestSample2.java000066400000000000000000000003561475274123300343070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1700package test.configuration.github1700; import org.testng.annotations.Test; public class ChildClassTestSample2 extends BaseClassSample { @Test public void test2() { messages.add(getClass().getCanonicalName() + ".test2()"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/github1700/RunTest.java000066400000000000000000000012271475274123300316730ustar00rootroot00000000000000package test.configuration.github1700; import static org.assertj.core.api.Java6Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class RunTest extends SimpleBaseTest { @Test(description = "GITHUB-1700") public void testMethod() { TestNG tng = create(); tng.setTestClasses(new Class[] {ChildClassTestSample1.class, ChildClassTestSample2.class}); tng.run(); assertThat(BaseClassSample.messages) .containsOnly( ChildClassTestSample2.class.getCanonicalName() + ".setup()", ChildClassTestSample2.class.getCanonicalName() + ".test2()"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1035/000077500000000000000000000000001475274123300272715ustar00rootroot00000000000000InvocationTracker.java000066400000000000000000000016101475274123300335000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1035package test.configuration.issue1035; import java.util.Objects; public class InvocationTracker { private final long time; private final long threadId; private final Object testInstance; public InvocationTracker(long time, long threadId, Object testInstance) { this.time = time; this.threadId = threadId; this.testInstance = testInstance; } public long getThreadId() { return threadId; } public long getTime() { return time; } public Object getTestInstance() { return testInstance; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InvocationTracker tracker = (InvocationTracker) o; return testInstance == tracker.testInstance; } @Override public int hashCode() { return Objects.hashCode(testInstance); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1035/MyFactory.java000066400000000000000000000011471475274123300320540ustar00rootroot00000000000000package test.configuration.issue1035; import static java.util.Collections.newSetFromMap; import static java.util.Collections.synchronizedSet; import java.util.IdentityHashMap; import java.util.Set; import org.testng.annotations.Factory; public class MyFactory { public static final Set TRACKER = synchronizedSet(newSetFromMap(new IdentityHashMap<>())); @Factory public Object[] instances() { return new Object[] { new TestclassExample(), new TestclassExample(), new TestclassExample(), new TestclassExample(), new TestclassExample() }; } } TestclassExample.java000066400000000000000000000011671475274123300333430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1035package test.configuration.issue1035; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestclassExample { @BeforeClass public void beforeClass() throws InterruptedException { printer(); Thread.sleep(2000); } @Test public void test() {} @AfterClass public void afterClass() {} private void printer() { long threadId = Thread.currentThread().getId(); long time = System.currentTimeMillis(); InvocationTracker tracker = new InvocationTracker(time, threadId, this); MyFactory.TRACKER.add(tracker); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1753/000077500000000000000000000000001475274123300273005ustar00rootroot00000000000000ChildClassSample.java000066400000000000000000000016041475274123300332400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1753package test.configuration.issue1753; import java.lang.reflect.Method; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ChildClassSample extends ParentClassSample { @BeforeMethod(alwaysRun = true) public void childClassBeforeMethod(Method method, ITestResult result) { result.setAttribute( getClass().getSimpleName() + "-childClassBeforeMethod", getClass().getName() + ".childClassBeforeMethod()"); throw new RuntimeException("Forcing a failure"); } @Test public void testMethod() {} @AfterMethod(alwaysRun = true) public void childClassAfterMethod(Method method, ITestResult result) { result.setAttribute( getClass().getSimpleName() + "-childClassAfterMethod", getClass().getName() + ".childClassAfterMethod()"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1753/IssueTest.java000066400000000000000000000020671475274123300321000ustar00rootroot00000000000000package test.configuration.issue1753; import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Maps; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testToEnsureProperTestResultIsReferredInNativeInjection() { TestNG testng = create(ChildClassSample.class); LocalReporter reporter = new LocalReporter(); testng.addListener(reporter); testng.run(); assertThat(reporter.getAttributes()).containsAllEntriesOf(expected()); } private static Map expected() { Map expected = Maps.newHashMap(); expected.put( ChildClassSample.class.getSimpleName() + "-childClassBeforeMethod", ChildClassSample.class.getName() + ".childClassBeforeMethod()"); expected.put( ChildClassSample.class.getSimpleName() + "-parentClassBeforeMethod", ChildClassSample.class.getName() + ".parentClassBeforeMethod()"); return expected; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1753/LocalReporter.java000066400000000000000000000021661475274123300327250ustar00rootroot00000000000000package test.configuration.issue1753; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import org.testng.*; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; public class LocalReporter implements IReporter { private Map attributes = Maps.newHashMap(); @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { suites.forEach( suite -> suite.getResults().values().stream() .flatMap(iSuiteResult -> extractSkippedResults(iSuiteResult).stream()) .forEach(this::extractAttributes)); } private void extractAttributes(ITestResult result) { Consumer attribute = each -> attributes.put(each, result.getAttribute(each).toString()); result.getAttributeNames().forEach(attribute); } private static Set extractSkippedResults(ISuiteResult suiteResult) { return suiteResult.getTestContext().getSkippedTests().getAllResults(); } Map getAttributes() { return attributes; } } ParentClassSample.java000066400000000000000000000015331475274123300334470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue1753package test.configuration.issue1753; import java.lang.reflect.Method; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class ParentClassSample { @BeforeMethod(alwaysRun = true) public void parentClassBeforeMethod(Method method, ITestResult result) { result.setAttribute( getClass().getSimpleName() + "-parentClassBeforeMethod", getClass().getName() + ".parentClassBeforeMethod()"); throw new RuntimeException("Forcing a failure"); } @AfterMethod(alwaysRun = true) public void parentClassAfterMethod(Method method, ITestResult result) { result.setAttribute( getClass().getSimpleName() + "-parentClassAfterMethod", getClass().getName() + ".parentClassAfterMethod()"); throw new RuntimeException("Forcing a failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2209/000077500000000000000000000000001475274123300272755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2209/IssueTest.java000066400000000000000000000025201475274123300320670ustar00rootroot00000000000000package test.configuration.issue2209; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testGithub2209() { TestNG tng = create(Sample.class); tng.setGroups("groupM"); InvokedMethodNameListener listener = new InvokedMethodNameListener(false); tng.addListener(listener); tng.run(); assertThat(listener.getInvokedMethodNames()) .containsExactly( "beforeClass", "beforeMethod", "test1", "afterMethod", "beforeMethod", "test2", "afterMethod", "afterClass"); } @Test(groups = {"groupM"}) public static class Sample { @BeforeClass public void beforeClass() {} @BeforeMethod public void beforeMethod() {} @Test(groups = {"groupK"}) public void test1() {} @Test(groups = {"groupL"}) public void test2() {} @AfterMethod public void afterMethod() {} @AfterClass public void afterClass() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2254/000077500000000000000000000000001475274123300272755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2254/IssueTest.java000066400000000000000000000033101475274123300320650ustar00rootroot00000000000000package test.configuration.issue2254; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlPackage; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2254") public void ensureConfigurationsAreInvokedOnce() { List packages = new ArrayList<>(); XmlPackage xmlPackage = new XmlPackage("test.configuration.issue2254.samples"); packages.add(xmlPackage); XmlTest test = new XmlTest(); test.setName("MyTest"); test.setXmlPackages(packages); XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("MySuite"); xmlSuite.setTests(Collections.singletonList(test)); test.addIncludedGroup("A"); test.setXmlSuite(xmlSuite); MyInvokedMethodListener listener = new MyInvokedMethodListener(); TestNG tng = new TestNG(); tng.addListener(listener); tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); Assert.assertEquals(listener.beforeCount, 9); Assert.assertEquals(listener.afterCount, 9); } public static class MyInvokedMethodListener implements IInvokedMethodListener { int beforeCount = 0; int afterCount = 0; @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { beforeCount++; } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { afterCount++; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2254/samples/000077500000000000000000000000001475274123300307415ustar00rootroot00000000000000SampleTestCase.java000066400000000000000000000015631475274123300344070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2254/samplespackage test.configuration.issue2254.samples; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @Test(groups = "A") public class SampleTestCase { @BeforeSuite public void beforeSuite() {} @BeforeTest public void beforeTest() {} @BeforeClass public void beforeClass() {} @BeforeMethod public void beforeMethod() {} @Test public void testMethod() {} @AfterMethod public void afterMethod() {} @AfterClass public void afterClass() {} @AfterTest public void afterTest() {} @AfterSuite public void afterSuite() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2400/000077500000000000000000000000001475274123300272665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2400/DataStore.java000066400000000000000000000006671475274123300320300ustar00rootroot00000000000000package test.configuration.issue2400; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public enum DataStore { INSTANCE; private Map tracker = new HashMap<>(); public void increment(String key) { tracker.computeIfAbsent(key, k -> new AtomicInteger(0)).incrementAndGet(); } public Map getTracker() { return tracker; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2400/IssueTest.java000066400000000000000000000012431475274123300320610ustar00rootroot00000000000000package test.configuration.issue2400; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2400") public void ensureDefaultConfigurationsAreSkipped() { TestNG testng = create(TestNGTestClass.class); testng.run(); SoftAssert softAssert = new SoftAssert(); DataStore.INSTANCE .getTracker() .forEach( (key, value) -> softAssert.assertEquals( value.get(), 1, "Ensuring " + key + " got invoked only once")); softAssert.assertAll(); } } TestNGTestClass.java000066400000000000000000000025661475274123300330550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2400package test.configuration.issue2400; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class TestNGTestClass implements TestRunnerCapabilities { @BeforeSuite @Override public void beforeSuite() { DataStore.INSTANCE.increment("beforeSuite"); } @BeforeTest @Override public void beforeTest() { DataStore.INSTANCE.increment("beforeTest"); } @BeforeClass @Override public void beforeClass() { DataStore.INSTANCE.increment("beforeClass"); } @BeforeMethod @Override public void beforeMethod() { DataStore.INSTANCE.increment("beforeMethod"); } @Test public void testMethod() {} @AfterMethod @Override public void afterMethod() { DataStore.INSTANCE.increment("afterMethod"); } @AfterClass @Override public void afterClass() { DataStore.INSTANCE.increment("afterClass"); } @AfterTest @Override public void afterTest() { DataStore.INSTANCE.increment("afterTest"); } @AfterSuite @Override public void afterSuite() { DataStore.INSTANCE.increment("afterSuite"); } } TestRunnerCapabilities.java000066400000000000000000000022741475274123300345020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2400package test.configuration.issue2400; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public interface TestRunnerCapabilities { @BeforeSuite default void beforeSuite() { DataStore.INSTANCE.increment("beforeSuite"); } @BeforeTest default void beforeTest() { DataStore.INSTANCE.increment("beforeTest"); } @BeforeClass default void beforeClass() { DataStore.INSTANCE.increment("beforeClass"); } @BeforeMethod default void beforeMethod() { DataStore.INSTANCE.increment("beforeMethod"); } @AfterMethod default void afterMethod() { DataStore.INSTANCE.increment("afterMethod"); } @AfterClass default void afterClass() { DataStore.INSTANCE.increment("afterClass"); } @AfterTest default void afterTest() { DataStore.INSTANCE.increment("afterTest"); } @AfterSuite default void afterSuite() { DataStore.INSTANCE.increment("afterSuite"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2426/000077500000000000000000000000001475274123300272765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2426/IssueTest.java000066400000000000000000000012131475274123300320660ustar00rootroot00000000000000package test.configuration.issue2426; import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testIfConfigMethodsHaveAccessToFactoryParams() { TestNG testng = create(SampleTestCase.class); MyMethodListener listener = new MyMethodListener(); testng.addListener(listener); testng.run(); Map, Object[]> data = listener.getContents(); assertThat(data).hasSize(8); data.values().forEach(each -> assertThat(each).hasSize(2)); } } MyMethodListener.java000066400000000000000000000026111475274123300333160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2426package test.configuration.issue2426; import java.util.HashMap; import java.util.Map; import org.testng.IConfigurationListener; import org.testng.ITestResult; import org.testng.annotations.*; public class MyMethodListener implements IConfigurationListener { private final Map, Object[]> contents = new HashMap<>(); @Override public void onConfigurationSuccess(ITestResult tr) { Object[] values = tr.getMethod().getFactoryMethodParamsInfo().getParameters(); if (tr.getMethod().isBeforeSuiteConfiguration()) { contents.put(BeforeSuite.class, values); } if (tr.getMethod().isAfterSuiteConfiguration()) { contents.put(AfterSuite.class, values); } if (tr.getMethod().isBeforeTestConfiguration()) { contents.put(BeforeTest.class, values); } if (tr.getMethod().isAfterTestConfiguration()) { contents.put(AfterTest.class, values); } if (tr.getMethod().isBeforeClassConfiguration()) { contents.put(BeforeClass.class, values); } if (tr.getMethod().isAfterClassConfiguration()) { contents.put(AfterClass.class, values); } if (tr.getMethod().isBeforeMethodConfiguration()) { contents.put(BeforeMethod.class, values); } if (tr.getMethod().isAfterMethodConfiguration()) { contents.put(AfterMethod.class, values); } } public Map, Object[]> getContents() { return contents; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2426/SampleTestCase.java000066400000000000000000000022771475274123300330260ustar00rootroot00000000000000package test.configuration.issue2426; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class SampleTestCase { @DataProvider(name = "constructorArguments") public static Object[][] constructorArguments() { return new Object[][] { {1, false}, {2, true} }; } @Factory(dataProvider = "constructorArguments") public SampleTestCase(int number, final boolean bool) {} @BeforeSuite public void beforeSuite() {} @BeforeTest public void beforeTest() {} @BeforeClass public void beforeClass() {} @BeforeMethod public void beforeMethod() {} @Test public void test() {} @AfterMethod public void afterMethod() {} @AfterClass public void afterClass() {} @AfterTest public void afterTest() {} @AfterSuite public void afterSuite() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2432/000077500000000000000000000000001475274123300272735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2432/Base.java000066400000000000000000000007331475274123300310130ustar00rootroot00000000000000package test.configuration.issue2432; import org.testng.annotations.BeforeSuite; public class Base { @BeforeSuite(groups = "prepareConfig") public void prepareConfig() {} @BeforeSuite(groups = "uploadConfigToDatabase", dependsOnGroups = "prepareConfig") public void uploadConfigToDatabase() {} @BeforeSuite( groups = "verifyConfigurationAfterInstall", dependsOnGroups = "uploadConfigToDatabase") public void verifyConfigurationAfterInstall() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2432/IssueTest.java000066400000000000000000000030011475274123300320600ustar00rootroot00000000000000package test.configuration.issue2432; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2432") public void ensureNoImplicitDependencyIsAddedWhenGroupsAreInvolved() { XmlClass xmlClass = new XmlClass(Test1.class); XmlInclude xmlInclude = new XmlInclude("test1"); xmlClass.setIncludedMethods(Collections.singletonList(xmlInclude)); XmlSuite xmlsuite = createXmlSuite("2432_suite"); xmlsuite.setParallel(ParallelMode.NONE); XmlTest xmlTest = new XmlTest(xmlsuite); xmlTest.setName("2432_test"); xmlTest.setXmlClasses(Collections.singletonList(xmlClass)); TestNG testng = create(xmlsuite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); List expected = Arrays.asList( "prepareConfig", "uploadConfigToDatabase", "verifyConfigurationAfterInstall", "prepareConfigForTest1", "test1"); assertThat(listener.getInvokedMethodNames()).containsExactlyElementsOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/issue2432/Test1.java000066400000000000000000000004401475274123300311340ustar00rootroot00000000000000package test.configuration.issue2432; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class Test1 extends Base { @BeforeSuite(groups = "prepareConfig") public void prepareConfigForTest1() {} @Test(groups = "test") public void test1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/sample/000077500000000000000000000000001475274123300271115ustar00rootroot00000000000000BaseSuiteTestSample.java000066400000000000000000000006601475274123300335650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/samplepackage test.configuration.sample; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public class BaseSuiteTestSample { public static List m_order; @BeforeSuite public void beforeSuiteParent() { m_order = new ArrayList<>(); m_order.add(1); } @AfterSuite public void afterSuiteParent() { m_order.add(4); } } ConfigurationTestSample.java000066400000000000000000000073061475274123300345140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/samplepackage test.configuration.sample; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class ConfigurationTestSample { private boolean m_beforeSuite = false; private boolean m_afterSuite = false; private boolean m_beforeClass = false; private boolean m_afterClass = false; private boolean m_beforeMethod = false; private boolean m_afterMethod = false; @BeforeSuite public void beforeSuite() { assertFalse(m_afterSuite, "afterSuite shouldn't have run"); assertFalse(m_beforeClass, "beforeClass shouldn't have run"); assertFalse(m_afterClass, "afterClass shouldn't have run"); assertFalse(m_beforeMethod, "beforeMethod shouldn't have run"); assertFalse(m_afterMethod, "afterMethod shouldn't have run"); m_beforeSuite = true; } @BeforeClass public void beforeClass() { assertTrue(m_beforeSuite, "beforeSuite should have run"); assertFalse(m_afterSuite, "afterSuite shouldn't have run"); assertFalse(m_beforeClass, "beforeClass shouldn't have run"); assertFalse(m_afterClass, "afterClass shouldn't have run"); assertFalse(m_beforeMethod, "beforeMethod shouldn't have run"); assertFalse(m_afterMethod, "afterMethod shouldn't have run"); m_beforeClass = true; } @BeforeMethod public void beforeMethod() { assertTrue(m_beforeSuite, "beforeSuite should have run"); assertTrue(m_beforeClass, "beforeClass have run"); assertFalse(m_afterSuite, "afterSuite shouldn't have run"); assertFalse(m_afterClass, "afterClass shouldn't have run"); assertFalse(m_beforeMethod, "beforeMethod shouldn't have run"); assertFalse(m_afterMethod, "afterMethod shouldn't have run"); m_beforeMethod = true; } @AfterMethod public void afterMethod() { assertTrue(m_beforeSuite, "beforeSuite should have run"); assertTrue(m_beforeClass, "beforeClass have run"); assertTrue(m_beforeMethod, "beforeMethod should have run"); assertFalse(m_afterSuite, "afterSuite shouldn't have run"); assertFalse(m_afterClass, "afterClass shouldn't have run"); assertFalse(m_afterMethod, "afterMethod shouldn't have run"); m_afterMethod = true; } @AfterClass public void afterClass() { assertTrue(m_beforeSuite, "beforeSuite should have run"); assertTrue(m_beforeClass, "beforeClass have run"); assertTrue(m_beforeMethod, "beforeMethod should have run"); assertTrue(m_afterMethod, "afterMethod should have run"); assertFalse(m_afterClass, "afterClass shouldn't have run"); assertFalse(m_afterSuite, "afterSuite shouldn't have run"); m_afterClass = true; } @AfterSuite public void afterSuite() { assertTrue(m_beforeSuite, "beforeSuite should have run"); assertTrue(m_beforeClass, "beforeClass have run"); assertTrue(m_beforeMethod, "beforeMethod should have run"); assertTrue(m_afterMethod, "afterMethod should have run"); assertTrue(m_afterClass, "afterClass should have run"); assertFalse(m_afterSuite, "afterSuite shouldn't have run"); m_afterSuite = true; } @Test public void verify() { assertTrue(m_beforeSuite, "beforeSuite should have run"); assertTrue(m_beforeClass, "beforeClass have run"); assertTrue(m_beforeMethod, "beforeMethod should have run"); assertFalse(m_afterSuite, "afterSuite shouldn't have run"); assertFalse(m_afterClass, "afterClass shouldn't have run"); assertFalse(m_afterMethod, "afterMethod shouldn't have run"); } } ExternalConfigurationClassSample.java000066400000000000000000000030071475274123300363370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/samplepackage test.configuration.sample; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public class ExternalConfigurationClassSample { public static boolean s_afterMethod; public static boolean s_afterClass; public static boolean s_afterTest; @BeforeSuite public void beforeSuite() { MethodCallOrderTestSample.s_beforeSuite = true; } @AfterSuite public void cleanUp() { s_afterMethod = false; s_afterClass = false; s_afterTest = false; } @BeforeTest public void beforeTest() { assertTrue(MethodCallOrderTestSample.s_beforeSuite); assertFalse(MethodCallOrderTestSample.s_beforeTest); assertFalse(MethodCallOrderTestSample.s_beforeClass); assertFalse(MethodCallOrderTestSample.s_beforeMethod); MethodCallOrderTestSample.s_beforeTest = true; } @AfterTest public void afterTest() { assertTrue(s_afterMethod, "afterTestMethod should have been run"); assertTrue(s_afterClass, "afterTestClass should have been run"); assertFalse(s_afterTest, "afterTest should haven't been run"); s_afterTest = true; } @AfterSuite public void afterSuite() { assertTrue(s_afterMethod, "afterTestMethod should have been run"); assertTrue(s_afterClass, "afterTestClass should have been run"); assertTrue(s_afterTest, "afterTest should have been run"); } } MethodCallOrderTestSample.java000066400000000000000000000042001475274123300347030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/samplepackage test.configuration.sample; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class MethodCallOrderTestSample { public static boolean s_beforeSuite; public static boolean s_beforeTest; public static boolean s_beforeClass; public static boolean s_beforeMethod; @BeforeClass public void beforeClass() { assertTrue(s_beforeSuite); assertTrue(s_beforeTest); assertFalse(s_beforeClass); assertFalse(s_beforeMethod); s_beforeClass = true; } @AfterSuite public void cleanUp() { s_beforeSuite = false; s_beforeTest = false; s_beforeClass = false; s_beforeMethod = false; } @BeforeMethod public void beforeMethod() { assertTrue(s_beforeSuite); assertTrue(s_beforeTest); assertTrue(s_beforeClass); assertFalse(s_beforeMethod); s_beforeMethod = true; } @Test public void realTest() { assertTrue(s_beforeSuite); assertTrue(s_beforeTest); assertTrue(s_beforeClass); assertTrue(s_beforeMethod); } @AfterMethod public void afterMethod() { assertFalse( ExternalConfigurationClassSample.s_afterMethod, "afterTestMethod shouldn't have been run"); assertFalse( ExternalConfigurationClassSample.s_afterClass, "afterTestClass shouldn't have been run"); assertFalse(ExternalConfigurationClassSample.s_afterTest, "afterTest should haven't been run"); ExternalConfigurationClassSample.s_afterMethod = true; } @AfterClass public void afterClass() { assertTrue( ExternalConfigurationClassSample.s_afterMethod, "afterTestMethod should have been run"); assertFalse( ExternalConfigurationClassSample.s_afterClass, "afterTestClass shouldn't have been run"); assertFalse(ExternalConfigurationClassSample.s_afterTest, "afterTest should haven't been run"); ExternalConfigurationClassSample.s_afterClass = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configuration/sample/SuiteTestSample.java000066400000000000000000000007721475274123300330550ustar00rootroot00000000000000package test.configuration.sample; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class SuiteTestSample extends BaseSuiteTestSample { @BeforeSuite(dependsOnMethods = {"beforeSuiteParent"}) public void beforeSuiteChild() { m_order.add(2); } @AfterSuite(dependsOnMethods = {"afterSuiteParent"}) public void afterSuiteChild() { m_order.add(5); } @Test public void test1() { m_order.add(3); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicy/000077500000000000000000000000001475274123300304205ustar00rootroot00000000000000ClassWithFailedBeforeClassMethod.java000066400000000000000000000006241475274123300374660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ClassWithFailedBeforeClassMethod { @BeforeClass public void setupClassFails() { throw new RuntimeException("setup class fail"); } @BeforeMethod public void setupMethod() {} @Test public void test1() {} } ClassWithFailedBeforeClassMethodAndAfterClass.java000066400000000000000000000006371475274123300420650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ClassWithFailedBeforeClassMethodAndAfterClass { @BeforeClass public void setupClassFails() { throw new RuntimeException("setup class fail"); } @Test public void test1() {} @AfterClass public void tearDownClass() {} } ClassWithFailedBeforeClassMethodAndBeforeGroupsAfterClassAfterGroups.java000066400000000000000000000013121475274123300465610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class ClassWithFailedBeforeClassMethodAndBeforeGroupsAfterClassAfterGroups { @BeforeClass(groups = "group1") public void setupClassFails() { throw new RuntimeException("setup class fail"); } @BeforeGroups(groups = "group1") public void beforeGroup() {} @Test(groups = "group1") public void test1() {} @AfterClass(groups = "group1") public void tearDownClass() {} @AfterGroups(groups = "group1") public void afterGroup() {} } ClassWithFailedBeforeClassMethodAndBeforeMethodAfterMethodAfterClass.java000066400000000000000000000011571475274123300464720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ClassWithFailedBeforeClassMethodAndBeforeMethodAfterMethodAfterClass { @BeforeClass public void setupClassFails() { throw new RuntimeException("setup class fail"); } @BeforeMethod public void setupMethod() {} @Test public void test1() {} @AfterMethod public void tearDownMethod() {} @AfterClass public void tearDownClass() {} } ClassWithFailedBeforeMethod.java000066400000000000000000000004651475274123300365030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ClassWithFailedBeforeMethod { @BeforeMethod public void setupShouldFail() { throw new RuntimeException("Failing in setUp"); } @Test public void test1() {} } ClassWithFailedBeforeMethodAndMultipleInvocations.java000066400000000000000000000011641475274123300430540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ClassWithFailedBeforeMethodAndMultipleInvocations { @BeforeMethod public void setupShouldFail() { throw new RuntimeException("Failing in setUp"); } @DataProvider(name = "data.provider") public Object[][] dataProvider() { return new Object[][] {new Object[] {"data1"}, new Object[] {"data2"}}; } @Test(dataProvider = "data.provider") public void test1(String s) {} @Test(invocationCount = 2) public void test2() {} } ClassWithFailedBeforeMethodAndMultipleTests.java000066400000000000000000000005471475274123300416660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ClassWithFailedBeforeMethodAndMultipleTests { @BeforeMethod public void setupShouldFail() { throw new RuntimeException("Failing in setUp"); } @Test public void test1() {} @Test public void test2() {} } ClassWithSkippingBeforeMethod.java000066400000000000000000000007031475274123300370760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.SkipException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ClassWithSkippingBeforeMethod { private int invocations = 0; @BeforeMethod public void beforeMethod() { invocations++; if (invocations == 2) { throw new SkipException("skipping"); } } @Test public void test1() {} @Test public void test2() {} } ExtendsClassWithFailedBeforeClassMethod.java000066400000000000000000000004271475274123300410220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.Test; public class ExtendsClassWithFailedBeforeClassMethod extends ClassWithFailedBeforeClassMethod { @Test public void test2() { // should be skipped, but BeforeClass method attempted again } } ExtendsClassWithFailedBeforeMethod.java000066400000000000000000000004501475274123300400300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ExtendsClassWithFailedBeforeMethod extends ClassWithFailedBeforeMethod { @BeforeMethod public void setupExtension() {} @Test public void test2() {} } FactoryClassWithFailedBeforeClassMethod.java000066400000000000000000000006471475274123300410230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.Factory; public class FactoryClassWithFailedBeforeClassMethod extends ClassWithFailedBeforeClassMethod { @Factory public Object[] createTests() { Object[] instances = new Object[2]; instances[0] = new FactoryClassWithFailedBeforeClassMethod(); instances[1] = new FactoryClassWithFailedBeforeClassMethod(); return instances; } } FactoryClassWithFailedBeforeMethod.java000066400000000000000000000006231475274123300400270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.Factory; public class FactoryClassWithFailedBeforeMethod extends ClassWithFailedBeforeMethod { @Factory public Object[] createTests() { Object[] instances = new Object[2]; instances[0] = new FactoryClassWithFailedBeforeMethod(); instances[1] = new FactoryClassWithFailedBeforeMethod(); return instances; } } FactoryClassWithFailedBeforeMethodAndMultipleInvocations.java000066400000000000000000000007571475274123300444130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import org.testng.annotations.Factory; public class FactoryClassWithFailedBeforeMethodAndMultipleInvocations extends ClassWithFailedBeforeMethodAndMultipleInvocations { @Factory public Object[] createTests() { Object[] instances = new Object[2]; instances[0] = new FactoryClassWithFailedBeforeMethodAndMultipleInvocations(); instances[1] = new FactoryClassWithFailedBeforeMethodAndMultipleInvocations(); return instances; } } FailurePolicyTest.java000066400000000000000000000132421475274123300346150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/configurationfailurepolicypackage test.configurationfailurepolicy; import static org.testng.Assert.assertEquals; import static test.SimpleBaseTest.getPathToResource; import org.testng.ITestContext; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import testhelper.OutputDirectoryPatch; public class FailurePolicyTest { // only if this is run from an xml file that sets this on the suite @BeforeClass(enabled = false) public void setupClass(ITestContext testContext) { assertEquals( testContext.getSuite().getXmlSuite().getConfigFailurePolicy(), XmlSuite.FailurePolicy.CONTINUE); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { // params - confFail, confSkip, skippedTests new Object[] {new Class[] {ClassWithFailedBeforeClassMethod.class}, 1, 1, 1}, new Object[] {new Class[] {ClassWithFailedBeforeClassMethodAndAfterClass.class}, 1, 1, 1}, new Object[] {new Class[] {ClassWithFailedBeforeMethodAndMultipleTests.class}, 2, 0, 2}, new Object[] { new Class[] {ClassWithFailedBeforeClassMethodAndBeforeMethodAfterMethodAfterClass.class}, 1, 3, 1 }, new Object[] {new Class[] {ClassWithFailedBeforeMethodAndMultipleInvocations.class}, 4, 0, 4}, new Object[] {new Class[] {ExtendsClassWithFailedBeforeMethod.class}, 2, 2, 2}, new Object[] {new Class[] {ExtendsClassWithFailedBeforeClassMethod.class}, 1, 2, 2}, new Object[] { new Class[] { ClassWithFailedBeforeClassMethod.class, ExtendsClassWithFailedBeforeClassMethod.class }, 2, 3, 3 }, new Object[] {new Class[] {ClassWithSkippingBeforeMethod.class}, 0, 1, 1}, new Object[] {new Class[] {FactoryClassWithFailedBeforeMethod.class}, 2, 0, 2}, new Object[] { new Class[] {FactoryClassWithFailedBeforeMethodAndMultipleInvocations.class}, 8, 0, 8 }, new Object[] {new Class[] {FactoryClassWithFailedBeforeClassMethod.class}, 2, 2, 2}, }; } @Test(dataProvider = "dp") public void confFailureTest( Class[] classesUnderTest, int configurationFailures, int configurationSkips, int skippedTests) { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = new TestNG(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(classesUnderTest); testng.addListener(tla); testng.setConfigFailurePolicy(XmlSuite.FailurePolicy.CONTINUE); testng.run(); verify(tla, configurationFailures, configurationSkips, skippedTests); } @Test public void confFailureTestInvolvingGroups() { Class[] classesUnderTest = new Class[] {ClassWithFailedBeforeClassMethodAndBeforeGroupsAfterClassAfterGroups.class}; TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = new TestNG(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(classesUnderTest); testng.addListener(tla); testng.setConfigFailurePolicy(XmlSuite.FailurePolicy.CONTINUE); testng.setGroups("group1"); testng.run(); verify(tla, 1, 3, 1); } @Test public void commandLineTest_policyAsSkip() { String[] argv = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-configfailurepolicy", "skip", "-testclass", ClassWithFailedBeforeMethodAndMultipleTests.class.getCanonicalName() }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); verify(tla, 1, 1, 2); } @Test public void commandLineTest_policyAsContinue() { String[] argv = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-configfailurepolicy", "continue", "-testclass", ClassWithFailedBeforeMethodAndMultipleTests.class.getCanonicalName() }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); verify(tla, 2, 0, 2); } @Test public void commandLineTestWithXMLFile_policyAsSkip() { String[] argv = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-configfailurepolicy", "skip", getPathToResource("testng-configfailure.xml") }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); verify(tla, 1, 1, 2); } @Test public void commandLineTestWithXMLFile_policyAsContinue() { String[] argv = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-configfailurepolicy", "continue", getPathToResource("testng-configfailure.xml") }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); verify(tla, 2, 0, 2); } private void verify( TestListenerAdapter tla, int configurationFailures, int configurationSkips, int skippedTests) { assertEquals( tla.getConfigurationFailures().size(), configurationFailures, "wrong number of configuration failures"); assertEquals( tla.getConfigurationSkips().size(), configurationSkips, "wrong number of configuration skips"); assertEquals(tla.getSkippedTests().size(), skippedTests, "wrong number of skipped tests"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/converter/000077500000000000000000000000001475274123300247705ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/converter/ConverterSample1.java000066400000000000000000000006201475274123300310230ustar00rootroot00000000000000package test.converter; import junit.framework.TestCase; public class ConverterSample1 extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public final void testClassJunit() {} public final void testSetClassId() {} public final void testSetClassName() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/custom/000077500000000000000000000000001475274123300242735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/custom/CustomAttributeTest.java000066400000000000000000000024171475274123300311400ustar00rootroot00000000000000package test.custom; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.IAnnotationTransformer; import org.testng.TestNG; import org.testng.annotations.CustomAttribute; import org.testng.annotations.Test; import test.SimpleBaseTest; public class CustomAttributeTest extends SimpleBaseTest { @Test public void ensureCustomAttributesAreAvailable() { runTest(null, "joy", Arrays.asList("KingFisher", "Bira")); } @Test public void ensureCustomAttributesCanBeAlteredViaAnnotationTransformer() { runTest(new CustomAttributesTransformer(), "sorrow", Arrays.asList("Coffee", "Tea")); } private static void runTest(IAnnotationTransformer transformer, String key, List values) { TestNG testng = create(TestClassSample.class); CustomAttributesListener listener = new CustomAttributesListener(); testng.addListener(listener); if (transformer != null) { testng.addListener(transformer); } testng.run(); List attributes = listener.getAttributes(); assertThat(attributes).hasSize(1); CustomAttribute attribute = attributes.get(0); assertThat(attribute.name()).isEqualTo(key); assertThat(attribute.values()).containsAll(values); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/custom/CustomAttributesListener.java000066400000000000000000000013301475274123300321620ustar00rootroot00000000000000package test.custom; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.CustomAttribute; import org.testng.collections.Lists; public class CustomAttributesListener implements IInvokedMethodListener { private final List attributes = Lists.newArrayList(); @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { this.attributes.addAll(Arrays.asList(method.getTestMethod().getAttributes())); } public List getAttributes() { return Collections.unmodifiableList(attributes); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/custom/CustomAttributesTransformer.java000066400000000000000000000022161475274123300327030ustar00rootroot00000000000000package test.custom; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.CustomAttribute; import org.testng.annotations.ITestAnnotation; public class CustomAttributesTransformer implements IAnnotationTransformer { @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { CustomAttribute[] attributes = new CustomAttribute[] {new MoreAttribute("sorrow", new String[] {"Coffee", "Tea"})}; annotation.setAttributes(attributes); } public static class MoreAttribute implements CustomAttribute { private final String key; private final String[] values; public MoreAttribute(String key, String... values) { this.key = key; this.values = values; } @Override public String name() { return key; } @Override public String[] values() { return values; } @Override public Class annotationType() { return CustomAttribute.class; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/custom/TestClassSample.java000066400000000000000000000004621475274123300302070ustar00rootroot00000000000000package test.custom; import org.testng.annotations.CustomAttribute; import org.testng.annotations.Test; public class TestClassSample { @Test( attributes = { @CustomAttribute( name = "joy", values = {"KingFisher", "Bira"}) }) public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cyclic/000077500000000000000000000000001475274123300242275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cyclic/AbstractGenericTests.java000066400000000000000000000003341475274123300311550ustar00rootroot00000000000000package test.cyclic; import org.testng.annotations.Test; public abstract class AbstractGenericTests extends BaseIntegrationTest { @Test(groups = "integration") public final void testSomething() { // ... } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cyclic/BaseIntegrationTest.java000066400000000000000000000004641475274123300310140ustar00rootroot00000000000000package test.cyclic; import org.testng.annotations.BeforeClass; public abstract class BaseIntegrationTest { @BeforeClass(groups = "integration") protected void initIntegrationTesting() { // ... } @BeforeClass(groups = "integration") void executeBeforeClassDbOperations() { // ... } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cyclic/HibernateConcreteTests.java000066400000000000000000000003241475274123300315000ustar00rootroot00000000000000package test.cyclic; import org.testng.annotations.Test; public class HibernateConcreteTests extends AbstractGenericTests { @Test(groups = "integration") public void testSomethingElse() { // ... } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/cyclic/SomeConcreteTests.java000066400000000000000000000003171475274123300305040ustar00rootroot00000000000000package test.cyclic; import org.testng.annotations.Test; public class SomeConcreteTests extends AbstractGenericTests { @Test(groups = "integration") public void testSomethingElse() { // ... } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/000077500000000000000000000000001475274123300254455ustar00rootroot00000000000000AnnotatedInheritedDataProviderBaseSample.java000066400000000000000000000002611475274123300362430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.Test; @Test(dataProviderClass = InheritedDataProvider.class) public class AnnotatedInheritedDataProviderBaseSample {} AnnotatedInheritedDataProviderSample.java000066400000000000000000000003431475274123300354510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.Test; public class AnnotatedInheritedDataProviderSample extends AnnotatedInheritedDataProviderBaseSample { @Test(dataProvider = "dp") public void f(String a) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/BooleanDataProviderSample.java000066400000000000000000000005701475274123300333400ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class BooleanDataProviderSample { @Test(dataProvider = "allBooleans") public void doStuff(boolean t) {} @DataProvider(name = "allBooleans") public Object[][] createData() { return new Object[][] {new Object[] {true}, new Object[] {false}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/ClassDataProviderSample.java000066400000000000000000000005411475274123300330240ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(dataProvider = "dp") public class ClassDataProviderSample { @DataProvider public Object[][] dp() { return new Object[][] {new Object[] {"a"}, new Object[] {"b"}}; } public void f(String a) {} public void g(String a) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/ClassSample.java000066400000000000000000000014071475274123300305210ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ClassSample { String s; @Factory(dataProvider = "dp1") public ClassSample(String s) { this.s = s; } @DataProvider(name = "dp1") public static Object[][] createData1(Class clazz) { Assert.assertEquals(clazz, ClassSample.class); return new Object[][] {{"0"}, {"1"}}; } @Test public void test1() {} @DataProvider(name = "dp2") public Object[][] createData2(Class clazz) { Assert.assertEquals(clazz, ClassSample.class); return new Object[][] {{"Cedric" + s}, {"Alois" + s}}; } @Test(dataProvider = "dp2") public void test2(String s) {} } ConfigurationAndDataProvidersSample.java000066400000000000000000000026521475274123300353220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Make sure that all before methods except beforeTestMethod are invoked before DataProvider. */ public class ConfigurationAndDataProvidersSample { private boolean m_beforeSuite = false; private boolean m_beforeTest = false; private boolean m_beforeClass = false; private boolean m_beforeTestMethod = false; @DataProvider(name = "test1") public Object[][] createData() { Assert.assertTrue(m_beforeSuite, "beforeSuite should have been invoked"); Assert.assertTrue(m_beforeTest, "beforeTest should have been invoked"); Assert.assertTrue(m_beforeClass, "beforeClass should have been invoked"); Assert.assertFalse(m_beforeTestMethod, "beforeMethod should not have been invoked"); return new Object[][] {{"Test"}}; } @Test(dataProvider = "test1") public void verifyNames(Object p) { // do nothing } @BeforeSuite public void setUpSuite() { m_beforeSuite = true; } @BeforeTest public void setUpTest() { m_beforeTest = true; } @BeforeClass public void setUpClass() { m_beforeClass = true; } @BeforeMethod public void setUp() { m_beforeTestMethod = true; } } ConstructorInjectionProvider.java000066400000000000000000000006651475274123300341430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import com.google.inject.Inject; import com.google.inject.name.Named; import org.testng.annotations.DataProvider; public class ConstructorInjectionProvider { private final String value; @Inject public ConstructorInjectionProvider(@Named("test") String value) { this.value = value; } @DataProvider(name = "injection") public Object[][] create() { return new Object[][] {{value}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/ConstructorOrMethodSample.java000066400000000000000000000027361475274123300334510ustar00rootroot00000000000000package test.dataprovider; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.internal.ConstructorOrMethod; public class ConstructorOrMethodSample { String s; @Factory(dataProvider = "dp1") public ConstructorOrMethodSample(String s) { this.s = s; } @DataProvider(name = "dp1") public static Object[][] createData1(ConstructorOrMethod cOrM) { Assert.assertEquals(cOrM.getDeclaringClass(), ConstructorOrMethodSample.class); Assert.assertNull(cOrM.getMethod()); Assert.assertNotNull(cOrM.getConstructor()); Constructor c = cOrM.getConstructor(); Assert.assertNotNull(c.getAnnotation(Factory.class)); Assert.assertEquals(c.getParameterTypes().length, 1); Assert.assertEquals(c.getParameterTypes()[0], String.class); return new Object[][] {{"0"}, {"1"}}; } @Test public void test1() {} @DataProvider(name = "dp2") public Object[][] createData2(ConstructorOrMethod cOrM) { Assert.assertEquals(cOrM.getDeclaringClass(), ConstructorOrMethodSample.class); Assert.assertNotNull(cOrM.getMethod()); Assert.assertNull(cOrM.getConstructor()); Method m = cOrM.getMethod(); Assert.assertEquals(m.getName(), "test2"); return new Object[][] {{"Cedric" + s}, {"Alois" + s}}; } @Test(dataProvider = "dp2") public void test2(String s) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/ConstructorSample.java000066400000000000000000000016301475274123300317770ustar00rootroot00000000000000package test.dataprovider; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ConstructorSample { public static List all = new ArrayList<>(2); private final String s; @Factory(dataProvider = "dp") public ConstructorSample(String s) { this.s = s; } @DataProvider(name = "dp") public static Object[][] createData(Constructor c) { Assert.assertEquals(c.getDeclaringClass(), ConstructorSample.class); Assert.assertNotNull(c.getAnnotation(Factory.class)); Assert.assertEquals(c.getParameterTypes().length, 1); Assert.assertEquals(c.getParameterTypes()[0], String.class); return new Object[][] {{"Cedric"}, {"Alois"}}; } @Test public void test() { all.add(s); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/CreateDataTest.java000066400000000000000000000007151475274123300311500ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class CreateDataTest { @DataProvider(name = "create-data") public Object[][] create() { return new Object[][] {{new MyObject()}}; } @Test(dataProvider = "create-data") public void testMyTest(MyObject o) { // do something with o } } class MyObject { @Override public String toString() { return "MyObject{}"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/DataProviderAsTestSample.java000066400000000000000000000005621475274123300331650ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Test that if a class @Test is used, the @DataProvider method won't be considered as a test. */ @Test public class DataProviderAsTestSample { public void f() {} @DataProvider public Object[][] dataProvider() { throw new RuntimeException(); } } DataProviderIntegrationSample.java000066400000000000000000000007461475274123300341720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderIntegrationSample { @DataProvider public Object[][] testInts() { return new Object[][] {new Object[] {4}, new Object[] {8}, new Object[] {12}}; } @Test(dataProvider = "testInts", expectedExceptions = IllegalArgumentException.class) public void theTest(String aString) { Assert.assertNotNull(aString); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/DataProviderRetryAnalyzer.java000066400000000000000000000006061475274123300334320ustar00rootroot00000000000000package test.dataprovider; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class DataProviderRetryAnalyzer implements IRetryAnalyzer { private int currentTry = 0; private int maxreruntimes = 1; @Override public boolean retry(ITestResult result) { if (currentTry < maxreruntimes) { ++currentTry; return true; } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/DataProviderRetryTest.java000066400000000000000000000012461475274123300325650ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderRetryTest { @Test(dataProvider = "getVerdic", retryAnalyzer = DataProviderRetryAnalyzer.class) public void test(String verdict) { switch (verdict) { case "FAIL": Assert.fail("This time test FAIL!"); break; case "SKIP": throw new SkipException("This time test SKIPPED!"); default: break; } } @DataProvider(name = "getVerdic") public Object[][] getVerdicNames() { return new Object[][] {{"FAIL"}, {"SKIP"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/DataProviderTest.java000066400000000000000000000342761475274123300315500ustar00rootroot00000000000000package test.dataprovider; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.assertj.core.api.Condition; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.internal.reflect.MethodMatcherException; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.dataprovider.issue1691.DataProviderDefinitionAtClassLevelAndNoTestMethodUsage; import test.dataprovider.issue1691.DataProviderDefinitionCompletelyProvidedAtClassLevel; import test.dataprovider.issue1691.DataProviderDefinitionCompletelyProvidedAtClassLevelAndPartiallyAtMethodLevel; import test.dataprovider.issue1691.DataProviderDefinitionProvidedPartiallyAtClassLevel; import test.dataprovider.issue1691.withinheritance.ChildClassHasFullDefinitionOfDataProviderAtClassLevel; import test.dataprovider.issue1691.withinheritance.ChildClassHasPartialDefinitionOfDataProviderAtClassLevel; import test.dataprovider.issue1691.withinheritance.ChildClassWithNoDataProviderInformationInTestMethod; import test.dataprovider.issue2565.Data; import test.dataprovider.issue2565.SampleTestUsingConsumer; import test.dataprovider.issue2565.SampleTestUsingFunction; import test.dataprovider.issue2565.SampleTestUsingPredicate; import test.dataprovider.issue2565.SampleTestUsingSupplier; public class DataProviderTest extends SimpleBaseTest { @Test(description = "GITHUB-1691") public void testDataProviderInfoIgnored() { InvokedMethodNameListener listener = run(DataProviderDefinitionAtClassLevelAndNoTestMethodUsage.class); assertThat(listener.getSucceedMethodNames()) .containsExactly( "verifyHangoutPlaces(Hakuna Matata,Bangalore)", "verifyHangoutPlaces(Gem Inn,Chennai)"); Throwable throwable = listener.getResult("regularTestMethod").getThrowable(); assertThat(throwable).isInstanceOf(MethodMatcherException.class); } @Test(description = "GITHUB-1691", dataProvider = "getClasses") public void testDataProviderWhenProvidedAtClassLevel(Class cls) { InvokedMethodNameListener listener = run(cls); assertThat(listener.getSucceedMethodNames()) .containsExactly( "verifyHangoutPlaces(Hakuna Matata,Bangalore)", "verifyHangoutPlaces(Gem Inn,Chennai)"); } @DataProvider public Object[][] getClasses() { return new Object[][] { // No inheritance involved {DataProviderDefinitionProvidedPartiallyAtClassLevel.class}, {DataProviderDefinitionCompletelyProvidedAtClassLevel.class}, {DataProviderDefinitionCompletelyProvidedAtClassLevelAndPartiallyAtMethodLevel.class}, // Involves Inheritance {ChildClassHasPartialDefinitionOfDataProviderAtClassLevel.class}, {ChildClassHasFullDefinitionOfDataProviderAtClassLevel.class}, {ChildClassWithNoDataProviderInformationInTestMethod.class}, }; } @Test(description = "GITHUB-1139") public void oneDimDataProviderShouldWork() { InvokedMethodNameListener listener = run(OneDimDataProviderSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly( "testArray(foo)", "testArray(bar)", "testIterator(foo)", "testIterator(bar)", "testStaticArray(foo)", "testStaticArray(bar)", "testStaticIterator(foo)", "testStaticIterator(bar)"); } @Test public void booleanTest() { InvokedMethodNameListener listener = run(BooleanDataProviderSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("doStuff(true)", "doStuff(false)"); } @Test public void classTest() { InvokedMethodNameListener listener = run(ClassDataProviderSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("f(a)", "f(b)", "g(a)", "g(b)"); } @Test public void configurationAndDataProvidersTest() { InvokedMethodNameListener listener = run(ConfigurationAndDataProvidersSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly("setUpSuite", "setUpTest", "setUpClass", "setUp", "verifyNames(Test)"); } @Test public void dataProviderAsTest() { InvokedMethodNameListener listener = run(DataProviderAsTestSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("f"); } @Test public void emptyDataProviderTest() { InvokedMethodNameListener listener = run(EmptyDataProviderSample.class); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).isEmpty(); } @Test(description = "TESTNG-576: Prefer DataProvider explicit name") public void should_prefer_dataProvider_explicit_name() { InvokedMethodNameListener listener = run(ExplicitDataProviderNameSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly("should_find_exactly_one_data_provider(true)"); } /** * Make sure that if a test method fails in the middle of a data provider, the rest of the data * set is still run. */ @Test public void allMethodsShouldBeInvoked() { InvokedMethodNameListener listener = run(FailedDataProviderSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("f(1)", "f(3)"); assertThat(listener.getFailedMethodNames()).containsExactly("f(2)"); } @Test public void failedDataProviderShouldCauseSkip() { InvokedMethodNameListener listener = run(DependentSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("method1(ok)"); assertThat(listener.getSkippedMethodNames()).containsExactly("method2"); assertThat(listener.getFailedMethodNames()).containsExactly("method1(not ok)"); } @Test public void inheritedDataProviderTest() { InvokedMethodNameListener listener = run(AnnotatedInheritedDataProviderSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("f(a)"); } @Test public void instanceDataProviderTest() { InvokedMethodNameListener listener = run(InstanceDataProviderSampleFactory.class); assertThat(listener.getSucceedMethodNames()) .hasSize(2) .are(new RegexCondition("f\\(-?\\d+\\)")); } @Test(enabled = false, description = "java 1.4 tests no more supported") public void jdk4IteratorTest() { TestNG tng = create(Jdk14IteratorSample.class); // tng.setAnnotationFinder(new JDK14AnnotationFinder()); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()) .containsExactly("verifyNames(Cedric,36)", "verifyNames(Anne Marie,37)"); } @Test public void methodTest() { MethodSample.m_test2 = 0; MethodSample.m_test3 = 0; InvokedMethodNameListener listener = run(MethodSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly("test1(Cedric)", "test1(Alois)", "test2(Cedric)", "test3(Cedric)"); Assert.assertEquals(MethodSample.m_test2, 1); Assert.assertEquals(MethodSample.m_test3, 1); } @Test public void constructorTest() { ConstructorSample.all = new ArrayList<>(2); InvokedMethodNameListener listener = run(ConstructorSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("test", "test"); assertThat(ConstructorSample.all).containsExactlyInAnyOrder("Cedric", "Alois"); } @Test public void constructorOrMethodTest() { InvokedMethodNameListener listener = run(ConstructorOrMethodSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactlyInAnyOrder( "test1", "test1", "test2(Cedric1)", "test2(Alois1)", "test2(Cedric0)", "test2(Alois0)"); } @Test public void classInjectionTest() { InvokedMethodNameListener listener = run(ClassSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactlyInAnyOrder( "test1", "test1", "test2(Cedric1)", "test2(Alois1)", "test2(Cedric0)", "test2(Alois0)"); } @Test public void iTestNGMethodTest() { InvokedMethodNameListener listener = run(ITestNGMethodSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("test1(Cedric)", "test1(Alois)"); } @Test public void shouldNotThrowConcurrentModificationException() { InvokedMethodNameListener listener = run(ParallelDataProvider2Sample.class); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .are(new RegexCondition("checkCME\\(\\d+\\)|null", true)); // TODO null is not an expected value // .hasSize(2_000); TODO it is supposed to work } @Test(description = "GITHUB-2565", dataProvider = "2565") public void testForFunctionalInterfacesInLazyLoadingDataProviders( Class cls, List expected) { Data.INSTANCE.clear(); run(cls); List actualList = Data.INSTANCE.getData(); assertThat(actualList).isEqualTo(expected); } @DataProvider(name = "2565") public Object[][] getTestDataFor2565() { return new Object[][] { {SampleTestUsingSupplier.class, Arrays.asList("Optimus_Prime", "Megatron")}, {SampleTestUsingPredicate.class, Collections.singletonList("IronHide")}, {SampleTestUsingFunction.class, Collections.singletonList("Bumble_Bee")}, {SampleTestUsingConsumer.class, Collections.singletonList("StarScream")} }; } public static class RegexCondition extends Condition { private final String regex; private final boolean acceptNull; public RegexCondition(String regex) { this(regex, false); } public RegexCondition(String regex, boolean acceptNull) { this.regex = regex; this.acceptNull = acceptNull; } @Override public boolean matches(String value) { if (value == null) { if (acceptNull) { value = "null"; } else { return false; } } return value.matches(regex); } } @Test public void parallelDataProviderSample() { InvokedMethodNameListener listener = run(ParallelDataProviderSample.class); assertThat(listener.getSucceedMethodNames()) .hasSize(4) .are( new RegexCondition( "verifyData1\\(org\\.testng\\.TestRunner@\\p{XDigit}+,(" + "Cedric,36" + "|" + "Anne,37" + "|" + "A,36" + "|" + "B,37" + ")\\)")); } @Test public void staticDataProviderTest() { InvokedMethodNameListener listener = run(StaticDataProviderSampleSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly( "verifyConstructorInjection(Cedric)", "verifyExternal(Cedric)", "verifyFieldInjection(Cedric)", "verifyStatic(Cedric)"); } @Test public void staticDataProviderSampleWithoutGuiceTest() { InvokedMethodNameListener listener = run(StaticDataProviderSampleWithoutGuiceSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly("verifyExternal(Cedric)", "verifyStatic(Cedric)"); } @Test public void testInstanceFactoryTest() { TestInstanceSample.m_instanceCount = 0; InvokedMethodNameListener listener = run(TestInstanceFactory.class); assertThat(TestInstanceSample.m_instanceCount).isEqualTo(2); assertThat(listener.getSucceedMethodNames()) .containsExactly( "f(42)", "f(43)", "f(42)", "f(43)"); } @Test public void testNG411Test() { InvokedMethodNameListener listener = run(TestNG411Sample.class); assertThat(listener.getSucceedMethodNames()) .hasSize(1) .are( new RegexCondition( "checkMinTest_injection\\(1,2,org\\.testng\\.TestRunner@\\p{XDigit}+\\)")); assertThat(listener.getFailedBeforeInvocationMethodNames()) .containsExactly("checkMaxTest", "checkMinTest"); } @Test public void unnamedDataProviderTest() { InvokedMethodNameListener listener = run(UnnamedDataProviderSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("doStuff(true)", "doStuff(false)"); } @Test public void varArgsDataProviderTest() { InvokedMethodNameListener listener = run(VarArgsDataProviderSample.class); assertThat(listener.getSucceedMethodNames()) .containsExactly("testWithTwoEntriesInTestToolWindow([a,b,c])"); } @Test public void createDataTest() { InvokedMethodNameListener listener = run(CreateDataTest.class); assertThat(listener.getSucceedMethodNames()).containsExactly("testMyTest(MyObject{})"); } @Test public void testExceptions() { InvokedMethodNameListener listener = run(DataProviderIntegrationSample.class); Throwable exception = listener.getResult("theTest").getThrowable(); assertThat(exception).isInstanceOf(MethodMatcherException.class); } @Test public void mixedVarArgsDataProviderTest() { InvokedMethodNameListener listener = run(GitHub513Sample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("test(a,b,[c,d])"); } @Test(description = "GITHUB1509") public void testDataProvidersThatReturnNull() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(Github1509TestClassSample.class); tng.addListener(tla); tng.run(); assertThat(tla.getFailedTests()).size().isEqualTo(1); ITestResult result = tla.getFailedTests().get(0); String className = Github1509TestClassSample.class.getName() + ".getData()"; String msg = "Data Provider public java.lang.Object[][] " + className + " returned a null value"; assertThat(result.getThrowable().getMessage()).contains(msg); } @Test public void retryWithDataProvider() { TestNG testng = create(DataProviderRetryTest.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertThat(tla.getFailedTests()).size().isEqualTo(1); assertThat(tla.getSkippedTests()).size().isEqualTo(2); } } DataProviderWithErrorSample.java000066400000000000000000000010551475274123300336260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderWithErrorSample { @Test(dataProvider = "Data", invocationCount = 2) public void testShouldSkip() { Assert.fail(); } @Test(dataProvider = "Data", invocationCount = 2, successPercentage = 10) public void testShouldSkipEvenIfSuccessPercentage() { Assert.fail(); } @DataProvider(name = "Data") public static Object[][] Data() { throw new RuntimeException("Fail"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/DependentSample.java000066400000000000000000000010131475274123300313530ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DependentSample { @DataProvider(name = "data") public Object[][] dp() { return new Object[][] {{"ok"}, {"not ok"}}; } @Test( groups = {"a"}, dataProvider = "data") public void method1(String s) { if (!"ok".equals(s)) { throw new RuntimeException("error " + s); } } @Test( groups = {"b"}, dependsOnGroups = {"a"}) public void method2() {} } DuplicateDataProviderSample.java000066400000000000000000000006261475274123300336160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DuplicateDataProviderSample { @Test(dataProvider = "duplicate") public void f() {} @DataProvider(name = "duplicate") public Object[][] dp1() { return new Object[0][]; } @DataProvider(name = "duplicate") public Object[][] dp2() { return new Object[0][]; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/EmptyDataProviderSample.java000066400000000000000000000011021475274123300330470ustar00rootroot00000000000000package test.dataprovider; import java.util.Collections; import java.util.Iterator; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class EmptyDataProviderSample { @DataProvider public Object[][] dp1() { return new Object[0][]; } @Test(dataProvider = "dp1") public void test1() { Assert.fail(); } @DataProvider(indices = {2}) public Iterator dp2() { return Collections.emptyIterator(); } @Test(dataProvider = "dp2") public void test2() { Assert.fail(); } } ExplicitDataProviderNameSample.java000066400000000000000000000007511475274123300342650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ExplicitDataProviderNameSample { @Test(dataProvider = "dp_name") public void should_find_exactly_one_data_provider(boolean b) {} @DataProvider(name = "dp_name") Object[][] whatever_implicit_name() { return new Object[][] {{true}}; } @DataProvider(name = "whatever_explicit_name") Object[][] dp_name() { return new Object[][] {{false}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/FailedDataProviderSample.java000066400000000000000000000005621475274123300331460ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class FailedDataProviderSample { @DataProvider public Object[][] dp() { return new Integer[][] {{1}, {2}, {3}}; } @Test(dataProvider = "dp") public void f(int n) { if (n == 2) { throw new RuntimeException("Failed"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/FailingDataProviderSample.java000066400000000000000000000007071475274123300333340ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class FailingDataProviderSample { @DataProvider public Object[][] throwsExpectedException() { throw new RuntimeException("expected exception from @DP"); } @Test(dataProvider = "throwsExpectedException") public void dpThrowingException() { Assert.fail("Method should never get invoked"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/FailingDataProviderTest.java000066400000000000000000000035061475274123300330320ustar00rootroot00000000000000package test.dataprovider; import static org.assertj.core.api.Assertions.assertThat; import org.testng.DataProviderInvocationException; import org.testng.ITestResult; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.dataprovider.issue2157.TestClassWithDataProviderThatThrowsExceptions; public class FailingDataProviderTest extends SimpleBaseTest { @Test(description = "TESTNG-142: Exceptions in DataProvider are not reported as failed test") public void failingDataProvider() { InvokedMethodNameListener listener = run(FailingDataProviderSample.class); assertThat(listener.getSkippedMethodNames()).containsExactly("dpThrowingException"); } @Test(description = "TESTNG-447: Abort when two data providers have the same name") public void duplicateDataProviders() { InvokedMethodNameListener listener = run(DuplicateDataProviderSample.class); assertThat(listener.getFailedBeforeInvocationMethodNames()).containsExactly("f"); } @Test public void failingDataProviderAndInvocationCount() { InvokedMethodNameListener listener = run(DataProviderWithErrorSample.class); assertThat(listener.getSkippedMethodNames()) .containsExactly( "testShouldSkip", "testShouldSkip", "testShouldSkipEvenIfSuccessPercentage", "testShouldSkipEvenIfSuccessPercentage"); } @Test(description = "GITHUB-2157") public void abortWhenDataProviderThrowsException() { InvokedMethodNameListener listener = run(TestClassWithDataProviderThatThrowsExceptions.class); ITestResult result = listener.getResult("testMethod"); Throwable cause = result.getThrowable(); assertThat(cause).isInstanceOf(DataProviderInvocationException.class); assertThat(result.getStatus()).isEqualTo(ITestResult.FAILURE); } } FailingIterableDataProvider.java000066400000000000000000000014101475274123300335530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import java.util.Iterator; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class FailingIterableDataProvider { @DataProvider(name = "dp") public Iterator createData() { return new Iterator() { int count = 0; @Override public boolean hasNext() { return count < 10; } @Override public Object[] next() { if (++count == 6) { throw new RuntimeException(); } return new Object[] {count}; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }; } @Test(dataProvider = "dp") public void happyTest(int count) { // pass } } FailingIterableDataProviderTest.java000066400000000000000000000032031475274123300344150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; /** * TESTNG-291: Exceptions thrown by Iterable DataProviders are not caught, no failed test reported */ public class FailingIterableDataProviderTest extends SimpleBaseTest { @Test public void failingDataProvider() { InvokedMethodNameListener listener = run(FailingIterableDataProvider.class); assertThat(listener.getFailedBeforeInvocationMethodNames()).containsExactly("happyTest"); assertThat(listener.getSucceedMethodNames()) .containsExactly( "happyTest(1)", "happyTest(2)", "happyTest(3)", "happyTest(4)", "happyTest(5)"); } @Test public void failingDataProviderWithInvocationNumber() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); XmlClass xmlClass = createXmlClass(xmlTest, FailingIterableDataProvider.class); createXmlInclude(xmlClass, "happyTest", /* index */ 0, /* list */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); TestNG tng = create(xmlSuite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedBeforeInvocationMethodNames()).containsExactly("happyTest"); assertThat(listener.getSucceedMethodNames()) .containsExactly( "happyTest(1)", "happyTest(2)", "happyTest(3)", "happyTest(4)", "happyTest(5)"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/FieldInjectionProvider.java000066400000000000000000000005301475274123300327070ustar00rootroot00000000000000package test.dataprovider; import com.google.inject.Inject; import com.google.inject.name.Named; import org.testng.annotations.DataProvider; public class FieldInjectionProvider { @Inject @Named("test") private String value; @DataProvider(name = "injection") public Object[][] create() { return new Object[][] {{value}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/GitHub513Sample.java000066400000000000000000000011361475274123300310660ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class GitHub513Sample { @DataProvider public static Object[][] testData() { return new Object[][] {new Object[] {"a", "b", "c", "d"}}; } @Test(dataProvider = "testData") public void test(String fixedArg1, Object fixedArg2, String... args) { Assert.assertEquals(fixedArg1, "a"); Assert.assertEquals(fixedArg2, "b"); Assert.assertEquals(args.length, 2); Assert.assertEquals(args[0], "c"); Assert.assertEquals(args[1], "d"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/Github1509TestClassSample.java000066400000000000000000000005401475274123300330400ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Github1509TestClassSample { @Test(dataProvider = "dp") public void demo(int i) { Assert.assertTrue(i > 0); } @DataProvider(name = "dp") public Object[][] getData() { return null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/ITestNGMethodSample.java000066400000000000000000000011451475274123300320710ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.ITestNGMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ITestNGMethodSample { @DataProvider(name = "dp1") public Object[][] createData(ITestNGMethod m) { Assert.assertEquals(m.getMethodName(), "test1"); Assert.assertEquals(m.getConstructorOrMethod().getMethod().getName(), "test1"); Assert.assertEquals(m.getRealClass(), ITestNGMethodSample.class); return new Object[][] {{"Cedric"}, {"Alois"}}; } @Test(dataProvider = "dp1") public void test1(String s) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/IndicesFactorySample.java000066400000000000000000000016251475274123300323640ustar00rootroot00000000000000package test.dataprovider; import java.lang.reflect.Method; import org.testng.ITest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test public class IndicesFactorySample implements ITest { private final int value; private String testName; @Factory(dataProvider = "dp", indices = 1) public IndicesFactorySample(int value) { this.value = value; } @DataProvider(indices = {1, 2}) public static Object[][] dp() { return new Object[][] {new Object[] {1}, new Object[] {2}, new Object[] {3}, new Object[] {4}}; } @BeforeMethod public void setUp(Method method) { testName = method.getName().replace("test", "testName"); } public void testA() {} public void testB() {} @Override public String getTestName() { return testName + "(" + value + ")"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/IndicesSample.java000066400000000000000000000014761475274123300310400ustar00rootroot00000000000000package test.dataprovider; import java.util.Arrays; import java.util.Iterator; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class IndicesSample { @DataProvider(indices = {2}) public Object[][] dp1() { return new Object[][] {{1}, {2}, {3}}; } @Test(dataProvider = "dp1") public void indicesShouldWork(int n) { if (n == 2) { throw new RuntimeException("This method should not have received a 2"); } } @DataProvider(indices = {2}) public Iterator dp2() { return Arrays.asList(new Object[] {1}, new Object[] {2}, new Object[] {3}).iterator(); } @Test(dataProvider = "dp2") public void indicesShouldWorkWithIterator(int n) { if (n == 2) { throw new RuntimeException("This method should not have received a 2"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/IndicesTest.java000066400000000000000000000046411475274123300305330ustar00rootroot00000000000000package test.dataprovider; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class IndicesTest extends SimpleBaseTest { @Test public void test() { InvokedMethodNameListener listener = run(IndicesSample.class); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .containsExactly("indicesShouldWork(3)", "indicesShouldWorkWithIterator(3)"); } @Test public void test2() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); XmlClass xmlClass = createXmlClass(xmlTest, IndicesSample.class); createXmlInclude(xmlClass, "indicesShouldWork", /* index*/ 0, /* list */ 0); createXmlInclude(xmlClass, "indicesShouldWorkWithIterator", /* index*/ 0, /* list */ 0); TestNG tng = create(xmlSuite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .containsExactly( "indicesShouldWork(1)", "indicesShouldWork(3)", "indicesShouldWorkWithIterator(1)", "indicesShouldWorkWithIterator(3)"); } @Test public void testIndicesFactory() { InvokedMethodNameListener listener = run(true, IndicesFactorySample.class); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .containsExactly("testNameA(3)#testA", "testNameB(3)#testB"); } @Test(enabled = false, description = "KO https://github.com/cbeust/testng/issues/1253") public void testIndicesFactory2() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); XmlClass xmlClass = createXmlClass(xmlTest, IndicesFactorySample.class); createXmlInclude(xmlClass, "testNameA", 0, 0); TestNG tng = create(xmlSuite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).containsExactly("testNameA(3)#testA"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/InheritedDataProvider.java000066400000000000000000000003121475274123300325240ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; public class InheritedDataProvider { @DataProvider public static Object[][] dp() { return new Object[][] {{"a"}}; } } InheritedDataProviderSample.java000066400000000000000000000003071475274123300336130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.Test; public class InheritedDataProviderSample extends InheritedDataProvider { @Test(dataProvider = "dp") public void f(String s) {} } InnexistentDataProviderSample.java000066400000000000000000000002761475274123300342150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.Test; public class InnexistentDataProviderSample { @Test(dataProvider = "doesnotexist") public void testMethod(String s) {} } InstanceDataProviderSample.java000066400000000000000000000006051475274123300334450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class InstanceDataProviderSample { @DataProvider public Object[][] dp() { return new Object[][] {{hashCode()}}; } @Test(dataProvider = "dp") public void f(Integer n) { Assert.assertEquals(n, Integer.valueOf(hashCode())); } } InstanceDataProviderSampleFactory.java000066400000000000000000000004021475274123300347700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.Factory; public class InstanceDataProviderSampleFactory { @Factory public Object[] create() { return new Object[] {new InstanceDataProviderSample(), new InstanceDataProviderSample()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/InterceptorTest.java000066400000000000000000000057111475274123300314520ustar00rootroot00000000000000package test.dataprovider; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.util.Collections; import org.testng.IDataProviderInterceptor; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.reporters.Files; import test.SimpleBaseTest; import test.TestHelper; import test.dataprovider.issue2111.CountingListener; import test.dataprovider.issue2111.LocalDataProviderInterceptor; import test.dataprovider.issue2111.TestClassExample; import test.dataprovider.issue2111.TestClassExamplePoweredByFactory; import test.dataprovider.issue2111.TestClassExamplePoweredByFactoryUsingListener; import test.dataprovider.issue2111.TestClassSampleUsingListener; public class InterceptorTest extends SimpleBaseTest { @Test(dataProvider = "dp") public void ensureInterceptorIsInvokedForDataDriverPoweredTests( Class testclass, IDataProviderInterceptor interceptor) { TestNG testng = create(testclass); if (interceptor != null) { testng.addListener(interceptor); } CountingListener counter = new CountingListener(); testng.addListener(counter); testng.run(); assertThat(counter.getResults()).hasSize(1); } @DataProvider(name = "dp") public Object[][] getTestData() { return new Object[][] { {TestClassExample.class, new LocalDataProviderInterceptor()}, {TestClassSampleUsingListener.class, null}, {TestClassExamplePoweredByFactory.class, new LocalDataProviderInterceptor()}, {TestClassExamplePoweredByFactoryUsingListener.class, null} }; } @Test(dataProvider = "dp1") public void ensureInterceptorIsInvokedViaListenersTag(Class testClass) throws IOException { String xml = TestHelper.SUITE_XML_HEADER + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + ""; xml = String.format(xml, testClass.getName()); File suiteFile = File.createTempFile("testng", ".xml"); Files.writeFile(xml, suiteFile); TestNG testng = create(); testng.setTestSuites(Collections.singletonList(suiteFile.getAbsolutePath())); CountingListener counter = new CountingListener(); testng.addListener(counter); testng.run(); assertThat(counter.getResults()).hasSize(1); } @DataProvider(name = "dp1") public Object[][] getTestClasses() { return new Object[][] { {TestClassExample.class}, {TestClassExamplePoweredByFactory.class}, }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/Jdk14IteratorSample.java000066400000000000000000000004741475274123300320460ustar00rootroot00000000000000package test.dataprovider; import java.util.Arrays; import java.util.Iterator; public class Jdk14IteratorSample { public Iterator createData() { return Arrays.asList(new Object[] {"Cedric", 36}, new Object[] {"Anne Marie", 37}).iterator(); } public void verifyNames(String firstName, Integer age) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/MethodSample.java000066400000000000000000000021601475274123300306710ustar00rootroot00000000000000package test.dataprovider; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class MethodSample { @DataProvider(name = "dp1") public Object[][] createData(Method m) { Assert.assertEquals(m.getName(), "test1"); Assert.assertEquals(m.getDeclaringClass(), MethodSample.class); return new Object[][] {{"Cedric"}, {"Alois"}}; } @Test(dataProvider = "dp1") public void test1(String s) {} public static int m_test2 = 0; public static int m_test3 = 0; @DataProvider(name = "dp2") public Object[][] createData2(Method m) { switch (m.getName()) { case "test2": m_test2++; break; case "test3": m_test3++; break; default: throw new RuntimeException("Received method " + m + ", expected test2 or test3"); } Assert.assertEquals(m.getDeclaringClass(), MethodSample.class); return new Object[][] {{"Cedric"}}; } @Test(dataProvider = "dp2") public void test2(String s) {} @Test(dataProvider = "dp2") public void test3(String s) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/NonStaticProvider.java000066400000000000000000000003331475274123300317240ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; public class NonStaticProvider { @DataProvider(name = "external") public Object[][] create() { return new Object[][] {{"Cedric"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/OneDimDataProviderSample.java000066400000000000000000000021331475274123300331310ustar00rootroot00000000000000package test.dataprovider; import java.util.Arrays; import java.util.Iterator; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class OneDimDataProviderSample { @DataProvider public static Object[] staticArray() { return new Object[] {"foo", "bar"}; } @Test(dataProvider = "staticArray") public void testStaticArray(String s) { Assert.assertNotNull(s); } @DataProvider public Object[] array() { return new Object[] {"foo", "bar"}; } @Test(dataProvider = "array") public void testArray(String s) { Assert.assertNotNull(s); } @DataProvider public static Iterator staticIterator() { return Arrays.asList("foo", "bar").iterator(); } @Test(dataProvider = "staticIterator") public void testStaticIterator(String s) { Assert.assertNotNull(s); } @DataProvider public Iterator iterator() { return Arrays.asList("foo", "bar").iterator(); } @Test(dataProvider = "iterator") public void testIterator(String s) { Assert.assertNotNull(s); } } ParallelDataProvider2Sample.java000066400000000000000000000013071475274123300335170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Make sure this class can run without causing a ConcurrentModificationException. */ public class ParallelDataProvider2Sample { @DataProvider(parallel = true) Iterator provide() { List ret = new ArrayList<>(); for (int i = 0; i < 1000; i++) { ret.add(new Integer[] {i}); } return ret.iterator(); } @Test(dataProvider = "provide", invocationCount = 2, threadPoolSize = 2) public void checkCME(Integer i) { Assert.assertNotNull(i); } } ParallelDataProviderSample.java000066400000000000000000000011071475274123300334330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Data providers were not working properly with parallel=true */ public class ParallelDataProviderSample { @DataProvider(name = "test1", parallel = true) public Object[][] createData1() { return new Object[][] { {"Cedric", 36}, {"Anne", 37}, {"A", 36}, {"B", 37} }; } @Test(dataProvider = "test1", threadPoolSize = 5) public void verifyData1(ITestContext testContext, String n1, Integer n2) {} } RawIteratorDataProviderSample.java000066400000000000000000000013651475274123300341500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import java.util.Arrays; import java.util.Iterator; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class RawIteratorDataProviderSample { @DataProvider public static Iterator staticIterator() { return Arrays.asList(new Object[] {"foo"}, new Object[] {"bar"}).iterator(); } @Test(dataProvider = "staticIterator") public void testStaticIterator(String s) { Assert.assertNotNull(s); } @DataProvider public Iterator iterator() { return Arrays.asList(new Object[] {"foo"}, new Object[] {"bar"}).iterator(); } @Test(dataProvider = "iterator") public void testIterator(String s) { Assert.assertNotNull(s); } } StaticDataProviderSampleSample.java000066400000000000000000000020201475274123300342630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import com.google.inject.AbstractModule; import com.google.inject.name.Names; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice(modules = StaticDataProviderSampleSample.InjectionProviderModule.class) public class StaticDataProviderSampleSample { @Test(dataProvider = "static", dataProviderClass = StaticProvider.class) public void verifyStatic(String s) {} @Test(dataProvider = "external", dataProviderClass = NonStaticProvider.class) public void verifyExternal(String s) {} @Test(dataProvider = "injection", dataProviderClass = FieldInjectionProvider.class) public void verifyFieldInjection(String s) {} @Test(dataProvider = "injection", dataProviderClass = ConstructorInjectionProvider.class) public void verifyConstructorInjection(String s) {} public static class InjectionProviderModule extends AbstractModule { @Override protected void configure() { bind(String.class).annotatedWith(Names.named("test")).toInstance("Cedric"); } } } StaticDataProviderSampleWithoutGuiceSample.java000066400000000000000000000005541475274123300366360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataproviderpackage test.dataprovider; import org.testng.annotations.Test; public class StaticDataProviderSampleWithoutGuiceSample { @Test(dataProvider = "static", dataProviderClass = StaticProvider.class) public void verifyStatic(String s) {} @Test(dataProvider = "external", dataProviderClass = NonStaticProvider.class) public void verifyExternal(String s) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/StaticProvider.java000066400000000000000000000003351475274123300312530ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; public class StaticProvider { @DataProvider(name = "static") public static Object[][] create() { return new Object[][] {{"Cedric"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/TestContextSample.java000066400000000000000000000020011475274123300317270ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests that when a DataProvider is declared with an ITestContext, this parameter is correctly * passed. */ public class TestContextSample { /** @return As many parameters as the name of the included group */ @DataProvider(name = "testContext") public Object[] createContext(ITestContext ctx) { String[] groups = ctx.getIncludedGroups(); int n = groups.length > 0 ? Integer.parseInt(groups[0]) : 0; Object[] result = new Object[n]; for (int i = 0; i < n; i++) { result[i] = "foo"; } return new Object[] {result}; } @Test(dataProvider = "testContext", groups = "10") public void verifyTen(Object[] objects) { Assert.assertEquals(objects.length, 10); } @Test(dataProvider = "testContext", groups = "5") public void verifyFive(Object[] objects) { Assert.assertEquals(objects.length, 5); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/TestContextTest.java000066400000000000000000000024631475274123300314410ustar00rootroot00000000000000package test.dataprovider; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class TestContextTest extends SimpleBaseTest { @Test public void verifySix() { // Not including any group, so the two test methods should fail TestNG tng = create(TestContextSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).hasSize(2); } @DataProvider public static Object[][] dp() { return new Object[][] {{10, "verifyTen"}, {5, "verifyFive"}}; } @Test(dataProvider = "dp") public void verify(int number, String passed) { TestNG tng = create(TestContextSample.class); tng.setGroups(String.valueOf(number)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).hasSize(1); assertThat(listener.getSucceedMethodNames().get(0)) .matches(passed + "\\(\\[foo(,foo){" + (number - 1) + "}?\\]\\)"); assertThat(listener.getFailedMethodNames()).isEmpty(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/TestInstanceFactory.java000066400000000000000000000003441475274123300322450ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.Factory; public class TestInstanceFactory { @Factory public Object[] init() { return new Object[] {new TestInstanceSample(1), new TestInstanceSample(2)}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/TestInstanceSample.java000066400000000000000000000014651475274123300320640ustar00rootroot00000000000000package test.dataprovider; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.annotations.TestInstance; public class TestInstanceSample { public static int m_instanceCount = 0; private final int m_n; public TestInstanceSample() { this(0); } public TestInstanceSample(int n) { this.m_n = n; } @DataProvider public Object[][] dp(Method m, @TestInstance Object instance) { TestInstanceSample o0 = (TestInstanceSample) instance; Assert.assertTrue(o0.m_n == 1 || o0.m_n == 2); m_instanceCount++; return new Object[][] {{42}, {43}}; } @Test(dataProvider = "dp") public void f(int o) {} @Override public String toString() { return "[A n:" + m_n + "]"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/TestNG411Sample.java000066400000000000000000000027721475274123300310540ustar00rootroot00000000000000package test.dataprovider; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestNG411Sample { private static final String CHECK_MAX_DATA = "checkMaxData"; private static final String CHECK_MIN_DATA = "checkMinData"; @DataProvider(name = CHECK_MAX_DATA) public Object[][] dataProviderCheckMax() { return new Object[][] {{1, 2, 3, 3}}; } @Test( description = "Number of parameters to this test don't match the ones passed by data provider", dataProvider = CHECK_MAX_DATA) public void checkMaxTest(int nr1, int nr2, int expected) { Assert.fail("This code shouldn't be executed"); } @DataProvider(name = CHECK_MIN_DATA) public Object[][] dataProviderCheckMin() { return new Object[][] {{1, 2}}; } @Test( description = "Number of parameters to this test don't match the ones passed by data provider", dataProvider = CHECK_MIN_DATA) public void checkMinTest(int nr1, int nr2, int expected) { Assert.fail("This code shouldn't be executed"); } @Test( description = "Number of parameters to this test don't match the " + "ones passed by data provider. But an object will be injected", dataProvider = CHECK_MIN_DATA) public void checkMinTest_injection(int nr1, int nr2, ITestContext ctx) { int result = Math.min(nr1, nr2); Assert.assertEquals(result, nr1); Assert.assertNotNull(ctx); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/UnnamedDataProviderSample.java000066400000000000000000000005511475274123300333470ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class UnnamedDataProviderSample { @Test(dataProvider = "unnamedDataProvider") public void doStuff(boolean t) {} @DataProvider public Object[][] unnamedDataProvider() { return new Object[][] {{Boolean.TRUE}, {Boolean.FALSE}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/VarArgsDataProviderSample.java000066400000000000000000000005451475274123300333300ustar00rootroot00000000000000package test.dataprovider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class VarArgsDataProviderSample { @DataProvider public Object[][] data() { return new Object[][] {new String[] {"a", "b", "c"}}; } @Test(dataProvider = "data") public void testWithTwoEntriesInTestToolWindow(String... o) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue128/000077500000000000000000000000001475274123300270305ustar00rootroot00000000000000DataProviderParametersMismatchTest.java000066400000000000000000000035201475274123300365520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue128package test.dataprovider.issue128; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.internal.reflect.MethodMatcherException; import test.SimpleBaseTest; public class DataProviderParametersMismatchTest extends SimpleBaseTest { @Test public void testIfWarningsAreServed() { PrintStream currentErr = System.err; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(out); System.setErr(stream); TestNG tng = create(GitHub128Sample.class); tng.run(); String msg = new String(out.toByteArray(), StandardCharsets.UTF_8); boolean contains = msg.contains( "Missing one or more parameters that are being injected by the data provider. Please add the below arguments to the method."); Assert.assertTrue(contains, "Missing parameters warning should have triggered"); } finally { System.setErr(currentErr); System.setProperty("strictParameterMatch", "false"); } } @Test(dependsOnMethods = "testIfWarningsAreServed") public void testIfExceptionIsRaised() { try { System.setProperty("strictParameterMatch", "true"); TestNG tng = create(GitHub128Sample.class); TestListenerAdapter listener = new TestListenerAdapter(); tng.addListener(listener); tng.run(); for (ITestResult each : listener.getFailedTests()) { Assert.assertTrue(each.getThrowable() instanceof MethodMatcherException); } Assert.assertEquals(listener.getFailedTests().size(), 2); } finally { System.setProperty("strictParameterMatch", "false"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue128/GitHub128Sample.java000066400000000000000000000036721475274123300324620ustar00rootroot00000000000000package test.dataprovider.issue128; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.NoInjection; import org.testng.annotations.Test; public class GitHub128Sample { @BeforeClass public void beforeClass(ITestContext ctx) { Assert.assertNotNull(ctx); } @BeforeMethod public void beforeMethod() { // Ensuring that a no-arg configuration method doesn't trigger any errors. } @Test public void testMethod(ITestContext ctx) { Assert.assertNotNull(ctx); } @DataProvider(name = "methods") public Object[][] getMethods() throws NoSuchMethodException { return new Object[][] {new Object[] {String.class.getMethod("toString"), new Object[0]}}; } @Test(dataProvider = "methods") public void testInvokeRemote(Method param1, Object[] param2) { Assert.fail("The test is supposed to fail because the method param is not defined"); ; } @Test(dataProvider = "methods") public void testInvokeRemote2(@NoInjection Method param1, Object[] param2) { Assert.assertEquals(param1.getName(), "toString"); Assert.assertEquals(param2.length, 0); } @DataProvider(name = "methods2") public Object[][] getMethods2() throws NoSuchMethodException { return new Object[][] {new Object[] {new Object[0], String.class.getMethod("toString")}}; } @Test(dataProvider = "methods2") public void testInvokeRemoteReversed(Object[] param1, Method param2) { Assert.fail("The test is supposed to fail because the method param is not defined"); } @Test(dataProvider = "methods2") public void testInvokeRemoteReversed2(Object[] param1, @NoInjection Method param2) { Assert.assertEquals(param1.length, 0); Assert.assertEquals(param2.getName(), "toString"); } // TODO Add similar test for Before/AfterMethod } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/000077500000000000000000000000001475274123300271165ustar00rootroot00000000000000DataProviderDefinitionAtClassLevelAndNoTestMethodUsage.java000066400000000000000000000006541475274123300424550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691package test.dataprovider.issue1691; import org.testng.Assert; import org.testng.annotations.Test; @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "hangoutPlaces") public class DataProviderDefinitionAtClassLevelAndNoTestMethodUsage { public void regularTestMethod() {} public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } DataProviderDefinitionCompletelyProvidedAtClassLevel.java000066400000000000000000000006141475274123300422760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691package test.dataprovider.issue1691; import org.testng.Assert; import org.testng.annotations.Test; @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "hangoutPlaces") public class DataProviderDefinitionCompletelyProvidedAtClassLevel { @Test public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } DataProviderDefinitionCompletelyProvidedAtClassLevelAndPartiallyAtMethodLevel.java000066400000000000000000000007011475274123300472160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691package test.dataprovider.issue1691; import org.testng.Assert; import org.testng.annotations.Test; @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "busyMalls") public class DataProviderDefinitionCompletelyProvidedAtClassLevelAndPartiallyAtMethodLevel { @Test(dataProvider = "hangoutPlaces") public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } DataProviderDefinitionProvidedPartiallyAtClassLevel.java000066400000000000000000000006131475274123300421210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691package test.dataprovider.issue1691; import org.testng.Assert; import org.testng.annotations.Test; @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "hangoutPlaces") public class DataProviderDefinitionProvidedPartiallyAtClassLevel { @Test public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } SampleDataProvider.java000066400000000000000000000006671475274123300334410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691package test.dataprovider.issue1691; import org.testng.annotations.DataProvider; public class SampleDataProvider { @DataProvider public Object[][] hangoutPlaces() { return new Object[][] { {"Hakuna Matata", "Bangalore"}, {"Gem Inn", "Chennai"} }; } @DataProvider public Object[][] busyMalls() { return new Object[][] { {"Orion Mall", "Bangalore"}, {"Phoenix Mall", "Chennai"} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritance/000077500000000000000000000000001475274123300323035ustar00rootroot00000000000000BaseClassWithFullDefinitionOfDataProviderInClassLevel.java000066400000000000000000000004541475274123300454610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritancepackage test.dataprovider.issue1691.withinheritance; import org.testng.annotations.Test; import test.dataprovider.issue1691.SampleDataProvider; @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "hangoutPlaces") public class BaseClassWithFullDefinitionOfDataProviderInClassLevel {} BaseClassWithFullDefinitionOfDataProviderInTestMethod.java000066400000000000000000000007161475274123300455050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritancepackage test.dataprovider.issue1691.withinheritance; import org.testng.Assert; import org.testng.annotations.Test; import test.dataprovider.issue1691.SampleDataProvider; public class BaseClassWithFullDefinitionOfDataProviderInTestMethod { @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "hangoutPlaces") public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } BaseClassWithPartialDefinitionOfDataProviderInTestMethod.java000066400000000000000000000005541475274123300461770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritancepackage test.dataprovider.issue1691.withinheritance; import org.testng.Assert; import org.testng.annotations.Test; public class BaseClassWithPartialDefinitionOfDataProviderInTestMethod { @Test(dataProvider = "hangoutPlaces") public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } ChildClassHasFullDefinitionOfDataProviderAtClassLevel.java000066400000000000000000000005521475274123300454270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritancepackage test.dataprovider.issue1691.withinheritance; import org.testng.annotations.Test; import test.dataprovider.issue1691.SampleDataProvider; @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "busyMalls") public class ChildClassHasFullDefinitionOfDataProviderAtClassLevel extends BaseClassWithFullDefinitionOfDataProviderInTestMethod {} ChildClassHasPartialDefinitionOfDataProviderAtClassLevel.java000066400000000000000000000005241475274123300461200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritancepackage test.dataprovider.issue1691.withinheritance; import org.testng.annotations.Test; import test.dataprovider.issue1691.SampleDataProvider; @Test(dataProviderClass = SampleDataProvider.class) public class ChildClassHasPartialDefinitionOfDataProviderAtClassLevel extends BaseClassWithPartialDefinitionOfDataProviderInTestMethod {} ChildClassWithNoDataProviderInformationInTestMethod.java000066400000000000000000000005351475274123300452370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1691/withinheritancepackage test.dataprovider.issue1691.withinheritance; import org.testng.Assert; public class ChildClassWithNoDataProviderInformationInTestMethod extends BaseClassWithFullDefinitionOfDataProviderInClassLevel { public void verifyHangoutPlaces(String place, String city) { Assert.assertNotNull(place); Assert.assertNotNull(city); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987/000077500000000000000000000000001475274123300271265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987/BaseClassSample.java000066400000000000000000000003341475274123300327730ustar00rootroot00000000000000package test.dataprovider.issue1987; import org.testng.annotations.DataProvider; public class BaseClassSample { @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } DataProviderInBaseClass.java000066400000000000000000000003151475274123300343450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987package test.dataprovider.issue1987; import org.testng.annotations.Test; public class DataProviderInBaseClass extends BaseClassSample { @Test(dataProvider = "dp") public void testMethod(int i) {} } DataProviderInDifferentClass.java000066400000000000000000000003451475274123300354040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987package test.dataprovider.issue1987; import org.testng.annotations.Test; public class DataProviderInDifferentClass { @Test(dataProvider = "dp", dataProviderClass = BaseClassSample.class) public void testMethod(int i) {} } DataProviderInSameClass.java000066400000000000000000000005111475274123300343560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987package test.dataprovider.issue1987; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderInSameClass { @Test(dataProvider = "dp") public void testMethod(int i) {} @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } DataProviderTrackingListener.java000066400000000000000000000005421475274123300354700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987package test.dataprovider.issue1987; import org.testng.ITestListener; import org.testng.ITestResult; public class DataProviderTrackingListener implements ITestListener { private ITestResult result; @Override public void onTestStart(ITestResult result) { this.result = result; } public ITestResult getResult() { return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue1987/IssueTest.java000066400000000000000000000027011475274123300317210ustar00rootroot00000000000000package test.dataprovider.issue1987; import static org.assertj.core.api.Assertions.assertThat; import org.testng.IDataProviderMethod; import org.testng.ITestNGMethod; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(dataProvider = "testData", description = "GITHUB-1987") public void extractDataProviderInfoWhenDpResidesInSameClass( Class clazz, boolean performInstanceCheck, Class dataProviderClass) { TestNG testng = create(clazz); DataProviderTrackingListener listener = new DataProviderTrackingListener(); testng.addListener(listener); testng.run(); ITestNGMethod method = listener.getResult().getMethod(); IDataProviderMethod dpm = method.getDataProviderMethod(); assertThat(dpm).isNotNull(); if (performInstanceCheck) { assertThat(dpm.getInstance()).isEqualTo(method.getInstance()); } assertThat(dpm.getMethod().getName()).isEqualTo("getData"); assertThat(dpm.getInstance().getClass()).isEqualTo(dataProviderClass); } @DataProvider(name = "testData") public Object[][] getTestData() { return new Object[][] { {DataProviderInSameClass.class, true, DataProviderInSameClass.class}, {DataProviderInBaseClass.class, true, DataProviderInBaseClass.class}, {DataProviderInDifferentClass.class, false, BaseClassSample.class} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111/000077500000000000000000000000001475274123300271025ustar00rootroot00000000000000CountingListener.java000066400000000000000000000010161475274123300331600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.collections.Lists; public class CountingListener implements IInvokedMethodListener { private List results = Lists.newArrayList(); @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { results.add(testResult); } public List getResults() { return results; } } DataProviderHouse.java000066400000000000000000000003351475274123300332570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import org.testng.annotations.DataProvider; public class DataProviderHouse { @DataProvider public static Object[][] getData() { return new Object[][] {{1}, {2}, {3}}; } } LocalDataProviderInterceptor.java000066400000000000000000000014741475274123300354520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.testng.IDataProviderInterceptor; import org.testng.IDataProviderMethod; import org.testng.ITestContext; import org.testng.ITestNGMethod; public class LocalDataProviderInterceptor implements IDataProviderInterceptor { @Override public Iterator intercept( Iterator original, IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { Iterable iterable = () -> original; List list = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); list.remove(0); list.remove(1); return list.iterator(); } } TestClassExample.java000066400000000000000000000003321475274123300331050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import org.testng.annotations.Test; public class TestClassExample { @Test(dataProvider = "getData", dataProviderClass = DataProviderHouse.class) public void test(int i) {} } TestClassExamplePoweredByFactory.java000066400000000000000000000005141475274123300362600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class TestClassExamplePoweredByFactory { @Factory(dataProvider = "getData", dataProviderClass = DataProviderHouse.class) public TestClassExamplePoweredByFactory(int i) {} @Test public void test() {} } TestClassExamplePoweredByFactoryUsingListener.java000066400000000000000000000007001475274123300407710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import org.testng.annotations.Factory; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners({LocalDataProviderInterceptor.class}) public class TestClassExamplePoweredByFactoryUsingListener { @Factory(dataProvider = "getData", dataProviderClass = DataProviderHouse.class) public TestClassExamplePoweredByFactoryUsingListener(int i) {} @Test public void test() {} } TestClassSampleUsingListener.java000066400000000000000000000005001475274123300354440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2111package test.dataprovider.issue2111; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners({LocalDataProviderInterceptor.class}) public class TestClassSampleUsingListener { @Test(dataProvider = "getData", dataProviderClass = DataProviderHouse.class) public void test(int i) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2157/000077500000000000000000000000001475274123300271145ustar00rootroot00000000000000TestClassWithDataProviderThatThrowsExceptions.java000066400000000000000000000022341475274123300410410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2157package test.dataprovider.issue2157; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestClassWithDataProviderThatThrowsExceptions { @Test(dataProvider = "dp", retryAnalyzer = SimplyRetry.class) public void testMethod(String i) { if ("First".equalsIgnoreCase(i) || "Second".equalsIgnoreCase(i)) { Assert.fail(); } } private static AtomicInteger counter = new AtomicInteger(); @DataProvider(name = "dp") public static Object[][] dpWithException() { return new Object[][] { {foo()}, }; } private static String foo() { counter.getAndIncrement(); if (counter.get() == 1) { return "First"; } if (counter.get() == 2) { return "Second"; } throw new RuntimeException("TestNG doesn't handle an exception"); } public static class SimplyRetry implements IRetryAnalyzer { private static int attempts = 1; @Override public boolean retry(ITestResult result) { return attempts++ != 3; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue217/000077500000000000000000000000001475274123300270275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue217/IssueTest.java000066400000000000000000000007471475274123300316320ustar00rootroot00000000000000package test.dataprovider.issue217; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-217", expectedExceptions = TestNGException.class) public void ensureTestNGThrowsExceptionWhenAllTestsAreSkipped() { TestNG testng = create(SampleTestCase.class); testng.toggleFailureIfAllTestsWereSkipped(true); testng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue217/SampleTestCase.java000066400000000000000000000006041475274123300325470ustar00rootroot00000000000000package test.dataprovider.issue217; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestCase { public static final String DP_NAME = "dataProvider"; @DataProvider(name = DP_NAME) public static Object[][] getData() { throw new IllegalStateException("guess me!"); } @Test(dataProvider = DP_NAME) public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2255/000077500000000000000000000000001475274123300271135ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2255/IssueTest.java000066400000000000000000000006651475274123300317150ustar00rootroot00000000000000package test.dataprovider.issue2255; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2255") public void runTest() { TestNG testNG = create(SampleTestCase.class); testNG.run(); assertThat(SampleTestCase.data).containsExactly(100, 200); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2255/SampleTestCase.java000066400000000000000000000023741475274123300326410ustar00rootroot00000000000000package test.dataprovider.issue2255; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; public class SampleTestCase extends SimpleBaseTest { static final List data = new ArrayList<>(); private static final AtomicInteger counter = new AtomicInteger(0); @BeforeMethod public void beforeMethod(ITestResult result) { Object[] parameters = result.getParameters(); if (parameters == null || parameters.length == 0) { throw new IllegalStateException("parameters aren't visible"); } data.add((Integer) parameters[0]); } @Test(dataProvider = "dp") public void testMethod(int i) { int index = counter.getAndIncrement(); assertThat(i).isEqualTo(data.get(index)); Integer value = (Integer) Reporter.getCurrentTestResult().getParameters()[0]; assertThat(value).isEqualTo(data.get(index)); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{100}, {200}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2267/000077500000000000000000000000001475274123300271165ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2267/CustomListener.java000066400000000000000000000014461475274123300327460ustar00rootroot00000000000000package test.dataprovider.issue2267; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.internal.annotations.DisabledRetryAnalyzer; import test.dataprovider.DataProviderRetryAnalyzer; public class CustomListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isTestMethod()) { final IRetryAnalyzer currentRetryAnalyzer = method.getTestMethod().getRetryAnalyzer(testResult); if (currentRetryAnalyzer == null || currentRetryAnalyzer instanceof DisabledRetryAnalyzer) { method.getTestMethod().setRetryAnalyzerClass(DataProviderRetryAnalyzer.class); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2267/IssueTest.java000066400000000000000000000011501475274123300317060ustar00rootroot00000000000000package test.dataprovider.issue2267; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2267") public void runTest() { TestNG testng = create(SampleTestCase.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertThat(tla.getFailedTests()).size().isEqualTo(1); assertThat(tla.getSkippedTests()).size().isEqualTo(1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2267/SampleTestCase.java000066400000000000000000000011001475274123300326260ustar00rootroot00000000000000package test.dataprovider.issue2267; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.SimpleBaseTest; @Listeners(CustomListener.class) public class SampleTestCase extends SimpleBaseTest { @DataProvider(name = "dp") public Object[][] dp() { return new Object[][] { {1}, }; } @Test(dataProvider = "dp") public void testWithRetryAndDataProvider(int testNumber) { Assert.fail("This time test FAIL! with testNumber: " + testNumber); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2327/000077500000000000000000000000001475274123300271135ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2327/IssueTest.java000066400000000000000000000013151475274123300317060ustar00rootroot00000000000000package test.dataprovider.issue2327; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2327") public void runTest() { TestNG testng = create(SampleTestCase.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertThat(tla.getSkippedTests().size()).isEqualTo(2); for (ITestResult skippedTest : tla.getSkippedTests()) { assertThat(skippedTest.getParameters()).isNotEmpty(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2327/SampleTestCase.java000066400000000000000000000013161475274123300326340ustar00rootroot00000000000000package test.dataprovider.issue2327; import java.lang.reflect.Method; import java.util.Iterator; import java.util.LinkedList; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestCase { @BeforeMethod(alwaysRun = true) public void setup(Method method, Object[] params) { throw new RuntimeException("setup fail."); } @DataProvider(name = "dp", parallel = true) public Iterator dp() { LinkedList objects = new LinkedList<>(); objects.add("Dataset1"); objects.add("Dataset2"); return objects.iterator(); } @Test(dataProvider = "dp") public void test(String dataset) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2504/000077500000000000000000000000001475274123300271105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2504/IssueTest.java000066400000000000000000000016071475274123300317070ustar00rootroot00000000000000package test.dataprovider.issue2504; import java.util.Arrays; import java.util.Collections; import org.assertj.core.api.Assertions; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2504") public void ensureParametersCopiedOnConfigFailures() { XmlTest xmltest = createXmlTest("2504_suite", "2504_test"); xmltest.setXmlClasses(Collections.singletonList(new XmlClass(SampleTestCase.class))); TestNG testNG = create(Collections.singletonList(xmltest.getSuite())); SampleTestCaseListener listener = new SampleTestCaseListener(); testNG.addListener(listener); testNG.run(); Assertions.assertThat(listener.getParameters()) .containsExactlyElementsOf(Arrays.asList(1, 2, 3, 4, 5)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2504/SampleTestCase.java000066400000000000000000000011241475274123300326260ustar00rootroot00000000000000package test.dataprovider.issue2504; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestCase { @DataProvider public Object[][] data() { return new Object[][] { new Object[] {1}, new Object[] {2}, new Object[] {3}, new Object[] {4}, new Object[] {5} }; } @BeforeMethod public void myBeforeMethod() { throw new RuntimeException("my exception"); } @Test(dataProvider = "data") void testSuccess(int i) { Assert.assertTrue(true); } } SampleTestCaseListener.java000066400000000000000000000011621475274123300342570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2504package test.dataprovider.issue2504; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.ITestListener; import org.testng.ITestResult; public class SampleTestCaseListener implements ITestListener { private final List parameters = new ArrayList<>(); @Override public void onTestStart(ITestResult result) { parameters.addAll( Arrays.stream(result.getParameters()) .mapToInt(each -> (int) each) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll)); } public List getParameters() { return parameters; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2565/000077500000000000000000000000001475274123300271175ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2565/Data.java000066400000000000000000000005331475274123300306340ustar00rootroot00000000000000package test.dataprovider.issue2565; import java.util.ArrayList; import java.util.List; public enum Data { INSTANCE; private final List data = new ArrayList<>(); public void addDatum(String datum) { data.add(datum); } public List getData() { return data; } public void clear() { data.clear(); } } SampleTestUsingConsumer.java000066400000000000000000000011111475274123300345000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2565package test.dataprovider.issue2565; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestUsingConsumer { @Test(dataProvider = "dp") public void testMethod(Consumer data) { data.accept("StarScream"); } @DataProvider(name = "dp") public Iterator> data() { List> obj = new ArrayList<>(); obj.add(Data.INSTANCE::addDatum); return obj.iterator(); } } SampleTestUsingFunction.java000066400000000000000000000013261475274123300345020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2565package test.dataprovider.issue2565; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.function.Function; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestUsingFunction { @Test(dataProvider = "dp") public void testMethod(Function data) { data.apply("Bumble_Bee"); } @DataProvider(name = "dp") public Iterator> data() { List> obj = new ArrayList<>(); obj.add( text -> { Data.INSTANCE.addDatum(text); return text.toUpperCase(Locale.ROOT); }); return obj.iterator(); } } SampleTestUsingPredicate.java000066400000000000000000000012161475274123300346130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2565package test.dataprovider.issue2565; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestUsingPredicate { @Test(dataProvider = "dp") public void testMethod(Predicate data) { data.test("IronHide"); } @DataProvider(name = "dp") public Iterator> data() { List> obj = new ArrayList<>(); obj.add( text -> { Data.INSTANCE.addDatum(text); return true; }); return obj.iterator(); } } SampleTestUsingSupplier.java000066400000000000000000000011571475274123300345220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dataprovider/issue2565package test.dataprovider.issue2565; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Supplier; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestUsingSupplier { @Test(dataProvider = "dp") public void testMethod(Supplier data) { Data.INSTANCE.addDatum(data.get()); } @DataProvider(name = "dp") public Iterator> data() { List> obj = new ArrayList<>(); obj.add(() -> "Optimus_Prime"); obj.add(() -> "Megatron"); return obj.iterator(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/defaultmethods/000077500000000000000000000000001475274123300257715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/defaultmethods/DefaultMethodTest.java000066400000000000000000000063151475274123300322260ustar00rootroot00000000000000package test.defaultmethods; import org.testng.Assert; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; import test.listeners.TestAndClassListener; public class DefaultMethodTest extends SimpleBaseTest { @DataProvider public Object[][] classes() { return new Object[][] { new Object[] {TestA.class}, new Object[] {TestB.class}, new Object[] {TestC.class} }; } @Test( description = "Test default methods defined in an interface should be run", dataProvider = "classes") public void testDefaultShouldRun(Class clazz) { ITestClass testClass = runTestWithDefaultMethods(clazz); ITestNGMethod[] testMethods = testClass.getTestMethods(); Assert.assertEquals(testMethods.length, 1); Assert.assertEquals(testMethods[0].getMethodName(), "defaultMethodTest"); } @Test( description = "Before class default methods defined in an interface should be run", dataProvider = "classes") public void beforeClassDefaultShouldRun(Class clazz) { ITestClass testClass = runTestWithDefaultMethods(clazz); ITestNGMethod[] beforeClassMethods = testClass.getBeforeClassMethods(); Assert.assertEquals(beforeClassMethods.length, 1); Assert.assertEquals(beforeClassMethods[0].getMethodName(), "beforeClassRun"); } @Test( description = "After class default methods defined in an interface should be run", dataProvider = "classes") public void afterClassDefaultShouldRun(Class clazz) { ITestClass testClass = runTestWithDefaultMethods(clazz); ITestNGMethod[] afterClassMethods = testClass.getAfterClassMethods(); Assert.assertEquals(afterClassMethods.length, 1); Assert.assertEquals(afterClassMethods[0].getMethodName(), "afterClassRun"); } @Test( description = "Before method default methods defined in an interface should be run", dataProvider = "classes") public void beforeMethodDefaultShouldRun(Class clazz) { final ITestClass testClass = runTestWithDefaultMethods(clazz); ITestNGMethod[] beforeMethods = testClass.getBeforeTestMethods(); Assert.assertEquals(beforeMethods.length, 1); Assert.assertEquals(beforeMethods[0].getMethodName(), "beforeMethodRun"); } @Test( description = "After method default methods defined in an interface should be run", dataProvider = "classes") public void afterMethodDefaultShouldRun(Class clazz) { final ITestClass testClass = runTestWithDefaultMethods(clazz); ITestNGMethod[] afterMethods = testClass.getAfterTestMethods(); Assert.assertEquals(afterMethods.length, 1); Assert.assertEquals(afterMethods[0].getMethodName(), "afterMethodRun"); } private ITestClass runTestWithDefaultMethods(Class clazz) { TestNG tng = create(clazz); TestClassListener listener = new TestClassListener(); tng.addListener(listener); tng.run(); return listener.testClass; } public static class TestClassListener extends TestAndClassListener { private ITestClass testClass; @Override public void onBeforeClass(ITestClass testClass) { this.testClass = testClass; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/defaultmethods/InterfaceA.java000066400000000000000000000010121475274123300306270ustar00rootroot00000000000000package test.defaultmethods; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public interface InterfaceA { @Test default void defaultMethodTest() {} @BeforeClass default void beforeClassRun() {} @AfterClass default void afterClassRun() {} @BeforeMethod default void beforeMethodRun() {} @AfterMethod default void afterMethodRun() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/defaultmethods/TestA.java000066400000000000000000000001121475274123300276460ustar00rootroot00000000000000package test.defaultmethods; public class TestA implements InterfaceA {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/defaultmethods/TestB.java000066400000000000000000000001021475274123300276460ustar00rootroot00000000000000package test.defaultmethods; public class TestB extends TestA {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/defaultmethods/TestC.java000066400000000000000000000001301475274123300276500ustar00rootroot00000000000000package test.defaultmethods; public class TestC extends TestA implements InterfaceA {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/000077500000000000000000000000001475274123300247275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/BaseOrderMethodTest.java000066400000000000000000000017011475274123300314400ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; /** * This class * * @author Cedric Beust, Aug 20, 2004 */ public class BaseOrderMethodTest { protected boolean[] m_group1 = {false, false}; protected boolean[] m_group2 = {false, false}; protected boolean[] m_group3 = {false}; @Test( groups = {"2.0"}, dependsOnGroups = {"1.0", "1.1"}) public void a_second0() { verifyGroup(2, m_group1); m_group2[0] = true; } @Test( groups = {"3"}, dependsOnGroups = {"2.0", "2.1"}) public void third0() { verifyGroup(3, m_group2); m_group3[0] = true; } protected void verifyGroup(int groupNumber, boolean[] group) { for (int i = 0; i < group.length; i++) { assert group[i] : "Error while running group " + groupNumber + ": " + " index " + i + " of previous group should have been run before."; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/C1.java000066400000000000000000000003171475274123300260360ustar00rootroot00000000000000package test.dependent; import static org.testng.Assert.fail; import org.testng.annotations.Test; @Test(groups = "group1") public class C1 { public void failingTest() { fail("always fails"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/C2.java000066400000000000000000000005041475274123300260350ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; @Test( groups = {"group2"}, dependsOnGroups = {"group1"}) public class C2 { public void shouldBeSkipped() { // the expectation is that this test will be SKIPPED because // a test in group1 failed and we have a dependsOnGroups={"group1"} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/ClassDependsOnGroups.java000066400000000000000000000016151475274123300316420ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; import test.BaseTest; public class ClassDependsOnGroups extends BaseTest { @Test public void verifyDependsOnGroups() { addClass(test.dependent.DifferentClassDependsOnGroupsTest1.class.getName()); addClass(test.dependent.DifferentClassDependsOnGroupsTest2.class.getName()); run(); String[] failed = {"test0"}; String[] skipped = {"test1", "test2"}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyGroupsAcrossClasses() { addClass(test.dependent.C1.class.getName()); addClass(test.dependent.C2.class.getName()); run(); String[] failed = {"failingTest"}; String[] skipped = {"shouldBeSkipped"}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/ClassWide1Test.java000066400000000000000000000005311475274123300303700ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class ClassWide1Test { private static boolean m_ok = false; @BeforeTest public void init() { m_ok = false; } @Test public void m1() { m_ok = true; } public static boolean m1WasRun() { return m_ok; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/ClassWide2Test.java000066400000000000000000000004051475274123300303710ustar00rootroot00000000000000package test.dependent; import org.testng.Assert; import org.testng.annotations.Test; public class ClassWide2Test { @Test(dependsOnMethods = {"test.dependent.ClassWide1Test.m1"}) public void m2() { Assert.assertTrue(ClassWide1Test.m1WasRun()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DepBugSampleTest.java000066400000000000000000000012431475274123300307420ustar00rootroot00000000000000package test.dependent; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test public class DepBugSampleTest { private static final List m_log = new ArrayList<>(); private static void log(String s) { m_log.add(s); } public static List getLog() { return m_log; } @BeforeClass public void setup() { log("setup"); } @AfterClass public void destroy() { log("destroy"); } @Test(dependsOnMethods = "send") public void get() { log("get"); } public void send() { log("send"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DepBugVerifyTest.java000066400000000000000000000006301475274123300307640ustar00rootroot00000000000000package test.dependent; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; public class DepBugVerifyTest { @Test public void verify() { List log = DepBugSampleTest.getLog(); String[] expected = new String[] {"setup", "send", "get", "destroy"}; for (int i = 0; i < log.size(); i++) { Assert.assertEquals(expected[i], log.get(i)); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DependencyFixTest.java000066400000000000000000000011531475274123300311570ustar00rootroot00000000000000package test.dependent; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; public class DependencyFixTest { @Test(dependsOnMethods = "helloWorld", ignoreMissingDependencies = true) public void dependentOnNonExistingMethod() { assertTrue(true); } @Test(dependsOnMethods = "dependentOnNonExistingMethod") public void dependentOnExistingMethod() { assertTrue(true); } @Test( groups = "selfSufficient", dependsOnGroups = "nonExistingGroup", ignoreMissingDependencies = true) public void dependentOnNonExistingGroup() { assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DependentAlwaysRunTest.java000066400000000000000000000025061475274123300322110ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; import test.BaseTest; public class DependentAlwaysRunTest extends BaseTest { @Test public void verifyDependsOnMethodsAlwaysRun() { addClass("test.dependent.DependentOnMethod1AlwaysRunSampleTest"); run(); String[] passed = {"b", "verify"}; String[] failed = {"a"}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyDependsOnGroups1AlwaysRun() { addClass("test.dependent.DependentOnGroup1AlwaysRunSampleTest"); run(); String[] passed = {"b", "verify"}; String[] failed = {"a"}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyDependsOnGroups2AlwaysRun() { addClass("test.dependent.DependentOnGroup2AlwaysRunSampleTest"); run(); String[] passed = {"a2", "b", "verify"}; String[] failed = {"a"}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } DependentOnGroup1AlwaysRunSampleTest.java000066400000000000000000000011551475274123300346660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.Assert; import org.testng.annotations.Test; /** * a will fail but b should run anyway because of alwaysRun=true * * @author cbeust */ public class DependentOnGroup1AlwaysRunSampleTest { private boolean m_ok = false; @Test(groups = {"group-a"}) public void a() { throw new RuntimeException("Voluntary failure"); } @Test( dependsOnGroups = {"group-a"}, alwaysRun = true) public void b() { m_ok = true; } @Test(dependsOnMethods = {"b"}) public void verify() { Assert.assertTrue(m_ok, "method b() should have been invoked"); } } DependentOnGroup2AlwaysRunSampleTest.java000066400000000000000000000012421475274123300346640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.Assert; import org.testng.annotations.Test; /** * a will fail but b should run anyway because of alwaysRun=true * * @author cbeust */ public class DependentOnGroup2AlwaysRunSampleTest { private boolean m_ok = false; @Test(groups = {"group-a"}) public void a() { throw new RuntimeException("Voluntary failure"); } @Test(groups = {"group-a"}) public void a2() {} @Test( dependsOnGroups = {"group-a"}, alwaysRun = true) public void b() { m_ok = true; } @Test(dependsOnMethods = {"b"}) public void verify() { Assert.assertTrue(m_ok, "method b() should have been invoked"); } } DependentOnMethod1AlwaysRunSampleTest.java000066400000000000000000000011231475274123300350050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.Assert; import org.testng.annotations.Test; /** * a will fail but b should run anyway because of alwaysRun=true * * @author cbeust */ public class DependentOnMethod1AlwaysRunSampleTest { private boolean m_ok = false; @Test public void a() { throw new RuntimeException("Voluntary failure"); } @Test( dependsOnMethods = {"a"}, alwaysRun = true) public void b() { m_ok = true; } @Test(dependsOnMethods = {"b"}) public void verify() { Assert.assertTrue(m_ok, "method b() should have been invoked"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DependentTest.java000066400000000000000000000174601475274123300303500ustar00rootroot00000000000000package test.dependent; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite.ParallelMode; import test.BaseTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.dependent.github1156.ASample; import test.dependent.github1156.BSample; import test.dependent.github1380.GitHub1380Sample; import test.dependent.github1380.GitHub1380Sample2; import test.dependent.github1380.GitHub1380Sample3; import test.dependent.github1380.GitHub1380Sample4; public class DependentTest extends BaseTest { @Test public void simpleSkip() { addClass(SampleDependent1.class.getName()); run(); String[] passed = {}; String[] failed = {"fail"}; String[] skipped = {"shouldBeSkipped"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void dependentMethods() { addClass(SampleDependentMethods.class.getName()); run(); String[] passed = {"oneA", "oneB", "secondA", "thirdA", "canBeRunAnytime"}; String[] failed = {}; String[] skipped = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void dependentMethodsWithSkip() { addClass(SampleDependentMethods4.class.getName()); run(); String[] passed = { "step1", }; String[] failed = { "step2", }; String[] skipped = {"step3"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test(expectedExceptions = {org.testng.TestNGException.class}) public void dependentMethodsWithNonExistentMethod() { addClass(SampleDependentMethods5.class.getName()); run(); String[] passed = {"step1", "step2"}; String[] failed = {}; String[] skipped = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test(expectedExceptions = org.testng.TestNGException.class) public void dependentMethodsWithCycle() { addClass(SampleDependentMethods6.class.getName()); run(); } @Test(expectedExceptions = org.testng.TestNGException.class) public void dependentGroupsWithCycle() { addClass("test.dependent.SampleDependentMethods7"); run(); } @Test public void multipleSkips() { addClass(MultipleDependentSampleTest.class.getName()); run(); String[] passed = { "init", }; String[] failed = { "fail", }; String[] skipped = {"skip1", "skip2"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void instanceDependencies() { addClass(InstanceSkipSampleTest.class.getName()); run(); verifyInstanceNames(getPassedTests(), new String[] {"f#1", "f#3", "g#1", "g#3"}); verifyInstanceNames(getFailedTests(), new String[] {"f#2"}); verifyInstanceNames(getSkippedTests(), new String[] {"g#2"}); } @Test public void dependentWithDataProvider() { TestNG tng = SimpleBaseTest.create(DependentWithDataProviderSampleTest.class); tng.setGroupByInstances(true); List log = DependentWithDataProviderSampleTest.m_log; log.clear(); tng.run(); for (int i = 0; i < 12; i += 4) { String[] s = log.get(i).split("#"); String instance = s[1]; Assert.assertEquals(log.get(i), "prepare#" + instance); Assert.assertEquals(log.get(i + 1), "test1#" + instance); Assert.assertEquals(log.get(i + 2), "test2#" + instance); Assert.assertEquals(log.get(i + 3), "clean#" + instance); } } @DataProvider public static Object[][] dp() { return new Object[][] { {new Class[] {ASample.class, BSample.class}, true}, {new Class[] {ASample.class, BSample.class}, false}, {new Class[] {BSample.class, ASample.class}, true}, {new Class[] {BSample.class, ASample.class}, false} }; } @Test(dataProvider = "dp", description = "GITHUB-1156") public void methodDependencyBetweenClassesShouldWork(Class[] classes, boolean preserveOrder) { TestNG tng = SimpleBaseTest.create(classes); tng.setPreserveOrder(preserveOrder); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("testB", "testA"); } @DataProvider public static Object[][] dp1380() { return new Object[][] { {GitHub1380Sample.class, new String[] {"testMethodA", "testMethodB", "testMethodC"}}, {GitHub1380Sample2.class, new String[] {"testMethodC", "testMethodB", "testMethodA"}}, {GitHub1380Sample3.class, new String[] {"testMethodA", "testMethodB", "testMethodC"}}, {GitHub1380Sample4.class, new String[] {"testMethodB", "testMethodA", "testMethodC"}}, }; } @Test(dataProvider = "dp1380", description = "GITHUB-1380") public void simpleCyclingDependencyShouldWorkWithoutParallelism( Class testClass, String[] runMethods) { TestNG tng = SimpleBaseTest.create(testClass); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); // When not running parallel, invoke order and succeed order are the same. assertThat(listener.getInvokedMethodNames()).containsExactly(runMethods); assertThat(listener.getSucceedMethodNames()).containsExactly(runMethods); } @DataProvider public static Object[][] dp1380Parallel() { return new Object[][] { {GitHub1380Sample.class, new String[] {"testMethodA", "testMethodB", "testMethodC"}}, { GitHub1380Sample2.class, // A dependsOn B; C can be anywhere even though B has "sleep 5 sec" // C is the first new String[] {"testMethodC", "testMethodB", "testMethodA"}, // C is the second new String[] {"testMethodB", "testMethodC", "testMethodA"}, // C is the third new String[] {"testMethodB", "testMethodA", "testMethodC"}, }, {GitHub1380Sample3.class, new String[] {"testMethodA", "testMethodB", "testMethodC"}}, { GitHub1380Sample4.class, // A dependsOn B; C can be anywhere // C is the first new String[] {"testMethodC", "testMethodB", "testMethodA"}, // C is the second new String[] {"testMethodB", "testMethodC", "testMethodA"}, // C is the third new String[] {"testMethodB", "testMethodA", "testMethodC"}, }, }; } @Test(dataProvider = "dp1380Parallel", description = "GITHUB-1380") public void simpleCyclingDependencyShouldWorkWitParallelism( Class testClass, String[]... runMethods) { TestNG tng = SimpleBaseTest.create(testClass); tng.setParallel(ParallelMode.METHODS); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getInvokedMethodNames()) .matches( strings -> { boolean result = false; for (String[] runMethod : runMethods) { result = result || Arrays.asList(runMethod).equals(strings); } return result; }, "When running parallel, invoke order is consistent, but succeed order isn't " + Arrays.deepToString(runMethods)); assertThat(listener.getSucceedMethodNames()).containsExactlyInAnyOrder(runMethods[0]); } } DependentWithDataProviderSampleTest.java000066400000000000000000000021251475274123300345640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.collections.Lists; public class DependentWithDataProviderSampleTest { public static List m_log = Lists.newArrayList(); private String param; @Factory(dataProvider = "prov") public DependentWithDataProviderSampleTest(String param) { this.param = param; } @DataProvider(name = "prov") public static Object[][] dataProvider() { return new Object[][] { {"One"}, {"Two"}, {"Three"}, }; } private void log(String s) { m_log.add(s + "#" + param); } @BeforeClass public void prepare() { log("prepare"); } @Test public void test1() { log("test1"); } @Test(dependsOnMethods = "test1") public void test2() { log("test2"); } @AfterClass public void clean() { log("clean"); } @Override public String toString() { return "[" + param + "]"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DependsOnProtectedMethodTest.java000066400000000000000000000011651475274123300333270ustar00rootroot00000000000000package test.dependent; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** This class/interface */ public class DependsOnProtectedMethodTest { private boolean m_before1 = false; private boolean m_before2 = false; @BeforeMethod(dependsOnMethods = {"before2"}) protected void before() { m_before1 = true; } @BeforeMethod protected void before2() { m_before2 = true; } @Test public void verifyBeforeInvocations() { Assert.assertTrue( m_before1 && m_before2, "Protected dependent @BeforeMethods should have been invoked"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/DepthDependencyTest.java000066400000000000000000000005411475274123300314750ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; public class DepthDependencyTest { @Test(groups = {"1"}) public void f1() { throw new RuntimeException(); } @Test( groups = {"2"}, dependsOnGroups = {"1"}) public void f2() {} @Test( groups = {"3"}, dependsOnGroups = {"2"}) public void f3() {} } DifferentClassDependsOnGroupsTest1.java000066400000000000000000000005111475274123300343250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; public class DifferentClassDependsOnGroupsTest1 { @Test(groups = {"mainGroup"}) public void test0() { assertTrue(1 == 0); // Force a failure } @Test(dependsOnGroups = {"mainGroup"}) public void test2() {} } DifferentClassDependsOnGroupsTest2.java000066400000000000000000000002641475274123300343330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.annotations.Test; public class DifferentClassDependsOnGroupsTest2 { @Test(dependsOnGroups = {"mainGroup"}) public void test1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/GitHub261AlphaSample.java000066400000000000000000000003231475274123300313130ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; public class GitHub261AlphaSample { @Test public void testAlpha1() {} @Test(dependsOnMethods = "testAlpha1") public void testAlpha2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/GitHub261BetaSample.java000066400000000000000000000004251475274123300311440ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; public class GitHub261BetaSample { @Test(dependsOnMethods = "testBeta2") public void testBeta1() {} @Test public void testBeta2() {} @Test(dependsOnMethods = "testBeta2") public void testBeta3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/GitHub261Test.java000066400000000000000000000012631475274123300300470ustar00rootroot00000000000000package test.dependent; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class GitHub261Test extends SimpleBaseTest { @Test public void testGitHub261() { TestNG tng = create(GitHub261AlphaSample.class, GitHub261BetaSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.setGroupByInstances(true); tng.run(); assertThat(listener.getInvokedMethodNames()) .containsExactly("testAlpha1", "testAlpha2", "testBeta2", "testBeta1", "testBeta3"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/GroupByInstancesSampleTest.java000066400000000000000000000020661475274123300330370ustar00rootroot00000000000000package test.dependent; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.collections.Lists; public class GroupByInstancesSampleTest { private String m_country; public static List m_log = Lists.newArrayList(); private static void log(String method, String country) { // System.out.println("LOG:" + method + "#" + country + " " + // Thread.currentThread().getId()); m_log.add(method + "#" + country); } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {"usa"}, new Object[] {"uk"}, }; } @Factory(dataProvider = "dp") public GroupByInstancesSampleTest(String country) { m_country = country; } @Test public void signIn() { log("signIn", m_country); } @Test(dependsOnMethods = "signIn") public void signOut() { log("signOut", m_country); } @Override public String toString() { return "[GroupByInstancesSampleTest: " + m_country + "]"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/GroupByInstancesTest.java000066400000000000000000000022731475274123300316750ustar00rootroot00000000000000package test.dependent; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.SimpleBaseTest; public class GroupByInstancesTest extends SimpleBaseTest { @Test public void dontGroupByInstances() { runTest(false); } @Test public void groupByInstances() { runTest(true); } private void runTest(boolean group) { TestNG tng = create(GroupByInstancesSampleTest.class); GroupByInstancesSampleTest.m_log = Lists.newArrayList(); tng.setGroupByInstances(group); tng.run(); List log = GroupByInstancesSampleTest.m_log; int i = 0; if (group) { Assert.assertTrue(log.get(i++).startsWith("signIn")); Assert.assertTrue(log.get(i++).startsWith("signOut")); Assert.assertTrue(log.get(i++).startsWith("signIn")); Assert.assertTrue(log.get(i++).startsWith("signOut")); } else { Assert.assertTrue(log.get(i++).startsWith("signIn")); Assert.assertTrue(log.get(i++).startsWith("signIn")); Assert.assertTrue(log.get(i++).startsWith("signOut")); Assert.assertTrue(log.get(i++).startsWith("signOut")); } } } ImplicitGroupInclusion2SampleTest.java000066400000000000000000000014071475274123300342540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ImplicitGroupInclusion2SampleTest { private boolean m_m1, m_m2, m_m3; @BeforeClass(groups = {"g2"}) public void init() { m_m1 = m_m2 = m_m3 = false; } @Test(groups = {"g1"}) public void m1() { m_m1 = true; } @Test( groups = {"g1"}, dependsOnMethods = "m1") public void m2() { m_m2 = true; } @Test(groups = {"g2"}) public void m3() { m_m3 = true; } @AfterClass(groups = {"g2"}) public void verify() { Assert.assertFalse(m_m1, "Shouldn't have invoked m1()"); Assert.assertFalse(m_m2); Assert.assertTrue(m_m3); } } ImplicitGroupInclusion3SampleTest.java000066400000000000000000000006311475274123300342530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.annotations.Test; public class ImplicitGroupInclusion3SampleTest { @Test(groups = {"inc"}) public void test1() {} @Test(groups = {"exc"}) public void test2() { throw new RuntimeException("exclude me"); } @Test( groups = {"exc"}, dependsOnMethods = {"test2"}) public void test3() { throw new RuntimeException("exclude me"); } } ImplicitGroupInclusion4SampleTest.java000066400000000000000000000016331475274123300342570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ImplicitGroupInclusion4SampleTest { private boolean m_m1, m_m2, m_m3, m_m4; @BeforeClass(groups = {"g2"}) public void init() { m_m1 = m_m2 = m_m3 = m_m4 = false; } @Test(groups = {"g1"}) public void m1() { m_m1 = true; } @Test( groups = {"g1"}, dependsOnMethods = "m1") public void m2() { m_m2 = true; } @Test(groups = {"g2"}) public void m3() { m_m3 = true; } @Test( groups = {"g2"}, dependsOnMethods = "m3") public void m4() { m_m4 = true; } @AfterClass(groups = {"g2"}) public void verify() { Assert.assertFalse(m_m1, "Shouldn't have invoked m1()"); Assert.assertFalse(m_m2); Assert.assertTrue(m_m3); Assert.assertTrue(m_m4); } } ImplicitGroupInclusionSampleTest.java000066400000000000000000000005001475274123300341630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.annotations.Test; public class ImplicitGroupInclusionSampleTest { @Test(groups = "z") public void z() {} @Test( groups = "a", dependsOnGroups = {"z"}) public void a() {} @Test( groups = "b", dependsOnGroups = {"a"}) public void b() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/ImplicitGroupInclusionTest.java000066400000000000000000000043231475274123300331070ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; import test.BaseTest; public class ImplicitGroupInclusionTest extends BaseTest { @Test public void verifyImplicitGroupInclusion() { addClass("test.dependent.ImplicitGroupInclusionSampleTest"); addIncludedGroup("b"); run(); String[] passed = {"a", "b", "z"}; String[] failed = {}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyImplicitGroupInclusion2() { addClass("test.dependent.ImplicitGroupInclusion2SampleTest"); addIncludedGroup("g2"); run(); String[] passed = {"m3"}; String[] failed = {}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyImplicitGroupInclusion4() { addClass("test.dependent.ImplicitGroupInclusion4SampleTest"); addIncludedGroup("g2"); run(); String[] passed = {"m3", "m4"}; String[] failed = {}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyImplicitGroupInclusion3() { addClass("test.dependent.ImplicitGroupInclusion3SampleTest"); addIncludedGroup("inc"); addExcludedGroup("exc"); run(); String[] passed = {"test1"}; String[] failed = {}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } @Test public void verifyImplicitMethodInclusion() { addClass("test.dependent.ImplicitMethodInclusionSampleTest"); addIncludedGroup("windows"); run(); String[] passed = {"a", "b"}; String[] failed = {}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } ImplicitMethodInclusionSampleTest.java000066400000000000000000000004061475274123300343140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.annotations.Test; public class ImplicitMethodInclusionSampleTest { @Test(groups = {"linux"}) public void a() {} @Test( groups = {"linux", "windows"}, dependsOnMethods = {"a"}) public void b() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/InstanceSkipSampleTest.java000066400000000000000000000021131475274123300321640ustar00rootroot00000000000000package test.dependent; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.collections.Lists; /** * Verify that only instances that fail cause dependency failures. In other words, when run, this * test should show: passed = [f#1 f#3 g#1 g#3], failed = [f#2], skipped = [g#2] * * @author Cedric Beust */ public class InstanceSkipSampleTest { private int m_n; public static List m_list = Lists.newArrayList(); @Factory(dataProvider = "dp") public InstanceSkipSampleTest(int n) { m_n = n; } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {1}, new Object[] {2}, new Object[] {3}, }; } @Test public void f() { if (m_n == 2) throw new RuntimeException(); log("f"); } @Test(dependsOnMethods = "f") public void g() { log("g"); } private void log(String s) { m_list.add(s + "#" + m_n); } @Override public String toString() { return "" + m_n; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MissingGroupSampleTest.java000066400000000000000000000017411475274123300322250ustar00rootroot00000000000000package test.dependent; import java.io.ByteArrayInputStream; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.internal.Parser; import test.TestHelper; public class MissingGroupSampleTest { @Test(dependsOnGroups = {"missing-group"}) public void shouldBeSkipped() {} @Test( dependsOnGroups = {"missing-group"}, ignoreMissingDependencies = true) public void shouldNotBeSkipped() {} public static void main(String[] args) throws Exception { TestNG tng = new TestNG(); String xml = TestHelper.SUITE_XML_HEADER + "" + "" + "" + "" + ""; System.out.println(xml); ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); tng.setXmlSuites(new Parser(is).parseToList()); tng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MissingGroupTest.java000066400000000000000000000010511475274123300310550ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; import test.BaseTest; public class MissingGroupTest extends BaseTest { @Test public void verifyThatExceptionIsThrownIfMissingGroup() { addClass("test.dependent.MissingGroupSampleTest"); run(); String[] passed = {"shouldNotBeSkipped"}; String[] failed = {}; String[] skipped = {"shouldBeSkipped"}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MissingMethodSampleTest.java000066400000000000000000000017261475274123300323540ustar00rootroot00000000000000package test.dependent; import java.io.ByteArrayInputStream; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.internal.Parser; import test.TestHelper; public class MissingMethodSampleTest { @Test(dependsOnMethods = "missingMethod", ignoreMissingDependencies = true) public void explicitlyIgnoreMissingMethod() {} @Test(dependsOnMethods = "missingMethod", alwaysRun = true) public void alwaysRunDespiteMissingMethod() {} public static void main(String[] args) throws Exception { TestNG tng = new TestNG(); String xml = TestHelper.SUITE_XML_HEADER + "" + "" + ""; System.out.println(xml); ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); tng.setXmlSuites(new Parser(is).parseToList()); tng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MissingMethodTest.java000066400000000000000000000011071475274123300312030ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; import test.BaseTest; public class MissingMethodTest extends BaseTest { @Test public void verifyThatExceptionIsThrownIfMissingMethod() { addClass("test.dependent.MissingMethodSampleTest"); run(); String[] passed = {"explicitlyIgnoreMissingMethod", "alwaysRunDespiteMissingMethod"}; String[] failed = {}; String[] skipped = {}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MultiGroup1SampleTest.java000066400000000000000000000004021475274123300317600ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; @Test(groups = {"checkin"}) public class MultiGroup1SampleTest { @Test(groups = {"a"}) public void testA() {} public void test1() throws Exception { throw new Exception("fail"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MultiGroup2SampleTest.java000066400000000000000000000003141475274123300317630ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; @Test( groups = {"integration"}, dependsOnGroups = {"checkin", "a"}) public class MultiGroup2SampleTest { public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MultiGroupTest.java000066400000000000000000000011071475274123300305400ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; import test.BaseTest; public class MultiGroupTest extends BaseTest { @Test public void verifyDependsOnMultiGroups() { addClass(MultiGroup1SampleTest.class.getName()); addClass(MultiGroup2SampleTest.class.getName()); run(); String[] passed = { "testA", }; String[] failed = {"test1"}; String[] skipped = {"test2"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); verifyTests("Skipped", skipped, getSkippedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/MultipleDependentSampleTest.java000066400000000000000000000005631475274123300332220ustar00rootroot00000000000000package test.dependent; import org.testng.Assert; import org.testng.annotations.Test; public class MultipleDependentSampleTest { @Test public void init() {} @Test(dependsOnMethods = "init") public void fail() { Assert.fail(); } @Test(dependsOnMethods = "fail") public void skip1() {} @Test(dependsOnMethods = "skip1") public void skip2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/OrderMethodTest.java000066400000000000000000000011171475274123300306460ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; /** * This class verifies that when methods have dependents, they are run in the correct order. * * @author Cedric Beust, Aug 19, 2004 */ public class OrderMethodTest extends BaseOrderMethodTest { @Test(groups = {"1.0"}) public void z_first0() { m_group1[0] = true; } @Test( groups = {"2.1"}, dependsOnGroups = {"1.0", "1.1"}) public void a_second1() { verifyGroup(2, m_group1); m_group2[1] = true; } @Test(groups = {"1.1"}) public void z_premiere1() { m_group1[1] = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SD2.java000066400000000000000000000011441475274123300261620ustar00rootroot00000000000000package test.dependent; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; public class SD2 { public static List m_log = new ArrayList<>(); @Test(groups = {"one"}) public void oneA() { m_log.add("oneA"); } @Test public void canBeRunAnytime() { m_log.add("canBeRunAnytime"); } @Test(dependsOnGroups = {"one"}) public void secondA() { m_log.add("secondA"); } @Test(dependsOnMethods = {"secondA"}) public void thirdA() { m_log.add("thirdA"); } @Test(groups = {"one"}) public void oneB() { m_log.add("oneB"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependent1.java000066400000000000000000000005611475274123300307250ustar00rootroot00000000000000package test.dependent; import org.testng.Assert; import org.testng.annotations.Test; /** * This class exercises dependent groups * * @author Cedric Beust, Aug 19, 2004 */ public class SampleDependent1 { @Test(groups = {"fail"}) public void fail() { Assert.assertTrue(false); } @Test(dependsOnGroups = {"fail"}) public void shouldBeSkipped() {} } SampleDependentConfigurationMethods.java000066400000000000000000000012041475274123300346340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependentpackage test.dependent; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SampleDependentConfigurationMethods { private boolean m_create = false; private boolean m_first = false; @BeforeMethod public void createInstance() { m_create = true; } @BeforeMethod(dependsOnMethods = {"createInstance"}) public void firstInvocation() { assert m_create : "createInstance() was never called"; m_first = true; } @Test public void verifyDependents() { assert m_create : "createInstance() was never called"; assert m_first : "firstInvocation() was never called"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentMethods.java000066400000000000000000000025461475274123300321750ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * This class exercises dependent methods * * @author Cedric Beust, Aug 19, 2004 */ public class SampleDependentMethods { private boolean m_oneA = false; private boolean m_oneB = false; private boolean m_secondA = false; private boolean m_thirdA = false; @Test public void oneA() { assert !m_secondA : "secondA shouldn't have been run yet"; m_oneA = true; } @Test public void canBeRunAnytime() {} @Test(dependsOnMethods = {"oneA", "oneB"}) public void secondA() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert !m_secondA : "secondA shouldn't have been run yet"; m_secondA = true; } @Test(dependsOnMethods = {"secondA"}) public void thirdA() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert m_secondA : "secondA wasn't run"; assert !m_thirdA : "thirdA shouldn't have been run yet"; m_thirdA = true; } @Test public void oneB() { assert !m_secondA : "secondA shouldn't have been run yet"; m_oneB = true; } @AfterClass public void tearDown() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert m_secondA : "secondA wasn't run"; assert m_thirdA : "thirdA wasn't run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentMethods2.java000066400000000000000000000026011475274123300322470ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * This class exercises dependent methods * * @author Cedric Beust, Aug 19, 2004 */ public class SampleDependentMethods2 { private boolean m_oneA = false; private boolean m_oneB = false; private boolean m_secondA = false; private boolean m_thirdA = false; @Test(groups = {"one"}) public void oneA() { assert !m_secondA : "secondA shouldn't have been run yet"; m_oneA = true; } @Test public void canBeRunAnytime() {} @Test(dependsOnGroups = {"one"}) public void secondA() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert !m_secondA : "secondA shouldn't have been run yet"; m_secondA = true; } @Test(dependsOnMethods = {"secondA"}) public void thirdA() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert m_secondA : "secondA wasn't run"; assert !m_thirdA : "thirdA shouldn't have been run yet"; m_thirdA = true; } @Test(groups = {"one"}) public void oneB() { assert !m_secondA : "secondA shouldn't have been run yet"; m_oneB = true; } @AfterClass public void tearDown() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert m_secondA : "secondA wasn't run"; assert m_thirdA : "thirdA wasn't run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentMethods3.java000066400000000000000000000021561475274123300322550ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.AfterClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * This class tests overloaded dependent methods * * @author Cedric Beust, Aug 19, 2004 */ public class SampleDependentMethods3 { private boolean m_oneA = false; private boolean m_oneB = false; private boolean m_secondA = false; @Test public void one() { assert !m_secondA : "secondA shouldn't have been run yet"; m_oneA = true; } @Parameters({"foo"}) @Test public void one(String s) { assert !m_secondA : "secondA shouldn't have been run yet"; assert "Cedric".equals(s) : "Expected parameter value Cedric but got " + s; m_oneB = true; } @Test(dependsOnMethods = {"one"}) public void secondA() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert !m_secondA : "secondA shouldn't have been run yet"; m_secondA = true; } @AfterClass public void tearDown() { assert m_oneA : "oneA wasn't run"; assert m_oneB : "oneB wasn't run"; assert m_secondA : "secondA wasn't run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentMethods4.java000066400000000000000000000005301475274123300322500ustar00rootroot00000000000000package test.dependent; import org.testng.Assert; import org.testng.annotations.Test; public class SampleDependentMethods4 { @Test public void step1() {} @Test(dependsOnMethods = {"step1"}) public void step2() { Assert.assertTrue(false, "Problem in step2"); } @Test(dependsOnMethods = {"step2"}) public void step3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentMethods5.java000066400000000000000000000003261475274123300322540ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; public class SampleDependentMethods5 { @Test public void step1() {} @Test(dependsOnMethods = {"step1", "blablabla"}) public void step2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentMethods6.java000066400000000000000000000003461475274123300322570ustar00rootroot00000000000000package test.dependent; import org.testng.annotations.Test; public class SampleDependentMethods6 { @Test(dependsOnMethods = {"step2"}) public void step1() {} @Test(dependsOnMethods = {"step1"}) public void step2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/SampleDependentTest.java000066400000000000000000000014721475274123300315060ustar00rootroot00000000000000package test.dependent; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class SampleDependentTest extends SimpleBaseTest { @Test public void test2() { TestNG tng = create(SD2.class); SD2.m_log.clear(); tng.run(); boolean oneA = false; boolean oneB = false; boolean secondA = false; for (String s : SD2.m_log) { if ("oneA".equals(s)) { oneA = true; } if ("oneB".equals(s)) { oneB = true; } if ("secondA".equals(s)) { Assert.assertTrue(oneA); Assert.assertTrue(oneB); secondA = true; } if ("thirdA".equals(s)) { Assert.assertTrue(oneA); Assert.assertTrue(oneB); Assert.assertTrue(secondA); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/Test1.java000066400000000000000000000000571475274123300265740ustar00rootroot00000000000000package test.dependent; public class Test1 {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/functionality1/000077500000000000000000000000001475274123300277005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/functionality1/Config.java000066400000000000000000000003451475274123300317520ustar00rootroot00000000000000package test.dependent.functionality1; import org.testng.annotations.BeforeSuite; public class Config { @BeforeSuite(groups = "other") public void beforeSuite() { System.out.println("BeforeSuite group 'other'"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/functionality1/Test1.java000066400000000000000000000004251475274123300315440ustar00rootroot00000000000000package test.dependent.functionality1; import org.testng.annotations.Test; @Test(groups = "tests.functional.package") public class Test1 { public void test1_1() { System.out.println("Test 1_1"); } public void test1_2() { System.out.println("Test 1_2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/functionality1/Test2.java000066400000000000000000000005021475274123300315410ustar00rootroot00000000000000package test.dependent.functionality1; import org.testng.annotations.Test; @Test(groups = "tests.functional.upload", dependsOnGroups = "tests.functional.package") public class Test2 { public void test2_1() { System.out.println("Test 2_1"); } public void test2_2() { System.out.println("Test 2_2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1156/000077500000000000000000000000001475274123300265265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1156/ASample.java000066400000000000000000000003021475274123300307060ustar00rootroot00000000000000package test.dependent.github1156; import org.testng.annotations.Test; public class ASample { @Test(dependsOnMethods = "test.dependent.github1156.BSample.testB") public void testA() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1156/BSample.java000066400000000000000000000002041475274123300307100ustar00rootroot00000000000000package test.dependent.github1156; import org.testng.annotations.Test; public class BSample { @Test public void testB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1380/000077500000000000000000000000001475274123300265255ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1380/GitHub1380Sample.java000066400000000000000000000006651475274123300322370ustar00rootroot00000000000000package test.dependent.github1380; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; public class GitHub1380Sample { @Test(priority = 1) public void testMethodA() {} @Test(dependsOnMethods = "testMethodA", priority = 2) public void testMethodB() throws InterruptedException { TimeUnit.SECONDS.sleep(1); } @Test(dependsOnMethods = "testMethodB", priority = 1) public void testMethodC() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1380/GitHub1380Sample2.java000066400000000000000000000006241475274123300323140ustar00rootroot00000000000000package test.dependent.github1380; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; public class GitHub1380Sample2 { @Test(dependsOnMethods = "testMethodB", priority = 3) public void testMethodA() {} @Test(priority = 2) public void testMethodB() throws InterruptedException { TimeUnit.SECONDS.sleep(5); } @Test(priority = 1) public void testMethodC() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1380/GitHub1380Sample3.java000066400000000000000000000006661475274123300323230ustar00rootroot00000000000000package test.dependent.github1380; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; public class GitHub1380Sample3 { @Test(priority = 2) public void testMethodA() {} @Test(dependsOnMethods = "testMethodA", priority = 1) public void testMethodB() throws InterruptedException { TimeUnit.SECONDS.sleep(1); } @Test(dependsOnMethods = "testMethodB", priority = 2) public void testMethodC() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/github1380/GitHub1380Sample4.java000066400000000000000000000006241475274123300323160ustar00rootroot00000000000000package test.dependent.github1380; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; public class GitHub1380Sample4 { @Test(dependsOnMethods = "testMethodB", priority = 1) public void testMethodA() throws InterruptedException { TimeUnit.SECONDS.sleep(1); } @Test(priority = 2) public void testMethodB() {} @Test(priority = 3) public void testMethodC() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/000077500000000000000000000000001475274123300264025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/ClassASample.java000066400000000000000000000010311475274123300315500ustar00rootroot00000000000000package test.dependent.issue1648; import java.util.List; import org.testng.annotations.Test; import org.testng.collections.Lists; public class ClassASample implements LogExtractor { private final List logs = Lists.newArrayList(); @Test protected void test1() { addLog("A TestOne 1"); } @Test(dependsOnMethods = {"test1"}) protected void test2() { addLog("A test Two"); } @Override public List getLogs() { return logs; } protected void addLog(String log) { logs.add(log); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/ClassBSample.java000066400000000000000000000004661475274123300315640ustar00rootroot00000000000000package test.dependent.issue1648; import org.testng.annotations.Test; public class ClassBSample extends ClassASample { @Test(dependsOnMethods = {"test2"}) protected void test3() { addLog("B test 1"); } @Test(dependsOnMethods = {"test3"}) protected void test4() { addLog("B test 2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/LogExtractor.java000066400000000000000000000001671475274123300316660ustar00rootroot00000000000000package test.dependent.issue1648; import java.util.List; public interface LogExtractor { List getLogs(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/TestOneSample.java000066400000000000000000000001261475274123300317670ustar00rootroot00000000000000package test.dependent.issue1648; public class TestOneSample extends ClassBSample {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/TestRunner.java000066400000000000000000000022061475274123300313560ustar00rootroot00000000000000package test.dependent.issue1648; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class TestRunner extends SimpleBaseTest { @Test(description = "GITHUB-1648") public void testMethod() { List expected = Arrays.asList( "A TestOne 1", "A test Two", "B test 1", "B test 2", "A TestOne 1", "A test Two", "B test 1", "B test 2"); TestNG tng = create(TestOneSample.class, TestTwoSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); List actual = Lists.newArrayList(); for (Object instance : listener.getTestInstances()) { if (instance instanceof LogExtractor) { actual.addAll(((LogExtractor) instance).getLogs()); } } assertThat(actual).containsExactlyElementsOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/issue1648/TestTwoSample.java000066400000000000000000000001261475274123300320170ustar00rootroot00000000000000package test.dependent.issue1648; public class TestTwoSample extends ClassBSample {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/xml/000077500000000000000000000000001475274123300255275ustar00rootroot00000000000000GroupDependencySampleTest.java000066400000000000000000000003641475274123300334130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/xmlpackage test.dependent.xml; import org.testng.annotations.Test; public class GroupDependencySampleTest { @Test(groups = "a") public void a1() {} @Test(groups = "b") public void b1() {} @Test(groups = "c") public void c1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependent/xml/GroupDependencyTest.java000066400000000000000000000042011475274123300323220ustar00rootroot00000000000000package test.dependent.xml; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class GroupDependencyTest extends SimpleBaseTest { @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {new String[] {"a", "b", "c", "a1", "b1", "c1"}}, new Object[] {new String[] {"a", "c", "b", "a1", "c1", "b1"}}, new Object[] {new String[] {"b", "a", "c", "b1", "a1", "c1"}}, new Object[] {new String[] {"b", "c", "a", "b1", "c1", "a1"}}, new Object[] {new String[] {"c", "b", "a", "c1", "b1", "a1"}}, new Object[] {new String[] {"c", "a", "b", "c1", "a1", "b1"}}, }; } @Test(dataProvider = "dp") public void verifyGroupSingle(String[] a) { configureGroup(a, false /* single */); } @Test(dataProvider = "dp") public void verifyGroupMulti(String[] a) { configureGroup(a, true /* multi */); } private void configureGroup(String[] a, boolean multi) { XmlSuite suite = createXmlSuite("Dependencies"); XmlTest test = createXmlTest(suite, "DependencyTest", GroupDependencySampleTest.class.getName()); if (multi) { test.addXmlDependencyGroup(a[2], a[1] + " " + a[0]); } else { test.addXmlDependencyGroup(a[2], a[1]); test.addXmlDependencyGroup(a[1], a[0]); } TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(suite)); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); List t = tla.getPassedTests(); String method2 = t.get(2).getMethod().getMethodName(); if (multi) { // When we have "a depends on groups b and c", the only certainty is that "a" // will be run last Assert.assertEquals(method2, a[5]); } else { assertTestResultsEqual(tla.getPassedTests(), Arrays.asList(a[3], a[4], a[5])); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/000077500000000000000000000000001475274123300260155ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/DependsOnGroupsTest.java000066400000000000000000000015521475274123300326020ustar00rootroot00000000000000package test.dependsongroup; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class DependsOnGroupsTest extends SimpleBaseTest { @Test public void methodsShouldBeGroupedByClasses() { TestNG tng = create(ZeroSampleTest.class, FirstSampleTest.class, SecondSampleTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); String[] expected = new String[] { "zeroA", "zeroB", "firstA", "firstB", "secondA", "secondB" }; for (int i = 0; i < expected.length; i++) { ITestResult testResult = tla.getPassedTests().get(i); Assert.assertEquals(testResult.getMethod().getMethodName(), expected[i]); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/FirstSampleTest.java000066400000000000000000000003511475274123300317500ustar00rootroot00000000000000package test.dependsongroup; import org.testng.annotations.Test; @Test( groups = {"first"}, dependsOnGroups = {"zero"}) public class FirstSampleTest { @Test public void firstA() {} @Test public void firstB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/SecondSampleTest.java000066400000000000000000000003551475274123300321000ustar00rootroot00000000000000package test.dependsongroup; import org.testng.annotations.Test; @Test( groups = {"second"}, dependsOnGroups = {"zero"}) public class SecondSampleTest { @Test public void secondA() {} @Test public void secondB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/TestFixture1.java000066400000000000000000000002561475274123300312320ustar00rootroot00000000000000package test.dependsongroup; import org.testng.annotations.BeforeTest; public class TestFixture1 { @BeforeTest(groups = {"test", "testgroup"}) public void setup() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/TestFixture2.java000066400000000000000000000004551475274123300312340ustar00rootroot00000000000000package test.dependsongroup; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class TestFixture2 { @BeforeTest( groups = {"test"}, dependsOnGroups = {"testgroup"}) public void setup() {} @Test(groups = {"test"}) public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/ZeroSampleTest.java000066400000000000000000000003001475274123300315720ustar00rootroot00000000000000package test.dependsongroup; import org.testng.annotations.Test; @Test(groups = {"zero"}) public class ZeroSampleTest { @Test public void zeroA() {} @Test public void zeroB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/dependsongroup/suite.xml000066400000000000000000000005171475274123300276730ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/000077500000000000000000000000001475274123300242075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/A.java000066400000000000000000000032421475274123300252330ustar00rootroot00000000000000package test.enable; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class A { public void testA() {} @Test public void testA2() {} @Test(enabled = true) public void testA3() {} @Test(enabled = false) public void disabledA() {} @BeforeSuite public void beforeSuiteA() {} @BeforeSuite(enabled = true) public void beforeSuiteA2() {} @BeforeSuite(enabled = false) public void disabledBeforeSuiteA() {} @BeforeSuite(alwaysRun = false) public void beforeSuiteNoRunA() {} @BeforeSuite(enabled = true, alwaysRun = false) public void beforeSuiteNoRunA2() {} @BeforeSuite(enabled = false, alwaysRun = false) public void disabledBeforeSuiteNoRunA() {} @BeforeSuite(alwaysRun = true) public void beforeSuiteRunA() {} @BeforeSuite(enabled = true, alwaysRun = true) public void beforeSuiteRunA2() {} @BeforeSuite(enabled = false, alwaysRun = true) public void disabledBeforeSuiteRunA() {} @AfterSuite public void afterSuiteA() {} @AfterSuite(enabled = true) public void afterSuiteA2() {} @AfterSuite(enabled = false) public void disabledAfterSuiteA() {} @AfterSuite(alwaysRun = false) public void afterSuiteNoRunA() {} @AfterSuite(enabled = true, alwaysRun = false) public void afterSuiteNoRunA2() {} @AfterSuite(enabled = false, alwaysRun = false) public void disabledAfterSuiteNoRunA() {} @AfterSuite(alwaysRun = true) public void afterSuiteRunA() {} @AfterSuite(enabled = true, alwaysRun = true) public void afterSuiteRunA2() {} @AfterSuite(enabled = false, alwaysRun = true) public void disabledAfterSuiteRunA() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/B.java000066400000000000000000000033121475274123300252320ustar00rootroot00000000000000package test.enable; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; @Test(enabled = false) public class B { public void testB() {} @Test public void testB2() {} @Test(enabled = true) public void testB3() {} @Test(enabled = false) public void disabledB() {} @BeforeSuite(enabled = true) public void disabledBeforeSuiteB() {} @BeforeSuite public void disabledBeforeSuiteB2() {} @BeforeSuite(enabled = false) public void disabledBeforeSuiteB3() {} @BeforeSuite(alwaysRun = false) public void beforeSuiteNoRunB() {} @BeforeSuite(enabled = true, alwaysRun = false) public void beforeSuiteNoRunB2() {} @BeforeSuite(enabled = false, alwaysRun = false) public void disabledBeforeSuiteNoRunB() {} @BeforeSuite(alwaysRun = true) public void beforeSuiteRunB() {} @BeforeSuite(enabled = true, alwaysRun = true) public void beforeSuiteRunB2() {} @BeforeSuite(enabled = false, alwaysRun = true) public void disabledBeforeSuiteRunB() {} @AfterSuite public void afterSuiteB() {} @AfterSuite(enabled = true) public void afterSuiteB2() {} @AfterSuite(enabled = false) public void disabledAfterSuiteB() {} @AfterSuite(alwaysRun = false) public void afterSuiteNoRunB() {} @AfterSuite(enabled = true, alwaysRun = false) public void afterSuiteNoRunB2() {} @AfterSuite(enabled = false, alwaysRun = false) public void disabledAfterSuiteNoRunB() {} @AfterSuite(alwaysRun = true) public void afterSuiteRunB() {} @AfterSuite(enabled = true, alwaysRun = true) public void afterSuiteRunB2() {} @AfterSuite(enabled = false, alwaysRun = true) public void disabledAfterSuiteRunB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/C.java000066400000000000000000000032501475274123300252340ustar00rootroot00000000000000package test.enable; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; @Test public class C { public void testC() {} @Test public void testC2() {} @Test(enabled = true) public void testC3() {} @Test(enabled = false) public void disabledC() {} @BeforeSuite public void beforeSuiteC() {} @BeforeSuite(enabled = true) public void beforeSuiteC2() {} @BeforeSuite(enabled = false) public void disabledBeforeSuiteC() {} @BeforeSuite(alwaysRun = false) public void beforeSuiteNoRunC() {} @BeforeSuite(enabled = true, alwaysRun = false) public void beforeSuiteNoRunC2() {} @BeforeSuite(enabled = false, alwaysRun = false) public void disabledBeforeSuiteNoRunC() {} @BeforeSuite(alwaysRun = true) public void beforeSuiteRunC() {} @BeforeSuite(enabled = true, alwaysRun = true) public void beforeSuiteRunC2() {} @BeforeSuite(enabled = false, alwaysRun = true) public void disabledBeforeSuiteRunC() {} @AfterSuite public void afterSuiteC() {} @AfterSuite(enabled = true) public void afterSuiteC2() {} @AfterSuite(enabled = false) public void disabledAfterSuiteC() {} @AfterSuite(alwaysRun = false) public void afterSuiteNoRunC() {} @AfterSuite(enabled = true, alwaysRun = false) public void afterSuiteNoRunC2() {} @AfterSuite(enabled = false, alwaysRun = false) public void disabledAfterSuiteNoRunC() {} @AfterSuite(alwaysRun = true) public void afterSuiteRunC() {} @AfterSuite(enabled = true, alwaysRun = true) public void afterSuiteRunC2() {} @AfterSuite(enabled = false, alwaysRun = true) public void disabledAfterSuiteRunC() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/EnableTest.java000066400000000000000000000041331475274123300271010ustar00rootroot00000000000000package test.enable; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodListener; import test.SimpleBaseTest; public class EnableTest extends SimpleBaseTest { @Test public void disabled_methods_should_not_be_run() { TestNG tng = create(A.class, B.class, C.class); InvokedMethodListener listener = new InvokedMethodListener(); tng.addListener(listener); tng.setPreserveOrder(true); tng.run(); assertThat(listener.getInvokedMethods()) .containsExactly( "beforeSuiteA", "beforeSuiteA2", "beforeSuiteNoRunA", "beforeSuiteNoRunA2", "beforeSuiteRunA", "beforeSuiteRunA2", "beforeSuiteRunB", "beforeSuiteRunB2", "beforeSuiteC", "beforeSuiteC2", "beforeSuiteNoRunC", "beforeSuiteNoRunC2", "beforeSuiteRunC", "beforeSuiteRunC2", "testA2", "testA3", "testB2", "testB3", "testC", "testC2", "testC3", "afterSuiteA", "afterSuiteA2", "afterSuiteNoRunA", "afterSuiteNoRunA2", "afterSuiteRunA", "afterSuiteRunA2", "afterSuiteRunB", "afterSuiteRunB2", "afterSuiteC", "afterSuiteC2", "afterSuiteNoRunC", "afterSuiteNoRunC2", "afterSuiteRunC", "afterSuiteRunC2"); } @Test(description = "https://github.com/cbeust/testng/issues/420") public void issue420() { TestNG tng = create(Issue420FirstSample.class, Issue420SecondSample.class); InvokedMethodListener listener = new InvokedMethodListener(); tng.addListener(listener); tng.run(); assertThat(listener.getInvokedMethods()) .containsExactly( "alwaysBeforeSuite", "beforeSuite", "verifySomethingFirstSample", "verifySomethingSecondSample", "afterSuite", "alwaysAfterSuite"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/Issue420BaseTestCase.java000066400000000000000000000007051475274123300306210ustar00rootroot00000000000000package test.enable; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public abstract class Issue420BaseTestCase { @BeforeSuite(alwaysRun = true) public static void alwaysBeforeSuite() {} @BeforeSuite(alwaysRun = false) public static void beforeSuite() {} @AfterSuite(alwaysRun = false) public static void afterSuite() {} @AfterSuite(alwaysRun = true) public static void alwaysAfterSuite() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/Issue420FirstSample.java000066400000000000000000000003131475274123300305370ustar00rootroot00000000000000package test.enable; import org.testng.annotations.Test; @Test(enabled = false) public class Issue420FirstSample extends Issue420BaseTestCase { @Test public void verifySomethingFirstSample() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/enable/Issue420SecondSample.java000066400000000000000000000002741475274123300306710ustar00rootroot00000000000000package test.enable; import org.testng.annotations.Test; @Test public class Issue420SecondSample extends Issue420BaseTestCase { @Test public void verifySomethingSecondSample() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/000077500000000000000000000000001475274123300266645ustar00rootroot00000000000000ExpectedExceptionsTest.java000066400000000000000000000026531475274123300341210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptionspackage test.expectedexceptions; import java.util.Collection; import java.util.List; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.Test; import test.BaseTest; import test.expectedexceptions.github1409.TestClassSample; public class ExpectedExceptionsTest extends BaseTest { @Test public void expectedExceptionsDeprecatedSyntax() { runTest( "test.expectedexceptions.SampleExceptions", new String[] {"shouldPass"}, new String[] {"shouldFail1", "shouldFail2", "shouldFail3"}, new String[] {}); } @Test public void expectedExceptions() { runTest( "test.expectedexceptions.SampleExceptions2", new String[] {"shouldPass", "shouldPass2", "shouldPass3", "shouldPass4"}, new String[] {"shouldFail1", "shouldFail2", "shouldFail3", "shouldFail4"}, new String[] {}); } @Test public void expectedExceptionsMessage() { getFailedTests().clear(); addClass(TestClassSample.class); run(); Collection> failedTests = getFailedTests().values(); Assert.assertFalse(failedTests.isEmpty()); ITestResult result = failedTests.iterator().next().get(0); String actual = result.getThrowable().getMessage().replaceAll("\\n", ""); String expected = "The exception was thrown with the wrong message: expected \"expected\" but got \"actual\""; Assert.assertEquals(actual, expected); } } ParametersExceptionTest.java000066400000000000000000000012621475274123300342730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptionspackage test.expectedexceptions; import java.io.IOException; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.xml.sax.SAXException; /** This class/interface */ public class ParametersExceptionTest { @Test(dataProvider = "A") public void testA(Exception err) { System.out.println("testA"); } @DataProvider(name = "A") protected Object[][] dp() { return new Object[][] {{new IOException(), new SAXException()}}; } @AfterMethod protected void verify(Method method) { Assert.assertTrue(false, "forced failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/SampleExceptions.java000066400000000000000000000011451475274123300330130ustar00rootroot00000000000000package test.expectedexceptions; import org.testng.annotations.Test; /** * This class tests @ExpectedExceptions * * @author cbeust */ public class SampleExceptions { @Test(expectedExceptions = {NumberFormatException.class}) public void shouldPass() { throw new NumberFormatException(); } @Test(expectedExceptions = {NumberFormatException.class}) public void shouldFail1() { throw new RuntimeException(); } @Test(expectedExceptions = {NumberFormatException.class}) public void shouldFail2() {} @Test(expectedExceptions = RuntimeException.class) public void shouldFail3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/SampleExceptions2.java000066400000000000000000000026371475274123300331040ustar00rootroot00000000000000package test.expectedexceptions; import org.testng.annotations.Test; /** * This class tests @ExpectedExceptions * * @author cbeust */ public class SampleExceptions2 { @Test(expectedExceptions = NumberFormatException.class) public void shouldPass() { throw new NumberFormatException(); } @Test(expectedExceptions = NumberFormatException.class) public void shouldFail1() { throw new RuntimeException(); } @Test(expectedExceptions = NumberFormatException.class) public void shouldFail2() {} @Test( expectedExceptions = NumberFormatException.class, expectedExceptionsMessageRegExp = ".*bomb.*") public void shouldPass2() { throw new NumberFormatException("This should not bomb at all"); } @Test( expectedExceptions = NumberFormatException.class, expectedExceptionsMessageRegExp = ".*bombc.*") public void shouldFail3() { throw new NumberFormatException("This should bomb for good"); } @Test(expectedExceptions = NumberFormatException.class, expectedExceptionsMessageRegExp = ".*") public void shouldPass3() { throw new NumberFormatException(null); } @Test( expectedExceptions = NumberFormatException.class, expectedExceptionsMessageRegExp = "Multiline.*") public void shouldPass4() { throw new NumberFormatException("Multiline\nException"); } @Test(expectedExceptions = RuntimeException.class) public void shouldFail4() {} } WrappedExpectedExceptionTest.java000066400000000000000000000004521475274123300352540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptionspackage test.expectedexceptions; import org.testng.annotations.Test; public class WrappedExpectedExceptionTest { @Test( timeOut = 1000L, expectedExceptions = {IllegalStateException.class}) public void testTimeout() { throw new IllegalStateException("expected failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/github1409/000077500000000000000000000000001475274123300304645ustar00rootroot00000000000000TestClassSample.java000066400000000000000000000004331475274123300343170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/github1409package test.expectedexceptions.github1409; import org.testng.annotations.Test; public class TestClassSample { @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "expected") public void test() { throw new RuntimeException("actual"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/issue2074/000077500000000000000000000000001475274123300303315ustar00rootroot00000000000000FailingInterruptTest.java000066400000000000000000000011121475274123300352360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/issue2074package test.expectedexceptions.issue2074; import static org.testng.Assert.fail; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; public class FailingInterruptTest { @Test(expectedExceptions = RuntimeException.class, timeOut = 1000) public void shouldntInterruptTheThreadButDoesTest() { throw new RuntimeException("unit test exception"); } @AfterMethod public void checkForInterrupts() { if (Thread.interrupted()) { // check for interrupts and clear the flag fail("Thread was interrupted but shouldn't have been"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/issue2074/IssueTest.java000066400000000000000000000015151475274123300331260ustar00rootroot00000000000000package test.expectedexceptions.issue2074; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2074") public void testIfInterruptsAreCleared() { XmlSuite xmlSuite = createXmlSuite("my_suite", "my_test", FailingInterruptTest.class); xmlSuite.setParallel(ParallelMode.METHODS); TestNG tng = create(xmlSuite); TestListenerAdapter listener = new TestListenerAdapter(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedTests()).isEmpty(); assertThat(listener.getConfigurationFailures()).isEmpty(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/issue2235/000077500000000000000000000000001475274123300303305ustar00rootroot00000000000000ExampleTestCase.java000066400000000000000000000004201475274123300341370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/issue2235package test.expectedexceptions.issue2235; import org.testng.annotations.Test; public class ExampleTestCase { @Test(timeOut = 1000, expectedExceptions = IllegalArgumentException.class) public void testMethod() { throw new IllegalArgumentException("foo"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/expectedexceptions/issue2235/IssueTest.java000066400000000000000000000015121475274123300331220ustar00rootroot00000000000000package test.expectedexceptions.issue2235; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2235") public void testExpectedExceptions() { XmlSuite xmlSuite = createXmlSuite("main_suite", "main_test", ExampleTestCase.class); xmlSuite.setParallel(ParallelMode.METHODS); TestNG testng = create(xmlSuite); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); assertThat(listener.getPassedTests()).isNotEmpty(); assertThat(listener.getFailedTests()).isEmpty(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/000077500000000000000000000000001475274123300244305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/ArrayEmptyFactorySample.java000066400000000000000000000007071475274123300320660ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ArrayEmptyFactorySample { @DataProvider(name = "values") public static Object[][] values() { return new Object[][] {}; } @Factory(dataProvider = "values") public ArrayEmptyFactorySample(int value) {} @Test public void test() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/BadMethodReturnTypeFactory.java000066400000000000000000000003601475274123300325130ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Factory; public class BadMethodReturnTypeFactory { @Factory private Object createInstances() { return new Object[] {new BaseFactorySample(42), new BaseFactorySample(43)}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/BaseFactory.java000066400000000000000000000002741475274123300275000ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Factory; public class BaseFactory { @Factory public Object[] create() { return new Object[] {new FactoryBaseSample()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/BaseFactorySample.java000066400000000000000000000011271475274123300306400ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Test; public class BaseFactorySample { private final int n; public BaseFactorySample(int n) { this.n = n; } public int getN() { return n; } @Test public void f() {} /** * @@@ for some reason, the test results get added in the wrong order if I don't define a * toString() method. Need to investigate. https://github.com/cbeust/testng/issues/799 TODO Remove * the method when issue will be fixed */ @Override public String toString() { return "[" + getClass().getName() + " " + getN() + "]"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/ChildFactory.java000066400000000000000000000001101475274123300276360ustar00rootroot00000000000000package test.factory; public class ChildFactory extends BaseFactory {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/DisabledFactory.java000066400000000000000000000003111475274123300303250ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Factory; public class DisabledFactory { @Factory(enabled = false) public Object[] factory() { return new Object[] {new MySample()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/DisabledFactoryTest.java000066400000000000000000000011531475274123300311720ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class DisabledFactoryTest extends SimpleBaseTest { @Test public void disabledFactoryShouldNotRun() { TestNG tng = create(DisabledFactory.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 0); Assert.assertEquals(tla.getSkippedTests().size(), 0); Assert.assertEquals(tla.getFailedTests().size(), 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/DoubleFactory.java000066400000000000000000000005301475274123300300330ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Factory; public class DoubleFactory { @Factory public Object[] factory1() { return new Object[] {new FactoryBaseSample(1), new FactoryBaseSample(2)}; } @Factory public Object[] factory2() { return new Object[] {new FactoryBaseSample(3), new FactoryBaseSample(4)}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/EmptyFactoryDataProviderTest.java000066400000000000000000000012631475274123300330700ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class EmptyFactoryDataProviderTest extends SimpleBaseTest { @Test public void test() { TestNG testng = create(ArrayEmptyFactorySample.class, IteratorEmptyFactorySample.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); // Used to check the warning message testng.run(); Assert.assertTrue(tla.getFailedTests().isEmpty()); Assert.assertTrue(tla.getSkippedTests().isEmpty()); Assert.assertTrue(tla.getPassedTests().isEmpty()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/Factory2Test.java000066400000000000000000000005071475274123300276260ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Test; import test.configuration.ConfigurationBaseTest; import test.factory.sample.Factory2TestSample; public class Factory2Test extends ConfigurationBaseTest { @Test public void testFactoryCorrectlyInterleaved() { testConfiguration(Factory2TestSample.class); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryAndTestMethodTest.java000066400000000000000000000013271475274123300321710ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = {"x"}) public class FactoryAndTestMethodTest { @Factory(dataProvider = "data") public Object[] ohNo(String s) { return makeNullArgTests(s); } public static class NullArgsTest { public final String s; public NullArgsTest(String s) { this.s = s; } @Test public void test() { Assert.assertNotNull(s); } } private Object[] makeNullArgTests(String s) { return new Object[0]; } @DataProvider(name = "data") public Object[][] makeData() { return new Object[][] {{"foo"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryBaseSample.java000066400000000000000000000006311475274123300306370ustar00rootroot00000000000000package test.factory; import org.testng.ITest; import org.testng.annotations.Test; public class FactoryBaseSample implements ITest { private final int value; public FactoryBaseSample() { this(0); } public FactoryBaseSample(int value) { this.value = value; } @Test public void f() {} @Override public String getTestName() { return "FactoryBaseSample{" + value + "}"; } } FactoryDataProviderNotStaticSample.java000066400000000000000000000004461475274123300341270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factorypackage test.factory; import org.testng.annotations.Factory; public class FactoryDataProviderNotStaticSample extends BaseFactorySample { @Factory(dataProvider = "dp", dataProviderClass = NotStaticDataProvider.class) public FactoryDataProviderNotStaticSample(int n) { super(n); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryDataProviderSample.java000066400000000000000000000007271475274123300323570ustar00rootroot00000000000000package test.factory; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryDataProviderSample extends BaseFactorySample { @Factory(dataProvider = "dp") public FactoryDataProviderSample(int n) { super(n); } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {41}, new Object[] {42}, }; } @Test public void f() {} } FactoryDataProviderStaticErrorSample.java000066400000000000000000000006441475274123300344600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factorypackage test.factory; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; public class FactoryDataProviderStaticErrorSample extends BaseFactorySample { @Factory(dataProvider = "dp") public FactoryDataProviderStaticErrorSample(int n) { super(n); } @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {41}, new Object[] {42}, }; } } FactoryDataProviderStaticSample.java000066400000000000000000000004351475274123300334440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factorypackage test.factory; import org.testng.annotations.Factory; public class FactoryDataProviderStaticSample extends BaseFactorySample { @Factory(dataProvider = "dp", dataProviderClass = StaticDataProvider.class) public FactoryDataProviderStaticSample(int n) { super(n); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryDataProviderTest.java000066400000000000000000000035221475274123300320510ustar00rootroot00000000000000package test.factory; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import test.SimpleBaseTest; public class FactoryDataProviderTest extends SimpleBaseTest { @Test(description = "Test @Factory(dataProvider) on a local static data provider") public void factoryWithLocalDataProvider() { runTest(FactoryDataProviderSample.class, 41, 42); } @Test(description = "Test @Factory(dataProvider) on a data provider in another class (static)") public void factoryWithStaticDataProvider() { runTest(FactoryDataProviderStaticSample.class, 43, 44); } @Test( description = "Test @Factory(dataProvider) on a data provider in another class (not static)") public void factoryWithNotStaticDataProvider() { runTest(FactoryDataProviderNotStaticSample.class, 43, 44); } @Test(description = "Test @Factory(dataProvider) on a non static data provider with no arg ctor") public void factoryWithNonStaticDataProvider() { runTest(FactoryDataProviderWithNoArgCtorErrorSample.class, 45, 46); } @Test( expectedExceptions = TestNGException.class, description = "Should fail because the data provider is not static") public void factoryWithNonStaticDataProviderShouldFail() { runTest(FactoryDataProviderStaticErrorSample.class, 43, 44); } private static void runTest(Class cls, int n1, int n2) { TestNG tng = create(cls); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); assertThat(tla.getPassedTests()) .describedAs("arguments of passed tests: getPassedTests()") .extracting(x -> ((BaseFactorySample) x.getInstance()).getN()) .isEqualTo(Arrays.asList(n1, n2)); } } FactoryDataProviderWithNoArgCtorErrorSample.java000066400000000000000000000007761475274123300357310ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factorypackage test.factory; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; public class FactoryDataProviderWithNoArgCtorErrorSample extends BaseFactorySample { public FactoryDataProviderWithNoArgCtorErrorSample() { super(0); } @Factory(dataProvider = "dp") public FactoryDataProviderWithNoArgCtorErrorSample(int n) { super(n); } @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {45}, new Object[] {46}, }; } } FactoryFailureNoInstancesSample.java000066400000000000000000000006511475274123300334440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factorypackage test.factory; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryFailureNoInstancesSample { public static final String METHOD_NAME = FactoryFailureNoInstancesSample.class.getName() + ".factory()"; public FactoryFailureNoInstancesSample(int i) {} @Factory public static Object[] factory() { return new Object[] {}; } @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryFailureSample.java000066400000000000000000000003731475274123300313570ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryFailureSample { @Factory public Object[] factory() { throw new NullPointerException(); } @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryFailureTest.java000066400000000000000000000020451475274123300310530ustar00rootroot00000000000000package test.factory; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class FactoryFailureTest extends SimpleBaseTest { @Test public void factoryThrowingShouldNotRunTests() { TestNG tng = create(FactoryFailureSample.class); Throwable actual = new Throwable(); try { tng.run(); } catch (Exception ex) { actual = ex; } assertThat(actual.getCause()).hasCauseInstanceOf(NullPointerException.class); } @Test(description = "GITHUB-1953") public void factoryProducesNoInstancesTest() { TestNG tng = create(FactoryFailureNoInstancesSample.class); String actualErr = ""; String expected = String.format( "The Factory method %s should have produced at-least one instance.", FactoryFailureNoInstancesSample.METHOD_NAME); try { tng.run(); } catch (Exception ex) { actualErr = ex.getMessage(); } assertThat(actualErr).contains(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryInSeparateClassTest.java000066400000000000000000000020271475274123300325050ustar00rootroot00000000000000package test.factory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * this is like the FactoryTest, except it creates test instances in a separate class from the test * class */ public class FactoryInSeparateClassTest { private static boolean m_wasRun = false; private static int m_checkSum = 0; public static void addToSum(int i) { m_checkSum += i; } @BeforeTest public void beforeTest() { m_wasRun = false; m_checkSum = 0; } @Factory public Object[] createObjects() { return new Object[] { new MySample(1), new MySample(2), new MySample(3), }; } @Test( groups = "testMethodOnFactoryClass", dependsOnGroups = {"MySample"}) public void checkSum() { m_wasRun = true; assert (m_checkSum == 6) : "Test instances made by factory did not invoke their test methods correctly. expected 6 but got " + m_checkSum; } public static boolean wasRun() { return m_wasRun; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryInSuperClassTest.java000066400000000000000000000007711475274123300320430ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class FactoryInSuperClassTest extends SimpleBaseTest { @Test public void factoryInSuperClassShouldWork() { TestNG tng = create(ChildFactory.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryIntegrationTest.java000066400000000000000000000043411475274123300317500ustar00rootroot00000000000000package test.factory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class FactoryIntegrationTest extends SimpleBaseTest { @Test(description = "https://github.com/cbeust/testng/issues/876") public void testExceptionWithNonStaticFactoryMethod() { TestNG tng = create(GitHub876Sample.class); try { tng.run(); failBecauseExceptionWasNotThrown(TestNGException.class); } catch (TestNGException e) { assertThat(e) .hasMessage( "\nCan't invoke public java.lang.Object[] test.factory.GitHub876Sample.createInstances(): either make it static or add a no-args constructor to your class"); } } @Test public void testNonPublicFactoryMethodShouldWork() { TestNG tng = create(NonPublicFactory.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 2); } @Test public void testExceptionWithBadFactoryMethodReturnType() { TestNG tng = create(BadMethodReturnTypeFactory.class); try { tng.run(); failBecauseExceptionWasNotThrown(TestNGException.class); } catch (TestNGException e) { assertThat(e) .hasMessage( "\ntest.factory.BadMethodReturnTypeFactory.createInstances MUST return [ java.lang.Object[] or org.testng.IInstanceInfo[] ] but returns java.lang.Object"); } } @Test public void doubleFactoryMethodShouldWork() { TestNG tng = create(DoubleFactory.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); // TODO containsExactly is not used here because the order is not consistent. Check if we should // fix it. assertThat(listener.getSucceedMethodNames()) .contains( "FactoryBaseSample{1}#f", "FactoryBaseSample{2}#f", "FactoryBaseSample{3}#f", "FactoryBaseSample{4}#f"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryInterleavingTest.java000066400000000000000000000015451475274123300321170ustar00rootroot00000000000000package test.factory; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.SimpleBaseTest; public class FactoryInterleavingTest extends SimpleBaseTest { public static List LOG = Lists.newArrayList(); @Test public void methodsShouldBeInterleaved() { TestNG tng = create(InterleavingFactorySample.class); tng.setPreserveOrder(false); tng.run(); Integer[] valid1 = { 10, 11, 12, 13, 20, 21, 22, 23, }; Integer[] valid2 = { 20, 21, 22, 23, 10, 11, 12, 13, }; Integer[] logArray = LOG.toArray(new Integer[0]); if (!logArray.equals(valid1)) { Assert.assertEquals(logArray, valid1); } else if (!logArray.equals(valid2)) { Assert.assertEquals(logArray, valid2); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryOrderMainTest.java000066400000000000000000000013011475274123300313360ustar00rootroot00000000000000package test.factory; import java.util.List; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class FactoryOrderMainTest extends SimpleBaseTest { @Test public void factoriesShouldBeInvokedInTheOrderOfCreation() { TestNG tng = create(OrderFactory.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); List passed = tla.getPassedTests(); for (int i = 0; i < passed.size(); i++) { Assert.assertEquals(((OrderSample) passed.get(i).getInstance()).getValue(), i); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryTest.java000066400000000000000000000012321475274123300275400ustar00rootroot00000000000000package test.factory; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import org.testng.annotations.AfterSuite; import org.testng.annotations.Factory; import org.testng.annotations.Parameters; public class FactoryTest { static boolean isInvoked = false; @Parameters({"factory-param"}) @Factory public Object[] createObjects(String param) { assertEquals(param, "FactoryParam"); assertFalse(isInvoked, "Should only be invoked once"); isInvoked = true; return new Object[] {new FactoryTest2(42), new FactoryTest2(43)}; } @AfterSuite public void afterSuite() { isInvoked = false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryTest2.java000066400000000000000000000011611475274123300276230ustar00rootroot00000000000000package test.factory; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; public class FactoryTest2 { private static List numbers = new ArrayList<>(); private int number; public FactoryTest2() { throw new RuntimeException("Shouldn't be invoked"); } public static List getNumbers() { return numbers; } public FactoryTest2(int n) { number = n; } @Test(groups = {"first"}) public void testInt() { Integer n = number; numbers.add(n); } @Override public String toString() { return "[FactoryTest2 " + number + "]"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryWithDataProvider.java000066400000000000000000000011051475274123300320400ustar00rootroot00000000000000package test.factory; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; public class FactoryWithDataProvider { @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {new int[] {3, 5}}, new Object[] {new int[] {7, 9}}, }; } @Factory(dataProvider = "dp") public Object[] factory(int[] array) { List result = new ArrayList<>(); for (int n : array) { result.add(new OddSample(n)); } return result.toArray(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryWithDataProviderTest.java000066400000000000000000000027671475274123300327170ustar00rootroot00000000000000package test.factory; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.factory.issue1770.SampleTestFour; public class FactoryWithDataProviderTest extends SimpleBaseTest { /** Verify that a factory can receive a data provider */ @Test public void verifyDataProvider() { TestNG tng = create(FactoryWithDataProvider.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); assertThat(tla.getPassedTests()).hasSize(4); } private static final String RANDOM_VALUE = "random_value"; @Test(description = "GITHUB-1770") public void verifyDataProvider2() { InvokedMethodNameListener listener = new InvokedMethodNameListener(); XmlSuite xmlSuite = createXmlSuite("xml_suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "xml_test", SampleTestFour.class); Map parameters = Maps.newHashMap(); parameters.put("isCustom", RANDOM_VALUE); xmlTest.setParameters(parameters); TestNG testng = create(xmlSuite); testng.addListener(listener); testng.run(); assertThat(listener.getLogs("test")) .containsExactlyElementsOf(Collections.singletonList(RANDOM_VALUE)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryWithInstanceInfo2Sample.java000066400000000000000000000011721475274123300332640ustar00rootroot00000000000000package test.factory; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; /** This class is created by FactoryWithInstanceInfo2Sample */ public class FactoryWithInstanceInfo2Sample { private static List numbers = new ArrayList<>(); private int number; public FactoryWithInstanceInfo2Sample() { throw new RuntimeException("Shouldn't be invoked"); } public static List getNumbers() { return numbers; } public FactoryWithInstanceInfo2Sample(int n) { number = n; } @Test(groups = {"first"}) public void testInt() { numbers.add(number); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/FactoryWithInstanceInfoTest.java000066400000000000000000000017621475274123300327050ustar00rootroot00000000000000package test.factory; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import org.testng.IInstanceInfo; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Factory; import org.testng.annotations.Parameters; import org.testng.internal.InstanceInfo; public class FactoryWithInstanceInfoTest { static boolean isInvoked = false; @Parameters({"factory-param"}) @Factory public IInstanceInfo[] createObjectsWithInstanceInfo(String param) { assertEquals(param, "FactoryParam", "Incorrect param: " + param); assertFalse(isInvoked, "Should only be invoked once"); isInvoked = true; return new IInstanceInfo[] { new InstanceInfo<>( FactoryWithInstanceInfo2Sample.class, new FactoryWithInstanceInfo2Sample(42)), new InstanceInfo<>( FactoryWithInstanceInfo2Sample.class, new FactoryWithInstanceInfo2Sample(43)), }; } @BeforeSuite public void beforeSuite() { isInvoked = false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/GitHub876Sample.java000066400000000000000000000016261475274123300300710ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class GitHub876Sample { @Factory public Object[] createInstances() { return new Object[] { new GitHub876Sample(new DataTest("foo", true)), new GitHub876Sample(new DataTest("FOO", false)) }; } private final DataTest dataTest; public GitHub876Sample(DataTest dataTest) { this.dataTest = dataTest; } @Test public void test() { switch (dataTest.s) { case "FOO": Assert.assertFalse(dataTest.b); break; case "foo": Assert.assertTrue(dataTest.b); break; default: Assert.fail("Unknown value"); } } public static class DataTest { private final String s; private final boolean b; public DataTest(String s, boolean b) { this.s = s; this.b = b; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/InterleavingFactorySample.java000066400000000000000000000004751475274123300324220ustar00rootroot00000000000000package test.factory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; public class InterleavingFactorySample { @Factory public Object[] factory() { return new Object[] {new InterleavingSample(1), new InterleavingSample(2)}; } @BeforeClass public void beforeB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/InterleavingSample.java000066400000000000000000000011541475274123300310650ustar00rootroot00000000000000package test.factory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class InterleavingSample { public final int n; public InterleavingSample(int n) { this.n = n; } private void log(Integer s) { FactoryInterleavingTest.LOG.add(n * 10 + s); } @Override public String toString() { return "[A n:" + n + "]"; } @BeforeClass public void bc() { log(0); } @AfterClass public void ac() { log(3); } @Test public void f1() { log(1); } @Test public void f2() { log(2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/IteratorEmptyFactorySample.java000066400000000000000000000010301475274123300325670ustar00rootroot00000000000000package test.factory; import java.util.Collections; import java.util.Iterator; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class IteratorEmptyFactorySample { @DataProvider(name = "values") public static Iterator values() { return Collections.emptyIterator(); } @Factory(dataProvider = "values") public IteratorEmptyFactorySample(int value) {} @Test public void test() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/MySample.java000066400000000000000000000015321475274123300270230ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.annotations.Test; public class MySample { private final int i; // in this test, our default constructor sets s to a value that will cause a failure // the valid test instances should come from the factory public MySample() { i = 0; } public MySample(int i) { this.i = i; } @Test(groups = "MySample") public void testMethod() { FactoryInSeparateClassTest.addToSum(i); // assert i > 0 : "MySample was not constructed with correct params"; Assert.assertNotEquals(i, 0, "My test was not created by the factory"); } @Test(dependsOnGroups = "testMethodOnFactoryClass") public void verifyThatTestMethodOnFactoryClassWasRun() { Assert.assertTrue( FactoryInSeparateClassTest.wasRun(), "Test method on factory class wasn't run"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/NestedFactorySample.java000066400000000000000000000020621475274123300312070ustar00rootroot00000000000000package test.factory; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class NestedFactorySample { private final int m_capacity; private final float m_loadFactor; public class NestedFactory { @Factory public Object[] createInstances() { return new NestedFactorySample[] { new NestedFactorySample(1, 0.1f), new NestedFactorySample(10, 0.5f), }; } } private static int m_instanceCount = 0; public NestedFactorySample() { this(2, 0.4f); } public NestedFactorySample(int capacity, float loadFactor) { m_instanceCount++; this.m_capacity = capacity; this.m_loadFactor = loadFactor; } @Test public void verify() { // Should have three instances: the default one created by TestNG // and two created by the factory assertEquals(m_instanceCount, 3); assertTrue( (m_capacity == 1 && m_loadFactor == 0.1f) || m_capacity == 10 && m_loadFactor == 0.5f); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/NestedStaticFactorySample.java000066400000000000000000000021441475274123300323600ustar00rootroot00000000000000package test.factory; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class NestedStaticFactorySample { private final int m_capacity; private final float m_loadFactor; public static class NestedStaticFactory { @Factory public Object[] createInstances() { return new NestedStaticFactorySample[] { new NestedStaticFactorySample(1, 0.1f), new NestedStaticFactorySample(10, 0.5f), }; } } private static int m_instanceCount = 0; public NestedStaticFactorySample() { this(2, 0.4f); } public NestedStaticFactorySample(int capacity, float loadFactor) { m_instanceCount++; this.m_capacity = capacity; this.m_loadFactor = loadFactor; } @Test public void verify() { // Should have three instances: the default one created by TestNG // and two created by the factory assertEquals(m_instanceCount, 2); assertTrue( (m_capacity == 1 && m_loadFactor == 0.1f) || m_capacity == 10 && m_loadFactor == 0.5f); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/NonPublicFactory.java000066400000000000000000000003501475274123300305120ustar00rootroot00000000000000package test.factory; import org.testng.annotations.Factory; public class NonPublicFactory { @Factory private Object[] createInstances() { return new Object[] {new BaseFactorySample(42), new BaseFactorySample(43)}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/NotStaticDataProvider.java000066400000000000000000000003521475274123300315100ustar00rootroot00000000000000package test.factory; import org.testng.annotations.DataProvider; public class NotStaticDataProvider { @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {43}, new Object[] {44}, }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/OddSample.java000066400000000000000000000004061475274123300271430ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.annotations.Test; public class OddSample { private final int n; public OddSample(int n) { this.n = n; } @Test public void verify() { Assert.assertNotEquals(n % 2, 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/OrderFactory.java000066400000000000000000000005401475274123300276750ustar00rootroot00000000000000package test.factory; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; public class OrderFactory { @Factory public static Object[] testF() { List result = new ArrayList<>(); for (int i = 0; i < 5; i++) { result.add(new OrderSample(i)); } return result.toArray(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/OrderSample.java000066400000000000000000000010561475274123300275120ustar00rootroot00000000000000package test.factory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class OrderSample { final int value; public OrderSample(int j) { value = j; } @BeforeClass(groups = {"s1ds"}) public void setup() {} @Test(groups = {"s1ds"}) public void methodC1() {} @AfterClass(groups = {"s1ds"}) public void cleanup() {} @Override public String toString() { return "[OrderSample " + value + "]"; } public int getValue() { return value; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/StaticDataProvider.java000066400000000000000000000003561475274123300310330ustar00rootroot00000000000000package test.factory; import org.testng.annotations.DataProvider; public class StaticDataProvider { @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {43}, new Object[] {44}, }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/TestClassAnnotationTest.java000066400000000000000000000011321475274123300320700ustar00rootroot00000000000000package test.factory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Make sure that @Factory methods are not counted as @Test in the presence of a class-scoped @Test * annotation. */ @Test public class TestClassAnnotationTest { private int count; @Factory public Object[] createFixture() { count++; return new Object[] {new Object[] {new Object()}}; } public void testOne() { count++; } @AfterClass public void verify() { Assert.assertEquals(count, 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/VerifyFactoryTest.java000066400000000000000000000006671475274123300307400ustar00rootroot00000000000000package test.factory; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; public class VerifyFactoryTest { @Test(dependsOnGroups = {"first"}) public void mainCheck() { List numbers = FactoryTest2.getNumbers(); Assert.assertTrue(numbers.contains(42), "Didn't find 42"); Assert.assertTrue(numbers.contains(43), "Didn't find 43"); Assert.assertEquals(numbers.size(), 2); } } VerifyFactoryWithInstanceInfoTest.java000066400000000000000000000007311475274123300340060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factorypackage test.factory; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; public class VerifyFactoryWithInstanceInfoTest { @Test(dependsOnGroups = {"first"}) public void mainCheck() { List numbers = FactoryWithInstanceInfo2Sample.getNumbers(); Assert.assertTrue(numbers.contains(42), "Didn't find 42"); Assert.assertTrue(numbers.contains(43), "Didn't find 43"); Assert.assertEquals(numbers.size(), 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/classconf/000077500000000000000000000000001475274123300264035ustar00rootroot00000000000000XClassOrderWithFactory.java000066400000000000000000000013661475274123300335520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/classconfpackage test.factory.classconf; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class XClassOrderWithFactory { public static final String EXPECTED_LOG = "BTABTABTA"; public static final StringBuffer LOG = new StringBuffer(); @Factory public Object[] createInstances() { return new Object[] {new XClassOrderTest(), new XClassOrderTest(), new XClassOrderTest()}; } public static class XClassOrderTest { @BeforeClass public void beforeClass() { LOG.append("B"); } public @Test void test() { LOG.append("T"); } public @AfterClass void afterClass() { LOG.append("A"); } } } XClassOrderWithFactoryTest.java000066400000000000000000000011141475274123300344010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/classconfpackage test.factory.classconf; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; public class XClassOrderWithFactoryTest { @Test public void testBeforeAfterClassInvocationsWithFactory() { TestNG testng = new TestNG(); testng.setTestClasses(new Class[] {XClassOrderWithFactory.class}); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); Assert.assertEquals(XClassOrderWithFactory.LOG.toString(), XClassOrderWithFactory.EXPECTED_LOG); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083/000077500000000000000000000000001475274123300262265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083/ArrayFactorySample.java000066400000000000000000000011441475274123300326410ustar00rootroot00000000000000package test.factory.github1083; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ArrayFactorySample { public static final List parameters = new ArrayList<>(); private final String parameter; private ArrayFactorySample(String parameter) { this.parameter = parameter; } @Test public void test() { parameters.add(parameter); } @Factory(indices = 1) public static Object[] arrayFactory() { return new Object[] {new ArrayFactorySample("foo"), new ArrayFactorySample("bar")}; } } ConstructorFactorySample.java000066400000000000000000000012501475274123300340270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083package test.factory.github1083; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ConstructorFactorySample { public static final List parameters = new ArrayList<>(); private final String parameter; @Factory(indices = 1, dataProvider = "dp") public ConstructorFactorySample(String parameter) { this.parameter = parameter; } @Test public void test() { parameters.add(parameter); } @DataProvider public static Object[][] dp() { return new Object[][] {new Object[] {"foo"}, new Object[] {"bar"}}; } } DataProviderArrayFactorySample.java000066400000000000000000000014551475274123300350740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083package test.factory.github1083; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class DataProviderArrayFactorySample { public static final List parameters = new ArrayList<>(); private final String parameter; private DataProviderArrayFactorySample(String parameter) { this.parameter = parameter; } @Test public void test() { parameters.add(parameter); } @Factory(indices = 1, dataProvider = "dp") public static Object[] arrayFactory(String s) { return new Object[] {new DataProviderArrayFactorySample(s)}; } @DataProvider public static Object[][] dp() { return new Object[][] {new Object[] {"foo"}, new Object[] {"bar"}}; } } DataProviderInstanceInfoFactorySample.java000066400000000000000000000017621475274123300363770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083package test.factory.github1083; import java.util.ArrayList; import java.util.List; import org.testng.IInstanceInfo; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.internal.InstanceInfo; public class DataProviderInstanceInfoFactorySample { public static final List parameters = new ArrayList<>(); private final String parameter; private DataProviderInstanceInfoFactorySample(String parameter) { this.parameter = parameter; } @Test public void test() { parameters.add(parameter); } @Factory(indices = 1, dataProvider = "dp") public static IInstanceInfo[] arrayFactory(String s) { return new IInstanceInfo[] { new InstanceInfo<>( DataProviderInstanceInfoFactorySample.class, new DataProviderInstanceInfoFactorySample(s)) }; } @DataProvider public static Object[][] dp() { return new Object[][] {new Object[] {"foo"}, new Object[] {"bar"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083/GitHub1083Test.java000066400000000000000000000027231475274123300314330ustar00rootroot00000000000000package test.factory.github1083; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import java.util.List; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class GitHub1083Test extends SimpleBaseTest { @Test(dataProvider = "dp") public void testArrayFactorySample(Class sampleClass) throws NoSuchFieldException, IllegalAccessException { List parameters = getParameters(sampleClass); parameters.clear(); TestNG tng = create(sampleClass); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(parameters).containsExactly("bar"); assertThat(listener.getSucceedMethodNames()).containsExactly("test"); } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {ArrayFactorySample.class}, new Object[] {ConstructorFactorySample.class}, new Object[] {DataProviderArrayFactorySample.class}, new Object[] {DataProviderInstanceInfoFactorySample.class}, new Object[] {InstanceInfoFactorySample.class} }; } public static List getParameters(Class clazz) throws NoSuchFieldException, IllegalAccessException { Field parameters = clazz.getField("parameters"); return (List) parameters.get(null); } } InstanceInfoFactorySample.java000066400000000000000000000015241475274123300340660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1083package test.factory.github1083; import java.util.ArrayList; import java.util.List; import org.testng.IInstanceInfo; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.internal.InstanceInfo; public class InstanceInfoFactorySample { public static final List parameters = new ArrayList<>(); private final String parameter; private InstanceInfoFactorySample(String parameter) { this.parameter = parameter; } @Test public void test() { parameters.add(parameter); } @Factory(indices = 1) public static IInstanceInfo[] arrayFactory() { return new IInstanceInfo[] { new InstanceInfo<>(InstanceInfoFactorySample.class, new InstanceInfoFactorySample("foo")), new InstanceInfo<>(InstanceInfoFactorySample.class, new InstanceInfoFactorySample("bar")) }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1131/000077500000000000000000000000001475274123300262205ustar00rootroot00000000000000EmptyConstructorSample.java000066400000000000000000000007421475274123300335150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1131package test.factory.github1131; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class EmptyConstructorSample { public static int count = 0; @Factory(dataProvider = "dataProvider") public EmptyConstructorSample() { count++; } @Test public void test() {} @DataProvider public static Object[][] dataProvider() { return new Object[][] {new Object[] {}, new Object[] {}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1131/GitHub1131Test.java000066400000000000000000000031071475274123300314140ustar00rootroot00000000000000package test.factory.github1131; import static org.assertj.core.api.Assertions.assertThat; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class GitHub1131Test extends SimpleBaseTest { @Test public void testFactoryOnEmptyConstructor() { EmptyConstructorSample.count = 0; TestNG tng = create(EmptyConstructorSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("test", "test"); Assert.assertEquals(EmptyConstructorSample.count, 2); } @Test public void testFactoryOnIntConstructor() { IntConstructorSample.parameters.clear(); TestNG tng = create(IntConstructorSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("test", "test"); assertThat(IntConstructorSample.parameters).containsExactly(1, 2); } @Test public void testFactoryOnStringConstructor() { StringConstructorSample.parameters.clear(); TestNG tng = create(StringConstructorSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("test", "test"); assertThat(StringConstructorSample.parameters).containsExactly("foo", "bar"); } } IntConstructorSample.java000066400000000000000000000011271475274123300331470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1131package test.factory.github1131; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class IntConstructorSample { public static final List parameters = new ArrayList<>(); @Factory(dataProvider = "dataProvider") public IntConstructorSample(int parameter) { parameters.add(parameter); } @Test public void test() {} @DataProvider public static Object[][] dataProvider() { return new Object[][] {new Object[] {1}, new Object[] {2}}; } } StringConstructorSample.java000066400000000000000000000011471475274123300336650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1131package test.factory.github1131; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class StringConstructorSample { public static final List parameters = new ArrayList<>(); @Factory(dataProvider = "dataProvider") public StringConstructorSample(String parameter) { parameters.add(parameter); } @Test public void test() {} @DataProvider public static Object[][] dataProvider() { return new Object[][] {new Object[] {"foo"}, new Object[] {"bar"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1631/000077500000000000000000000000001475274123300262255ustar00rootroot00000000000000DataProviderTransformer.java000066400000000000000000000023661475274123300336270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1631package test.factory.github1631; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.ITestAnnotation; public class DataProviderTransformer implements IAnnotationTransformer { private Class dataProviderClass; @Override public void transform( final IConfigurationAnnotation annotation, final Class testClass, final Constructor testConstructor, final Method testMethod) { // not implemented } @Override public void transform(final IDataProviderAnnotation annotation, final Method testMethod) { // not implemented } @Override public void transform( final ITestAnnotation annotation, final Class testClass, final Constructor testConstructor, final Method testMethod) { // not implemented } @Override public void transform(final IFactoryAnnotation annotation, final Method testMethod) { dataProviderClass = annotation.getDataProviderClass(); } public Class getDataProviderClass() { return dataProviderClass; } } ExternalDataProviders.java000066400000000000000000000003111475274123300332560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1631package test.factory.github1631; import org.testng.annotations.DataProvider; public class ExternalDataProviders { @DataProvider public Object[] data() { return new Object[] {1, 2, 3}; } } FactoryWithExternalDataProviderTests.java000066400000000000000000000006771475274123300363210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1631package test.factory.github1631; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryWithExternalDataProviderTests { public FactoryWithExternalDataProviderTests() {} @Factory(dataProvider = "data", dataProviderClass = ExternalDataProviders.class) public FactoryWithExternalDataProviderTests(final int i) { // not important } @Test public void fakeTest() { // not important } } FactoryWithLocalDataProviderTests.java000066400000000000000000000010041475274123300355520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1631package test.factory.github1631; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryWithLocalDataProviderTests { public FactoryWithLocalDataProviderTests() {} @Factory(dataProvider = "data") public FactoryWithLocalDataProviderTests(final int i) { // not important } @DataProvider public Object[] data() { return new Object[] {1, 2, 3}; } @Test public void fakeTest() { // not important } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github1631/GitHub1631Tests.java000066400000000000000000000022271475274123300316130ustar00rootroot00000000000000package test.factory.github1631; import org.testng.*; import org.testng.annotations.Test; import test.SimpleBaseTest; public class GitHub1631Tests extends SimpleBaseTest { @Test( description = "Test @Factory(dataProvider) should implicitly inject data provider class name") public void factoryWithLocalDataProviderShouldUseHostClassName() { final DataProviderTransformer transformer = runTest(FactoryWithLocalDataProviderTests.class); Assert.assertEquals( transformer.getDataProviderClass(), FactoryWithLocalDataProviderTests.class); } @Test(description = "Test @Factory(dataProvider) should explicitly set data provider class name") public void factoryWithExplicitDataProviderShouldUseExternalClassName() { final DataProviderTransformer transformer = runTest(FactoryWithExternalDataProviderTests.class); Assert.assertEquals(transformer.getDataProviderClass(), ExternalDataProviders.class); } private DataProviderTransformer runTest(final Class cls) { final TestNG tng = create(cls); final DataProviderTransformer dpt = new DataProviderTransformer(); tng.addListener(dpt); tng.run(); return dpt; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github2428/000077500000000000000000000000001475274123300262325ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github2428/FactoryTest.java000066400000000000000000000010251475274123300313420ustar00rootroot00000000000000package test.factory.github2428; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryTest { int i; @Factory(dataProvider = "dp") public FactoryTest(int i) { this.i = i; } @DataProvider(parallel = true) public static Object[][] dp() { return new Object[][] {{5}, {4}, {12}, {9}, {2}}; } @BeforeClass public void beforeClassBody() {} @Test public void testBody() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github2428/IssueTest.java000066400000000000000000000011251475274123300310240ustar00rootroot00000000000000package test.factory.github2428; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void issue2438() { TestNG testng = create(FactoryTest.class); testng.setDefaultSuiteName("factory tests"); Reporter reporter = new Reporter(); testng.addListener(reporter); testng.run(); Assert.assertEquals( reporter.getResults().size(), 5, "Data provider generated 5 rows, so expecting 5 distinct test instances to be used"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github2428/Reporter.java000066400000000000000000000013751475274123300307050ustar00rootroot00000000000000package test.factory.github2428; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import org.testng.IReporter; import org.testng.ISuite; import org.testng.xml.XmlSuite; public class Reporter implements IReporter { private final Set results = Collections.newSetFromMap(new IdentityHashMap<>()); public Set getResults() { return results; } public void generateReport( List xmlSuites, List suites, String outputDirectory) { suites .get(0) .getResults() .get("Command line test") .getTestContext() .getPassedConfigurations() .getAllResults() .forEach(x -> results.add(x.getInstance())); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github328/000077500000000000000000000000001475274123300261475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github328/ExcludedFactory.java000066400000000000000000000010731475274123300321000ustar00rootroot00000000000000package test.factory.github328; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ExcludedFactory { public static final String EXCLUDED_GROUP = "excludedCtorFactory"; public static boolean factoryRan = false; @Factory(dataProvider = "empty") public ExcludedFactory(int a) { factoryRan = true; } @Test(groups = EXCLUDED_GROUP) public void emptyTest() {} @DataProvider(name = "empty") private static Object[][] provider() { return new Object[][] {{1}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/github328/GitHub328Test.java000066400000000000000000000013301475274123300312660ustar00rootroot00000000000000package test.factory.github328; import static test.factory.github328.ExcludedFactory.EXCLUDED_GROUP; import java.util.Collections; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class GitHub328Test extends SimpleBaseTest { @Test public void testFactoryExecutionWhenNoIncludedTests() { XmlSuite suite = createXmlSuite("Suite"); XmlTest test = createXmlTest(suite, "Test", ExcludedFactory.class); test.setExcludedGroups(Collections.singletonList(EXCLUDED_GROUP)); TestNG tng = create(suite); tng.run(); Assert.assertFalse(ExcludedFactory.factoryRan); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1041/000077500000000000000000000000001475274123300260665ustar00rootroot00000000000000FactoryAnnotatedConstructorExample.java000066400000000000000000000023071475274123300357030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1041package test.factory.issue1041; import java.util.List; import java.util.Objects; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.collections.Lists; public class FactoryAnnotatedConstructorExample { static List objects = Lists.newArrayList(); private int data; @Factory(dataProvider = "dp") public FactoryAnnotatedConstructorExample(int data) { this.data = data; addInstance(this); } private static void addInstance(FactoryAnnotatedConstructorExample instance) { objects.add(instance); } @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] {{1}, {2}}; } @Test public void testMethod() { Assert.assertTrue(data > 0); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FactoryAnnotatedConstructorExample that = (FactoryAnnotatedConstructorExample) o; return data == that.data; } @Override public int hashCode() { return Objects.hash(data); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1041/IssueTest.java000066400000000000000000000016441475274123300306660ustar00rootroot00000000000000package test.factory.issue1041; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testFactoryAnnotatedConstructor() { TestNG testng = create(FactoryAnnotatedConstructorExample.class); ResultExtractor extractor = new ResultExtractor(); testng.addListener(extractor); testng.run(); List expected = Lists.newArrayList(); expected.add(new Object[] {1}); expected.add(new Object[] {2}); List actual = FactoryAnnotatedConstructorExample.objects.stream() .map(extractor::getData) .collect(Collectors.toList()); assertThat(actual).containsExactlyInAnyOrderElementsOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1041/ResultExtractor.java000066400000000000000000000024141475274123300321040ustar00rootroot00000000000000package test.factory.issue1041; import java.util.Arrays; import java.util.List; import java.util.Map; import org.testng.IReporter; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; public class ResultExtractor implements IReporter { private Map data = Maps.newHashMap(); @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { suites.forEach(this::process); } private void process(ISuite suite) { suite.getResults().values().forEach(this::process); } private void process(ISuiteResult suiteResult) { ITestContext ctx = suiteResult.getTestContext(); List resultmaps = Arrays.asList(ctx.getFailedTests(), ctx.getPassedTests(), ctx.getSkippedTests()); resultmaps.forEach(this::process); } private void process(IResultMap resultMap) { resultMap.getAllResults().forEach(this::process); } private void process(ITestResult result) { data.put(result.getInstance(), result.getFactoryParameters()); } public Object[] getData(Object key) { return data.get(key); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1745/000077500000000000000000000000001475274123300261015ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1745/Github1745Test.java000066400000000000000000000016451475274123300313550ustar00rootroot00000000000000package test.factory.issue1745; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class Github1745Test extends SimpleBaseTest { private static final String TEST_METHOD = "testMethod"; @Test public void testMethod() { XmlTest xmlTest = createXmlTest("1745_suite", "1745_test", SuiteXmlPoweredFactoryTest.class); xmlTest.addParameter("number", "3"); TestNG testng = create(); testng.setXmlSuites(Collections.singletonList(xmlTest.getSuite())); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); assertThat(listener.getSucceedMethodNames()) .containsExactly(TEST_METHOD, TEST_METHOD, TEST_METHOD, TEST_METHOD); } } SuiteXmlPoweredFactoryTest.java000066400000000000000000000014271475274123300341610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1745package test.factory.issue1745; import org.testng.ITestContext; import org.testng.annotations.Factory; import org.testng.xml.XmlTest; public class SuiteXmlPoweredFactoryTest { @Factory public Object[] createInstances(ITestContext ctx) { return new Object[] {new TestClassSample(ctx, "testcontext")}; } @Factory public Object[] createInstances(XmlTest currentXmlTest) { return new Object[] {new TestClassSample(currentXmlTest, "xmltest")}; } @Factory public Object[] createInstances(ITestContext ctx, XmlTest currentXmlTest) { return new Object[] {new TestClassSample(ctx, currentXmlTest)}; } @Factory public Object[] createInstances(XmlTest currentXmlTest, ITestContext ctx) { return new Object[] {new TestClassSample(ctx, currentXmlTest)}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1745/TestClassSample.java000066400000000000000000000021571475274123300320200ustar00rootroot00000000000000package test.factory.issue1745; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.ITestContext; import org.testng.annotations.Test; import org.testng.xml.XmlTest; public class TestClassSample { private ITestContext ctx; private XmlTest currentXmlTest; private String whatWasPassed = ""; public TestClassSample(ITestContext ctx, String whatWasPassed) { this.ctx = ctx; this.whatWasPassed = whatWasPassed; } public TestClassSample(XmlTest currentXmlTest, String whatWasPassed) { this.currentXmlTest = currentXmlTest; this.whatWasPassed = whatWasPassed; } public TestClassSample(ITestContext ctx, XmlTest currentXmlTest) { this.ctx = ctx; this.currentXmlTest = currentXmlTest; } @Test public void testMethod() { if ("testcontext".equalsIgnoreCase(whatWasPassed)) { // only testcontext was provided assertNotNull(ctx); currentXmlTest = ctx.getCurrentXmlTest(); } assertNotNull(currentXmlTest); int number = Integer.parseInt(currentXmlTest.getParameter("number")); assertTrue(number != 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1770/000077500000000000000000000000001475274123300260775ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1770/SampleTestBase.java000066400000000000000000000003101475274123300316100ustar00rootroot00000000000000package test.factory.issue1770; public class SampleTestBase { private String flag; public SampleTestBase(String fl) { this.flag = fl; } public String getFlag() { return flag; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1770/SampleTestFour.java000066400000000000000000000006131475274123300316570ustar00rootroot00000000000000package test.factory.issue1770; import org.testng.Reporter; import org.testng.annotations.Factory; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class SampleTestFour extends SampleTestBase { @Factory @Parameters({"isCustom"}) public SampleTestFour(String fl) { super(fl); } @Test public void test() { Reporter.log(getFlag()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1924/000077500000000000000000000000001475274123300261005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1924/IssueTest.java000066400000000000000000000011241475274123300306710ustar00rootroot00000000000000package test.factory.issue1924; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void ensureTestClassInstantiationWorksWhenFactoryMethodAndCustomConstructorPresent() { TestNG testng = create(TestclassSample.class); testng.run(); List expected = Arrays.asList("1", "2"); assertThat(TestclassSample.logs).containsExactlyInAnyOrderElementsOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue1924/TestclassSample.java000066400000000000000000000010361475274123300320520ustar00rootroot00000000000000package test.factory.issue1924; import java.util.List; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.collections.Lists; public class TestclassSample { public static List logs = Lists.newArrayList(); private int i; public TestclassSample(int i) { this.i = i; } @Factory public static Object[] produce() { return new Object[] {new TestclassSample(1), new TestclassSample(2)}; } @Test public void testMethod() { logs.add(Integer.toString(this.i)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue326/000077500000000000000000000000001475274123300260135ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue326/IssueTest.java000066400000000000000000000043331475274123300306110ustar00rootroot00000000000000package test.factory.issue326; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite.ParallelMode; import test.SimpleBaseTest; import test.factory.issue326.LocalTrackingListener.Statistics; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-326") public void testToCheckParallelExecutionOfInstancesWithOneThreadPerInstance() { TestNG testng = create(SampleTestClass.class); testng.setGroupByInstances(true); testng.setParallel(ParallelMode.INSTANCES); testng.setThreadCount(20); testng.setDataProviderThreadCount(10); LocalTrackingListener listener = new LocalTrackingListener(); testng.addListener(listener); testng.run(); // Ensure that the difference in start times for the methods in both instances is <= 1000 ms. long diff = computeDiffInStartTimeFor(listener.getResults(), SampleTestClass.FREDDY); assertThat(diff).isLessThanOrEqualTo(1000); diff = computeDiffInStartTimeFor(listener.getResults(), SampleTestClass.BARNEY); assertThat(diff).isLessThanOrEqualTo(1000); // Ensure that the thread ids for both the instances are different. long threadIdFreddyInstance = listener.getThreadIds().get(SampleTestClass.FREDDY); long threadIdBarneyInstance = listener.getThreadIds().get(SampleTestClass.BARNEY); assertThat(threadIdFreddyInstance).isNotEqualTo(threadIdBarneyInstance); } private static long computeDiffInStartTimeFor( Map> allStats, String instanceName) { long test1OnFreddyInstance = getStartTimeFrom(allStats, instanceName, "test1"); long test2OnFreddyInstance = getStartTimeFrom(allStats, instanceName, "test2"); return Math.abs(test2OnFreddyInstance - test1OnFreddyInstance); } private static long getStartTimeFrom( Map> allStats, String instanceName, String methodName) { return allStats.get(instanceName).stream() .filter(statistics -> statistics.methodName.equals(methodName)) .findFirst() .map(statistics -> statistics.startTimeInMs) .orElseThrow(IllegalStateException::new); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue326/LocalTrackingListener.java000066400000000000000000000025701475274123300331050ustar00rootroot00000000000000package test.factory.issue326; import java.util.List; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.collections.Maps; public class LocalTrackingListener implements IInvokedMethodListener { private Map> results = Maps.newConcurrentMap(); private Map threadIds = Maps.newConcurrentMap(); @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String key = testResult.getInstance().toString(); if (!results.containsKey(key)) { results.put(key, Lists.newArrayList()); } results .get(key) .add(new Statistics(testResult.getMethod().getMethodName(), testResult.getStartMillis())); if (!threadIds.containsKey(key)) { Long threadId = Long.parseLong(testResult.getAttribute(SampleTestClass.THREAD_ID).toString()); threadIds.put(key, threadId); } } public Map> getResults() { return results; } public Map getThreadIds() { return threadIds; } static class Statistics { String methodName; long startTimeInMs; public Statistics(String methodName, long startTimeInMs) { this.methodName = methodName; this.startTimeInMs = startTimeInMs; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue326/SampleTestClass.java000066400000000000000000000025331475274123300317300ustar00rootroot00000000000000package test.factory.issue326; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class SampleTestClass { static final String THREAD_ID = "threadId"; static final String FREDDY = "Freddy"; static final String BARNEY = "Barney"; private final String instance; private final Random random; @Factory(dataProvider = "dp") public SampleTestClass(String instance) { this.instance = instance; random = new Random(); } @DataProvider public static Iterator dp() { List names = Arrays.asList(new Object[] {FREDDY}, new Object[] {BARNEY}); return names.iterator(); } @Test public void test1() throws InterruptedException { printer(); } @Test public void test2() throws InterruptedException { printer(); } @Override public String toString() { return this.instance; } private void printer() throws InterruptedException { ITestResult result = Reporter.getCurrentTestResult(); result.setAttribute(THREAD_ID, Thread.currentThread().getId()); TimeUnit.MILLISECONDS.sleep(10 * random.nextInt(100)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue553/000077500000000000000000000000001475274123300260155ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue553/Base.java000066400000000000000000000004561475274123300275370ustar00rootroot00000000000000package test.factory.issue553; import org.testng.annotations.Factory; public abstract class Base { @Factory public Object[] createTests() { return new Object[] {new Inner()}; } public class Inner { @Factory public Object[] createTests() { return new Object[0]; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue553/Concrete.java000066400000000000000000000001061475274123300304170ustar00rootroot00000000000000package test.factory.issue553; public class Concrete extends Base {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/issue553/IssueTest.java000066400000000000000000000014001475274123300306030ustar00rootroot00000000000000package test.factory.issue553; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test( description = "GITHUB-553", expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = "\\nFound a default constructor and also a Factory method when working with .*") public void testMethod() { XmlTest xmltest = createXmlTest("suite", "test", Concrete.class); TestNG testng = create(xmltest.getSuite()); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/nested/000077500000000000000000000000001475274123300257125ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/nested/AbstractBaseSample.java000066400000000000000000000004761475274123300322640ustar00rootroot00000000000000package test.factory.nested; import org.testng.Assert; import org.testng.annotations.Test; public abstract class AbstractBaseSample { protected abstract String someMethod(String param); @Test public void test() { String result = someMethod("hello"); Assert.assertEquals(result, "hello world"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/nested/BaseFactorySample.java000066400000000000000000000004441475274123300321230ustar00rootroot00000000000000package test.factory.nested; import org.testng.annotations.Factory; public abstract class BaseFactorySample { public abstract AbstractBaseSample buildTest(); @Factory public Object[] createObjects() { AbstractBaseSample test = buildTest(); return new Object[] {test}; } } FactoryWithAnonymousTestsSample.java000066400000000000000000000004741475274123300350440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/nestedpackage test.factory.nested; public class FactoryWithAnonymousTestsSample extends BaseFactorySample { @Override public AbstractBaseSample buildTest() { return new AbstractBaseSample() { @Override protected String someMethod(String param) { return param + " world"; } }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/nested/GitHub1307Test.java000066400000000000000000000012741475274123300311160ustar00rootroot00000000000000package test.factory.nested; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class GitHub1307Test extends SimpleBaseTest { @Test public void testGitHub1307() { TestNG tng = create(FactoryWithAnonymousTestsSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).containsExactly("test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/sample/000077500000000000000000000000001475274123300257115ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/sample/Factory2Sample.java000066400000000000000000000026331475274123300314130ustar00rootroot00000000000000package test.factory.sample; import static org.testng.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; /** * Test that setUp methods are correctly interleaved even when we use similar instances of a same * test class. */ public class Factory2Sample { private static List methods = new ArrayList<>(); @BeforeSuite public void init() { methods = new ArrayList<>(); } @BeforeMethod public void setUp() { methods.add("setUp"); } @AfterMethod public void tearDown() { methods.add("tearDown"); } private static final List EXPECTED_METHODS = Arrays.asList( "setUp", "testInputImages", "tearDown", "setUp", "testInputImages", "tearDown", "setUp", "testImages", "tearDown", "setUp", "testImages", "tearDown"); @AfterSuite public void afterSuite() { assertEquals(methods, EXPECTED_METHODS); } @Test public void testInputImages() { methods.add("testInputImages"); } @Test(dependsOnMethods = {"testInputImages"}) public void testImages() { methods.add("testImages"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/factory/sample/Factory2TestSample.java000066400000000000000000000005521475274123300322510ustar00rootroot00000000000000package test.factory.sample; import org.testng.annotations.Factory; /** * Factory to test that setUp methods are correctly interleaved even when we use similar instances * of a same test class. */ public class Factory2TestSample { @Factory() public Object[] createObjects() { return new Object[] {new Factory2Sample(), new Factory2Sample()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/000077500000000000000000000000001475274123300257705ustar00rootroot00000000000000FailedReporter2SampleTest.java000066400000000000000000000006461475274123300335550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporterpackage test.failedreporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class FailedReporter2SampleTest { @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {0}, new Object[] {1}, new Object[] {2}, }; } @Test(dataProvider = "dp") public void f1(Integer ip) { if (ip == 1) { throw new RuntimeException(); } } } FailedReporterLocalTestClass.java000066400000000000000000000011211475274123300342570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporterpackage test.failedreporter; import org.testng.Assert; import org.testng.annotations.Test; /** * A simple test class that is used by {@link FailedReporterScenariosTest} class to test out the * presence/absence of testng-failed.xml file when there are failures/no failures scenarios. */ public class FailedReporterLocalTestClass { public static class WithFailure { @Test public void testMethodWithFailure() { Assert.fail(); } } public static class WithoutFailure { @Test public void testMethodWithoutFailure() { Assert.assertTrue(true); } } } FailedReporterParametersTest.java000066400000000000000000000117111475274123300343500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporterpackage test.failedreporter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.reporters.FailedReporter; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; import test.reports.SimpleFailedSample; public class FailedReporterParametersTest extends SimpleBaseTest { private File mTempDirectory; @BeforeMethod public void setUp() { mTempDirectory = createDirInTempDir("testng-tmp-" + System.currentTimeMillis() % 1000); } @AfterMethod public void tearDown() { deleteDir(mTempDirectory); } @Test public void failedSuiteShouldHaveParameters() { Map suiteParams = create("suite"); Map testParams = create("test"); Map classParams = create("class"); Map methodParams = create("method"); // In testng-failed.xml, suite will have both origin suite parameters and children tests // parameters. XmlSuite suite = createXmlSuite(suiteParams); TestNG tng = create(mTempDirectory.toPath(), suite); tng.setUseDefaultListeners(true); XmlTest test = createXmlTest(suite, suite.getName(), testParams); XmlClass clazz = createXmlClass(test, FailedReporterSampleTest.class, classParams); createXmlInclude(clazz, "f2", methodParams); tng.run(); runAssertions( mTempDirectory, "", new String[] {"suiteParam", "testParam", "classParam", "methodParam"}); } @Test(description = "github-2008") public void preserveParameters() throws IOException { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); XmlClass xmlClass1 = createXmlClass(xmlTest, SimpleFailedSample.class); xmlClass1.getLocalParameters().put("sharedParameter", "44"); xmlClass1.getLocalParameters().put("class1Parameter", "43"); XmlClass xmlClass2 = createXmlClass(xmlTest, AnotherSimpleFailedSample.class); xmlClass2.getLocalParameters().put("sharedParameter", "55"); xmlClass2.getLocalParameters().put("class2Parameter", "56"); TestNG tng = create(xmlSuite); Path temp = Files.createTempDirectory("preserveParameters"); tng.setOutputDirectory(temp.toAbsolutePath().toString()); tng.addListener(new FailedReporter()); tng.run(); Collection failedSuites = new Parser(temp.resolve(FailedReporter.TESTNG_FAILED_XML).toAbsolutePath().toString()) .parse(); XmlSuite failedSuite = failedSuites.iterator().next(); XmlTest failedTest = failedSuite.getTests().get(0); XmlClass failedClass1 = failedTest.getClasses().stream() .filter(failedClass -> failedClass.getName().equals("test.reports.SimpleFailedSample")) .findFirst() .get(); XmlClass failedClass2 = failedTest.getClasses().stream() .filter( failedClass -> failedClass .getName() .equals( "test.failedreporter.FailedReporterParametersTest$AnotherSimpleFailedSample")) .findFirst() .get(); // Cheeck class1 Parameters Assert.assertEquals("44", failedClass1.getAllParameters().get("sharedParameter")); Assert.assertEquals("43", failedClass1.getAllParameters().get("class1Parameter")); Assert.assertNull(failedClass1.getAllParameters().get("class2Parameter")); // Cheeck class2 Parameters Assert.assertEquals("55", failedClass2.getAllParameters().get("sharedParameter")); Assert.assertEquals("56", failedClass2.getAllParameters().get("class2Parameter")); Assert.assertNull(failedClass2.getAllParameters().get("class1Parameter")); } private static Map create(String prefix) { Map params = Maps.newHashMap(); params.put(prefix + "Param", prefix + "ParamValue"); return params; } private static void runAssertions(File outputDir, String expectedFormat, String[] expectedKeys) { File failed = new File(outputDir, "testng-failed.xml"); for (String expectedKey : expectedKeys) { List resultLines = Lists.newArrayList(); grep(failed, String.format(expectedFormat, expectedKey, expectedKey + "Value"), resultLines); int expectedSize = 1; Assert.assertEquals(resultLines.size(), expectedSize, "Mismatch param:" + expectedKey); } } class AnotherSimpleFailedSample { @Test public void failed() { throw new RuntimeException("Failing intentionally"); } } } FailedReporterSampleTest.java000066400000000000000000000004721475274123300334700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporterpackage test.failedreporter; import org.testng.SkipException; import org.testng.annotations.Test; public class FailedReporterSampleTest { @Test public void f2() { throw new RuntimeException(); } @Test public void f1() { throw new SkipException("Skipped"); } @Test public void f3() {} } FailedReporterScenariosTest.java000066400000000000000000000046511475274123300342000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporterpackage test.failedreporter; import static test.failedreporter.FailedReporterLocalTestClass.WithFailure; import static test.failedreporter.FailedReporterLocalTestClass.WithoutFailure; import java.io.File; import java.util.UUID; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.reporters.FailedReporter; import test.SimpleBaseTest; public class FailedReporterScenariosTest extends SimpleBaseTest { @Test public void testFileCreationSkipWhenNoFailuresExist() { File fileLocation = runTests(RUN_TYPES.WITHOUT_FAILURES); try { Assert.assertFalse(getLocation(fileLocation).exists()); } finally { if (fileLocation.exists()) { deleteDir(fileLocation); } } } @Test public void testFileCreationInMixedMode() { File fileLocation = runTests(RUN_TYPES.MIXED_MODE); runAssertions(fileLocation); } @Test public void testFileCreationWhenFailuresExist() { File fileLocation = runTests(RUN_TYPES.WITH_FAILURES); runAssertions(fileLocation); } private void runAssertions(File fileLocation) { try { FailedReporterTest.runAssertions( fileLocation, new String[] {"testMethodWithFailure"}, ""); Assert.assertTrue(getLocation(fileLocation).exists()); } finally { if (fileLocation.exists()) { deleteDir(fileLocation); } } } private File getLocation(File fileLocation) { String name = fileLocation.getAbsolutePath() + File.separator + FailedReporter.TESTNG_FAILED_XML; return new File(name); } private File runTests(RUN_TYPES runType) { String suiteName = UUID.randomUUID().toString(); File fileLocation = createDirInTempDir(suiteName); Class[] classes = {}; switch (runType) { case WITH_FAILURES: classes = new Class[] {WithFailure.class}; break; case WITHOUT_FAILURES: classes = new Class[] {WithoutFailure.class}; break; case MIXED_MODE: classes = new Class[] {WithFailure.class, WithoutFailure.class}; } TestNG testNG = create(fileLocation.toPath(), classes); testNG.setUseDefaultListeners(true); try { testNG.run(); } catch (AssertionError e) { // catch all assertion failures. Our intent is not assertions of the test class. } return fileLocation; } enum RUN_TYPES { WITH_FAILURES, WITHOUT_FAILURES, MIXED_MODE } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/FailedReporterTest.java000066400000000000000000000215321475274123300324050ustar00rootroot00000000000000package test.failedreporter; import java.io.File; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import test.failedreporter.issue1297.depend.PassDependsOnFailureSample; import test.failedreporter.issue1297.depend_on_group.GroupDependFailureSample; import test.failedreporter.issue1297.depend_on_group.GroupDependPassSample; import test.failedreporter.issue1297.depend_on_test.PassDependsOnPassSample; import test.failedreporter.issue1297.groups.GroupsPassSample; import test.failedreporter.issue1297.groups.GroupsSampleBase; import test.failedreporter.issue1297.inheritance.InheritanceFailureSample; import test.failedreporter.issue1297.inheritance.InheritancePassSample; import test.failedreporter.issue1297.straightforward.AllPassSample; import test.failedreporter.issue1297.straightforward.FailureSample; public class FailedReporterTest extends SimpleBaseTest { public static final String DEPENDENCY_GROUP = "failed"; public static final String DEPENDENT_GROUP = "run"; private File mTempDirectory; @BeforeMethod public void setUp() { mTempDirectory = createDirInTempDir("testng-tmp-" + System.currentTimeMillis() % 1000); } @AfterMethod public void tearDown() { deleteDir(mTempDirectory); } @Test public void failedAndSkippedMethodsShouldBeIncluded() { testFailedReporter( new String[] {"f1", "f2"}, "", FailedReporterSampleTest.class); } @Test public void failedMethodWithDataProviderShouldHaveInvocationNumbers() { testFailedReporter( new String[] {"f1"}, "", FailedReporter2SampleTest.class); } @Test(description = "github-1297") public void testExclusionOfPassedConfigs() { triggerTest(AllPassSample.class, FailureSample.class); String[] substitutions = new String[] {AllPassSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 0); substitutions = new String[] {"newTest2", "beforeClassFailureSample", "afterClassFailureSample"}; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testExclusionOfPassedConfigsAmidstInheritance() { triggerTest(InheritanceFailureSample.class, InheritancePassSample.class); String[] substitutions = new String[] {InheritancePassSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 0); substitutions = new String[] { "newTest2", "baseBeforeTest", "baseAfterClass", "baseBeforeClass", "baseBeforeMethod" }; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testExclusionOfPassedConfigsAmidstInheritanceIndependentOfOrder() { triggerTest(InheritancePassSample.class, InheritanceFailureSample.class); String[] substitutions = new String[] {InheritancePassSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 0); substitutions = new String[] { "newTest2", "baseBeforeTest", "baseAfterClass", "baseBeforeClass", "baseBeforeMethod" }; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testExclusionOfPassedConfigsInvolvingGroupsAtTestLevel() { triggerTest(GroupsSampleBase.class.getPackage().getName(), true, DEPENDENT_GROUP); String[] substitutions = new String[] {GroupsPassSample.class.getName(), GroupsSampleBase.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 0); substitutions = new String[] {"baseBeforeTest", "baseBeforeClassAlwaysRun", "newTest2"}; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testExclusionOfPassedConfigsInvolvingGroupsAtSuiteLevel() { triggerTest(GroupsSampleBase.class.getPackage().getName(), false, DEPENDENT_GROUP); String[] substitutions = new String[] {GroupsPassSample.class.getName(), GroupsSampleBase.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 0); substitutions = new String[] {"baseBeforeTest", "baseBeforeClassAlwaysRun", "newTest2"}; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testInclusionOfPassedTestsDependOnFailedPackageSuite() { triggerTest(PassDependsOnFailureSample.class.getPackage().getName()); String[] substitutions = new String[] {PassDependsOnFailureSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 1); substitutions = new String[] {"newTest1", "newTest2"}; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testExclusionOfPassedTestsDependOnPassedTest() { triggerTest(PassDependsOnPassSample.class); String[] substitutions = new String[] {PassDependsOnPassSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 1); substitutions = new String[] {"test1", "test2", "dependsOnTest2"}; runAssertions(mTempDirectory, substitutions, "", 1); substitutions = new String[] {"dependsOnTest1"}; runAssertions(mTempDirectory, substitutions, "", 0); } @Test(description = "github-1297") public void testInclusionOfPassedTestsDependOnFailedClassSuite() { triggerTest(PassDependsOnFailureSample.class); String[] substitutions = new String[] {PassDependsOnFailureSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 1); substitutions = new String[] {"newTest1", "newTest2"}; runAssertions(mTempDirectory, substitutions, "", 1); } @Test(description = "github-1297") public void testInclusionOfPassedTestsDependOnFailedGroup() { triggerTest( GroupDependPassSample.class.getPackage().getName(), false, DEPENDENT_GROUP, DEPENDENCY_GROUP); String[] substitutions = new String[] {GroupDependFailureSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 1); substitutions = new String[] {GroupDependPassSample.class.getName()}; runAssertions(mTempDirectory, substitutions, "", 1); substitutions = new String[] {"baseBeforeTest", "baseBeforeClassAlwaysRun"}; runAssertions(mTempDirectory, substitutions, "", 2); substitutions = new String[] {"newTest1", "newTest2"}; runAssertions(mTempDirectory, substitutions, "", 1); } private void triggerTest( String packageName, boolean applyGroupSelectionAtTest, String... groups) { final XmlSuite suite = createXmlSuite("1297_suite"); final XmlTest xmlTest = createXmlTestWithPackages(suite, "1297_test", packageName); if (applyGroupSelectionAtTest) { createXmlGroups(xmlTest, groups); } else { createXmlGroups(suite, groups); } TestNG tng = create(mTempDirectory.toPath(), suite); tng.setUseDefaultListeners(true); tng.run(); } private void triggerTest(String packageName) { final XmlSuite suite = createXmlSuite("1297_suite"); createXmlTestWithPackages(suite, "1297_test", packageName); TestNG tng = create(mTempDirectory.toPath(), suite); tng.setUseDefaultListeners(true); tng.run(); } private void testFailedReporter(String[] expectedMethods, String expectedLine, Class... cls) { triggerTest(cls); runAssertions(mTempDirectory, expectedMethods, expectedLine); } private void triggerTest(Class... cls) { TestNG tng = create(mTempDirectory.toPath(), cls); tng.setUseDefaultListeners(true); tng.run(); } static void runAssertions(File outputDir, String[] expectedMethods, String expectedLine) { runAssertions(outputDir, expectedMethods, expectedLine, 1); } private static void runAssertions( File outputDir, String[] expectedMethods, String expectedLine, int expected) { File failed = new File(outputDir, "testng-failed.xml"); for (String s : expectedMethods) { List resultLines = Lists.newArrayList(); Assert.assertTrue(failed.exists(), String.format("File %s not exists", failed.getName())); grep(failed, String.format(expectedLine, s), resultLines); Assert.assertEquals( resultLines.size(), expected, String.format("Matched lines:\n %s", String.join(",\n", resultLines))); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/000077500000000000000000000000001475274123300274435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend/000077500000000000000000000000001475274123300307025ustar00rootroot00000000000000PassDependsOnFailureSample.java000066400000000000000000000004301475274123300366430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/dependpackage test.failedreporter.issue1297.depend; import org.testng.Assert; import org.testng.annotations.Test; public class PassDependsOnFailureSample { @Test(dependsOnMethods = "newTest2") public void newTest1() {} @Test public void newTest2() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend_on_group/000077500000000000000000000000001475274123300326125ustar00rootroot00000000000000GroupDependFailureSample.java000066400000000000000000000005261475274123300402670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend_on_grouppackage test.failedreporter.issue1297.depend_on_group; import org.testng.Assert; import org.testng.annotations.Test; import test.failedreporter.FailedReporterTest; public class GroupDependFailureSample extends GroupDependSampleBase { @Test(groups = FailedReporterTest.DEPENDENCY_GROUP) public void newTest2() { Assert.fail(); } } GroupDependPassSample.java000066400000000000000000000005461475274123300376100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend_on_grouppackage test.failedreporter.issue1297.depend_on_group; import org.testng.annotations.Test; import test.failedreporter.FailedReporterTest; public class GroupDependPassSample extends GroupDependSampleBase { @Test( groups = FailedReporterTest.DEPENDENT_GROUP, dependsOnGroups = FailedReporterTest.DEPENDENCY_GROUP) public void newTest1() {} } GroupDependSampleBase.java000066400000000000000000000011131475274123300375430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend_on_grouppackage test.failedreporter.issue1297.depend_on_group; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import test.failedreporter.FailedReporterTest; public class GroupDependSampleBase { @BeforeTest(groups = FailedReporterTest.DEPENDENT_GROUP) public void baseBeforeTest() {} @BeforeClass(alwaysRun = true) public void baseBeforeClassAlwaysRun() {} @BeforeMethod public void baseBeforeMethod() {} @AfterClass public void baseAfterClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend_on_test/000077500000000000000000000000001475274123300324355ustar00rootroot00000000000000PassDependsOnPassSample.java000066400000000000000000000006421475274123300377220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/depend_on_testpackage test.failedreporter.issue1297.depend_on_test; import org.testng.Assert; import org.testng.annotations.Test; public class PassDependsOnPassSample { @Test public void test1() {} @Test(dependsOnMethods = "test1") public void test2() { Assert.fail(); } @Test(dependsOnMethods = "test1") public void dependsOnTest1() {} @Test(dependsOnMethods = "test2") public void dependsOnTest2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/groups/000077500000000000000000000000001475274123300307625ustar00rootroot00000000000000GroupsFailureSample.java000066400000000000000000000005021475274123300354740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/groupspackage test.failedreporter.issue1297.groups; import org.testng.Assert; import org.testng.annotations.Test; import test.failedreporter.FailedReporterTest; public class GroupsFailureSample extends GroupsSampleBase { @Test(groups = FailedReporterTest.DEPENDENT_GROUP) public void newTest2() { Assert.fail(); } } GroupsPassSample.java000066400000000000000000000003031475274123300350120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/groupspackage test.failedreporter.issue1297.groups; import org.testng.annotations.Test; public class GroupsPassSample extends GroupsSampleBase { @Test(groups = "run") public void newTest1() {} } GroupsSampleBase.java000066400000000000000000000010751475274123300347650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/groupspackage test.failedreporter.issue1297.groups; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import test.failedreporter.FailedReporterTest; public class GroupsSampleBase { @BeforeTest(groups = FailedReporterTest.DEPENDENT_GROUP) public void baseBeforeTest() {} @BeforeClass(alwaysRun = true) public void baseBeforeClassAlwaysRun() {} @BeforeMethod public void baseBeforeMethod() {} @AfterClass public void baseAfterClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/inheritance/000077500000000000000000000000001475274123300317345ustar00rootroot00000000000000InheritanceFailureSample.java000066400000000000000000000003521475274123300374230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/inheritancepackage test.failedreporter.issue1297.inheritance; import org.testng.Assert; import org.testng.annotations.Test; public class InheritanceFailureSample extends SampleBase { @Test public void newTest2() { Assert.fail(); } } InheritancePassSample.java000066400000000000000000000002671475274123300367470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/inheritancepackage test.failedreporter.issue1297.inheritance; import org.testng.annotations.Test; public class InheritancePassSample extends SampleBase { @Test public void newTest1() {} } SampleBase.java000066400000000000000000000007051475274123300345360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/inheritancepackage test.failedreporter.issue1297.inheritance; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; public class SampleBase { @BeforeTest public void baseBeforeTest() {} @BeforeClass public void baseBeforeClass() {} @BeforeMethod public void baseBeforeMethod() {} @AfterClass public void baseAfterClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/straightforward/000077500000000000000000000000001475274123300326555ustar00rootroot00000000000000AllPassSample.java000066400000000000000000000004231475274123300361410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/straightforwardpackage test.failedreporter.issue1297.straightforward; import org.testng.annotations.*; public class AllPassSample { @BeforeClass public void beforeClassAllPassSample() {} @Test public void newTest1() {} @AfterClass public void afterClassAllPassSample() {} } FailureSample.java000066400000000000000000000006331475274123300361740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue1297/straightforwardpackage test.failedreporter.issue1297.straightforward; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class FailureSample { @BeforeClass public void beforeClassFailureSample() {} @Test public void newTest2() { Assert.fail(); } @AfterClass public void afterClassFailureSample() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue2517/000077500000000000000000000000001475274123300274375ustar00rootroot00000000000000DataProviderWithFactoryFailedReporterSample.java000066400000000000000000000011541475274123300407660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue2517package test.failedreporter.issue2517; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class DataProviderWithFactoryFailedReporterSample { private Integer data; @Factory(dataProvider = "dp") public DataProviderWithFactoryFailedReporterSample(Integer data) { this.data = data; } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {0}, new Object[] {1}, new Object[] {2}, }; } @Test public void f1() { if (data == 1) { throw new RuntimeException(); } } } DataProviderWithFactoryFailedReporterTest.java000066400000000000000000000032261475274123300404660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue2517package test.failedreporter.issue2517; import java.io.File; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.SimpleBaseTest; public class DataProviderWithFactoryFailedReporterTest extends SimpleBaseTest { private File mTempDirectory; @BeforeMethod public void setUp() { mTempDirectory = createDirInTempDir("testng-tmp-" + System.currentTimeMillis() % 1000); } @AfterMethod public void tearDown() { deleteDir(mTempDirectory); } @Test public void failedMethodWithDataProviderAndFactoryShouldHaveInvocationNumbers() { testFailedReporter( new String[] {"f1"}, "", DataProviderWithFactoryFailedReporterSample.class); } private void testFailedReporter(String[] expectedMethods, String expectedLine, Class... cls) { triggerTest(cls); runAssertions(mTempDirectory, expectedMethods, expectedLine, 1); } private void triggerTest(Class... cls) { TestNG tng = create(mTempDirectory.toPath(), cls); tng.setUseDefaultListeners(true); tng.run(); } private static void runAssertions( File outputDir, String[] expectedMethods, String expectedLine, int expected) { File failed = new File(outputDir, "testng-failed.xml"); for (String s : expectedMethods) { List resultLines = Lists.newArrayList(); grep(failed, String.format(expectedLine, s), resultLines); Assert.assertEquals(resultLines.size(), expected); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue2521/000077500000000000000000000000001475274123300274325ustar00rootroot00000000000000DataProviderWithFactoryMultiFailedReporterSample.java000066400000000000000000000013271475274123300417760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue2521package test.failedreporter.issue2521; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class DataProviderWithFactoryMultiFailedReporterSample { private Integer data; @Factory(dataProvider = "dp") public DataProviderWithFactoryMultiFailedReporterSample(Integer data) { this.data = data; } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {0}, new Object[] {1}, new Object[] {2}, }; } @Test public void f1() { if (data != 1) { throw new RuntimeException(); } } @Test public void f2() { if (data != 0) { throw new RuntimeException(); } } } DataProviderWithFactoryMultiFailedReporterTest.java000066400000000000000000000032471475274123300414770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failedreporter/issue2521package test.failedreporter.issue2521; import java.io.File; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.SimpleBaseTest; public class DataProviderWithFactoryMultiFailedReporterTest extends SimpleBaseTest { private File mTempDirectory; @BeforeMethod public void setUp() { mTempDirectory = createDirInTempDir("testng-tmp-" + System.currentTimeMillis() % 1000); } @AfterMethod public void tearDown() { deleteDir(mTempDirectory); } @Test public void multiFailedMethodWithDataProviderAndFactoryShouldHaveInvocationNumbers() { testFailedReporter( new String[] {"f1"}, "", DataProviderWithFactoryMultiFailedReporterSample.class); } private void testFailedReporter(String[] expectedMethods, String expectedLine, Class... cls) { triggerTest(cls); runAssertions(mTempDirectory, expectedMethods, expectedLine, 1); } private void triggerTest(Class... cls) { TestNG tng = create(mTempDirectory.toPath(), cls); tng.setUseDefaultListeners(true); tng.run(); } private static void runAssertions( File outputDir, String[] expectedMethods, String expectedLine, int expected) { File failed = new File(outputDir, "testng-failed.xml"); for (String s : expectedMethods) { List resultLines = Lists.newArrayList(); grep(failed, String.format(expectedLine, s), resultLines); Assert.assertEquals(resultLines.size(), expected); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/000077500000000000000000000000001475274123300245735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/Base0.java000066400000000000000000000001661475274123300263730ustar00rootroot00000000000000package test.failures; import org.testng.annotations.Test; public class Base0 { @Test public void base1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/Base1.java000066400000000000000000000003461475274123300263740ustar00rootroot00000000000000package test.failures; import org.testng.annotations.Test; public class Base1 extends Base0 { @Test public void base2() {} @Test public void failFromBase() { throw new RuntimeException("VOLUNTARILY FAILED"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/BaseFailuresTest.java000066400000000000000000000047251475274123300306530ustar00rootroot00000000000000package test.failures; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.regex.Pattern; import org.testng.Assert; import org.testng.TestNG; import org.testng.reporters.FailedReporter; import test.SimpleBaseTest; public abstract class BaseFailuresTest extends SimpleBaseTest { protected static TestNG run(TestNG result, Class[] classes, String outputDir) { result.setOutputDirectory(outputDir); result.setTestClasses(classes); result.run(); return result; } protected static boolean containsRegularExpressions(Path f, String[] strRegexps) { Pattern[] matchers = new Pattern[strRegexps.length]; boolean[] results = new boolean[strRegexps.length]; for (int i = 0; i < strRegexps.length; i++) { matchers[i] = Pattern.compile(".*" + strRegexps[i] + ".*"); results[i] = false; } try (BufferedReader br = Files.newBufferedReader(f, Charset.forName("UTF-8"))) { String line = br.readLine(); while (line != null) { for (int i = 0; i < strRegexps.length; i++) { if (matchers[i].matcher(line).matches()) { results[i] = true; } } line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); return false; } for (int i = 0; i < results.length; i++) { if (!results[i]) { throw new AssertionError("Couldn't find " + strRegexps[i]); } } return true; } protected static void verify(Path outputDir, String suiteName, String[] expected) throws IOException { Path f = outputDir.resolve(suiteName).resolve(FailedReporter.TESTNG_FAILED_XML); Assert.assertTrue(containsRegularExpressions(f, expected)); Files.walkFileTree( outputDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); Files.deleteIfExists(outputDir); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/Child.java000066400000000000000000000003351475274123300264620ustar00rootroot00000000000000package test.failures; import org.testng.annotations.Test; public class Child extends Base1 { @Test public void pass() {} @Test public void fail() { throw new RuntimeException("VOLUNTARILY FAILED"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/DependentTest.java000066400000000000000000000004001475274123300301760ustar00rootroot00000000000000package test.failures; import org.testng.annotations.Test; public class DependentTest { @Test public void f1() {} @Test( dependsOnMethods = {"f1"}, dependsOnGroups = {"f"}) public void f2() { throw new RuntimeException(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/FailuresTest.java000066400000000000000000000072141475274123300300540ustar00rootroot00000000000000package test.failures; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.reporters.FailedReporter; import org.testng.xml.XmlSuite; import test.TestHelper; import test.failures.issue1930.SimpleCliStatus; import test.failures.issue1930.TestClassSample; public class FailuresTest extends BaseFailuresTest { private static final String suiteName = "TmpSuite"; private static final String[] expected = new String[] { "", "", "", }; @Test public void shouldIncludeFailedMethodsFromBaseClass() throws IOException { Path tempDirectory = Files.createTempDirectory("temp-testng-"); XmlSuite suite = createXmlSuite(suiteName, "TmpTest", Child.class); TestNG tng = create(tempDirectory, suite); tng.addListener(new FailedReporter()); tng.run(); verify(tempDirectory, suiteName, expected); } private static final String[] expectedIncludes = new String[] {"", ""}; @Test(enabled = false) public void shouldIncludeDependentMethods() throws IOException { Path tempDirectory = Files.createTempDirectory("temp-testng-"); XmlSuite suite = TestHelper.createSuite("test.failures.DependentTest", suiteName); TestNG tng = TestHelper.createTestNG(suite); tng.run(); verify(tempDirectory, suiteName, expectedIncludes); } private static final String[] expectedParameter = new String[] {""}; @Test(enabled = false) public void shouldIncludeParameters() throws IOException { Path tempDirectory = Files.createTempDirectory("temp-testng-"); XmlSuite suite = TestHelper.createSuite("test.failures.Child", suiteName); Map params = new HashMap<>(); params.put("first-name", "Cedric"); params.put("last-name", "Beust"); suite.setParameters(params); TestNG tng = TestHelper.createTestNG(suite); tng.run(); verify(tempDirectory, suiteName, expectedParameter); } @Test(description = "GITHUB-1930") public void testToEnsureThatWeRunOnlyFailedIterationsFromBaseClass() { File outputDir = createDirInTempDir("testng-tmp-" + System.currentTimeMillis() % 1000); TestNG testng = create(TestClassSample.class); testng.setOutputDirectory(outputDir.getAbsolutePath()); testng.setUseDefaultListeners(true); testng.run(); String file = outputDir.getAbsolutePath() + File.separator + FailedReporter.TESTNG_FAILED_XML; // First iteration of running failed tests. runIteration(outputDir, file); // Second iteration of running failed tests. runIteration(outputDir, file); } private static void runIteration(File outputDir, String file) { SimpleCliStatus listener = new SimpleCliStatus(); TestNG testng = create(); testng.setTestSuites(Collections.singletonList(file)); testng.setOutputDirectory(outputDir.getAbsolutePath()); testng.setUseDefaultListeners(true); testng.addListener(listener); testng.run(); Map> expected = Maps.newHashMap(); expected.put("testPrimeNumberChecker", Arrays.asList(3, 4)); expected.put("testNumberEquality", Arrays.asList(2, 3)); assertThat(listener.getFailedTests()).containsAllEntriesOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/issue1930/000077500000000000000000000000001475274123300262405ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/issue1930/PrimeNumberChecker.java000066400000000000000000000006151475274123300326170ustar00rootroot00000000000000package test.failures.issue1930; public class PrimeNumberChecker { public boolean validate(int number) { if (number == 2 || number == 3) { return true; } if (number % 2 == 0) { return false; } int sqrt = (int) Math.sqrt(number) + 1; for (int i = 3; i < sqrt; i += 2) { if (number % i == 0) { return false; } } return true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/issue1930/SimpleCliStatus.java000066400000000000000000000012661475274123300321750ustar00rootroot00000000000000package test.failures.issue1930; import java.util.List; import java.util.Map; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.collections.Maps; public class SimpleCliStatus implements ITestListener { private Map> failedTests = Maps.newHashMap(); public Map> getFailedTests() { return failedTests; } @Override public void onFinish(ITestContext context) { context .getFailedTests() .getAllResults() .forEach( result -> failedTests.put( result.getMethod().getMethodName(), result.getMethod().getInvocationNumbers())); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/issue1930/TestBase.java000066400000000000000000000006761475274123300306260ustar00rootroot00000000000000package test.failures.issue1930; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestBase { @Test(dataProvider = "test2") public void testNumberEquality(Integer i1, Integer i2) { Assert.assertEquals(i1, i2); } @DataProvider(name = "test2") public static Object[][] numbers() { return new Object[][] {{2, 2}, {6, 6}, {19, 18}, {22, 21}, {23, 23}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/failures/issue1930/TestClassSample.java000066400000000000000000000013631475274123300321550ustar00rootroot00000000000000package test.failures.issue1930; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestClassSample extends TestBase { private PrimeNumberChecker primeNumberChecker; @BeforeMethod public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } @DataProvider(name = "test1") public static Object[][] primeNumbers() { return new Object[][] {{2, true}, {6, false}, {19, true}, {22, true}, {23, false}}; } @Test(dataProvider = "test1") public void testPrimeNumberChecker(int inputNumber, boolean expectedResult) { Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/000077500000000000000000000000001475274123300245605ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/BaseClass.java000066400000000000000000000014341475274123300272650ustar00rootroot00000000000000package test.github1336; import java.util.Random; import java.util.concurrent.TimeUnit; import org.testng.Assert; import org.testng.annotations.BeforeClass; public class BaseClass { private FakeDriver driver; @BeforeClass public void beforeClass() { driver = new FakeDriver(); } private FakeDriver getDriver() { return driver; } public static class FakeDriver { private String url; public void get(String url) { this.url = url; } String getCurrentUrl() { try { TimeUnit.SECONDS.sleep(new Random().nextInt(10)); return url; } catch (InterruptedException e) { return url; } } } void runTest(String url) { getDriver().get(url); Assert.assertEquals(getDriver().getCurrentUrl(), url); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/TestNG1.java000066400000000000000000000006371475274123300266560ustar00rootroot00000000000000package test.github1336; import org.testng.annotations.Test; public class TestNG1 extends BaseClass { @Test(priority = 1) public void test1TestNG1() { runTest("https://testng.org/doc/download.html"); } @Test(priority = 2) public void test2TestNG1() { runTest("https://www3.lenovo.com/in/en/"); } @Test(priority = 3) public void test3TestNG1() { runTest("https://github.com/"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/TestNG1NoPriority.java000066400000000000000000000005771475274123300307200ustar00rootroot00000000000000package test.github1336; import org.testng.annotations.Test; public class TestNG1NoPriority extends BaseClass { @Test public void test1TestNG1() { runTest("https://testng.org/doc/download.html"); } @Test public void test2TestNG1() { runTest("https://www3.lenovo.com/in/en/"); } @Test public void test3TestNG1() { runTest("https://github.com/"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/TestNG2.java000066400000000000000000000006371475274123300266570ustar00rootroot00000000000000package test.github1336; import org.testng.annotations.Test; public class TestNG2 extends BaseClass { @Test(priority = 1) public void test1TestNG2() { runTest("https://testng.org/doc/download.html"); } @Test(priority = 2) public void test2TestNG2() { runTest("https://www3.lenovo.com/in/en/"); } @Test(priority = 3) public void test3TestNG2() { runTest("https://github.com/"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/TestNG2NoPriority.java000066400000000000000000000005771475274123300307210ustar00rootroot00000000000000package test.github1336; import org.testng.annotations.Test; public class TestNG2NoPriority extends BaseClass { @Test public void test1TestNG2() { runTest("https://testng.org/doc/download.html"); } @Test public void test2TestNG2() { runTest("https://www3.lenovo.com/in/en/"); } @Test public void test3TestNG2() { runTest("https://github.com/"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/TestNG3.java000066400000000000000000000006371475274123300266600ustar00rootroot00000000000000package test.github1336; import org.testng.annotations.Test; public class TestNG3 extends BaseClass { @Test(priority = 1) public void test1TestNG3() { runTest("https://testng.org/doc/download.html"); } @Test(priority = 2) public void test2TestNG3() { runTest("https://www3.lenovo.com/in/en/"); } @Test(priority = 3) public void test3TestNG3() { runTest("https://github.com/"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1336/TestNG3NoPriority.java000066400000000000000000000005771475274123300307220ustar00rootroot00000000000000package test.github1336; import org.testng.annotations.Test; public class TestNG3NoPriority extends BaseClass { @Test public void test1TestNG3() { runTest("https://testng.org/doc/download.html"); } @Test public void test2TestNG3() { runTest("https://www3.lenovo.com/in/en/"); } @Test public void test3TestNG3() { runTest("https://github.com/"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1362/000077500000000000000000000000001475274123300245575ustar00rootroot00000000000000AfterGroupsTestInvolvingInterceptors.java000066400000000000000000000025471475274123300347520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1362package test.github1362; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class AfterGroupsTestInvolvingInterceptors extends SimpleBaseTest { @Test public void testMethod() { runTests(new LocalMethodInterceptor(), "setup", "test1", "test3", "clear"); } @Test public void testMethodWithoutInterceptor() { runTests(null, "setup", "test1", "test2", "test3", "clear"); } private void runTests(ITestNGListener interceptor, String... names) { List expected = Arrays.asList(names); XmlSuite xmlsuite = createXmlSuite("suite", "test", TestSample.class); xmlsuite.getTests().get(0).setIncludedGroups(Collections.singletonList("exTests")); TestNG testng = create(xmlsuite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); if (interceptor != null) { testng.addListener(interceptor); } testng.run(); for (String each : listener.getInvokedMethodNames()) { assertTrue( expected.contains(each), each + " not found in expected invocation methods " + expected); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1362/LocalMethodInterceptor.java000066400000000000000000000011651475274123300320370ustar00rootroot00000000000000package test.github1362; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.collections.Lists; public class LocalMethodInterceptor implements IMethodInterceptor { @Override public List intercept(List methods, ITestContext context) { List methodsToReturn = Lists.newArrayList(); for (IMethodInstance method : methods) { if (!method.getMethod().getMethodName().equals("test2")) { methodsToReturn.add(method); } } return methodsToReturn; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1362/TestSample.java000066400000000000000000000011561475274123300275060ustar00rootroot00000000000000package test.github1362; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; public class TestSample { @BeforeGroups(groups = {"exTests"}) public void setup() {} @Test(groups = {"exTests"}) public void test1() { Assert.assertTrue(true, "test1"); } @Test(groups = {"exTests"}) public void test2() { Assert.assertTrue(true, "test2"); } @Test(groups = {"exTests"}) public void test3() { Assert.assertTrue(true, "test3"); } @AfterGroups(groups = {"exTests"}) public void clear() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1405/000077500000000000000000000000001475274123300245555ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1405/JUnitTestClassSample.java000066400000000000000000000001761475274123300314450ustar00rootroot00000000000000package test.github1405; import org.junit.Test; public class JUnitTestClassSample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1405/TestClassSample.java000066400000000000000000000002611475274123300304660ustar00rootroot00000000000000package test.github1405; import org.testng.annotations.Test; @Test public class TestClassSample { public static void main(String[] args) {} public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1405/TestExclusionOfMainMethod.java000066400000000000000000000013001475274123300324560ustar00rootroot00000000000000package test.github1405; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class TestExclusionOfMainMethod extends SimpleBaseTest { @Test public void testMainMethodExclusion() { TestNG tng = create(TestClassSample.class); tng.run(); Assert.assertEquals(tng.getStatus(), 0); } @Test public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); TestNG tng = create(xmlSuite); tng.run(); Assert.assertEquals(tng.getStatus(), 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1417/000077500000000000000000000000001475274123300245605ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1417/AnotherTestClassSample.java000066400000000000000000000017231475274123300320160ustar00rootroot00000000000000package test.github1417; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class AnotherTestClassSample { private static AnotherTestClassSample instance; private String browsername; public AnotherTestClassSample() { setInstance(this); } private void setInstance(AnotherTestClassSample obj) { instance = obj; } public static AnotherTestClassSample getInstance() { return instance; } String getBrowsername() { return browsername; } @Parameters({"browsername"}) @BeforeClass public void beforeClass(String browsername) { this.browsername = browsername; } @Parameters({"browsername"}) @AfterClass public void afterClass(String browsername) { this.browsername = browsername; } @Test public void testMethod() { Assert.assertEquals("chrome", browsername); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1417/TestClassSample.java000066400000000000000000000007171475274123300304770ustar00rootroot00000000000000package test.github1417; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class TestClassSample { private String browsername; @Parameters({"browsername"}) @BeforeClass public void beforeClass(String browsername) { this.browsername = browsername; } @Test public void testMethod() { Assert.assertEquals("firefox", browsername); } } TestParamsInjectionInBeforeClass.java000066400000000000000000000014751475274123300337010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1417package test.github1417; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; public class TestParamsInjectionInBeforeClass { @Test public void testMethod() { String suite = "src/test/resources/parametertest/1417.xml"; TestNG testNG = new TestNG(); testNG.setTestSuites(Collections.singletonList(suite)); testNG.run(); Assert.assertFalse(testNG.hasFailure()); Assert.assertFalse(testNG.hasSkip()); Assert.assertEquals(AnotherTestClassSample.getInstance().getBrowsername(), "chrome"); List actual = YetAnotherTestClassSample.getInstance().getBrowsers(); Assert.assertEquals(actual.size(), 2); Assert.assertEquals(actual, Arrays.asList("safari", "safari")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1417/YetAnotherTestClassSample.java000066400000000000000000000020411475274123300324720ustar00rootroot00000000000000package test.github1417; import com.beust.jcommander.internal.Lists; import java.util.List; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class YetAnotherTestClassSample { private static YetAnotherTestClassSample instance; private List browsers = Lists.newArrayList(); public YetAnotherTestClassSample() { setInstance(this); } private void setInstance(YetAnotherTestClassSample obj) { instance = obj; } public static YetAnotherTestClassSample getInstance() { return instance; } @Parameters({"browsername"}) @BeforeClass public void beforeClass(String browser) { browsers.add(browser); } @Test public void testMethod() { Assert.assertFalse(browsers.isEmpty()); } @Parameters({"browsername"}) @AfterClass public void afterClass(String browser) { browsers.add(browser); } List getBrowsers() { return browsers; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1461/000077500000000000000000000000001475274123300245575ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1461/MemoryLeakTestNg.java000066400000000000000000000042571475274123300306240ustar00rootroot00000000000000package test.github1461; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.log4testng.Logger; /** * This class reproduces a memory leak problem when running TestNG tests. The same (memory behavior * will be shown when running this test as normal TestNG test (e.g. using Intellij) * *

See https://github.com/cbeust/testng/issues/1461 */ public class MemoryLeakTestNg { private static final Logger log = Logger.getLogger(MemoryLeakTestNg.class); @Test(timeOut = 10_000) public void testMemoryLeak() throws Exception { // we run the test programmatically runTest(); // lets wait for garbage collection waitForAllObjectsDestructed(); } private static void waitForAllObjectsDestructed() throws InterruptedException { while (true) { log.debug("waiting for clean up..."); // enforce a full gc System.gc(); // check if there are still instances of our test class if (MyTestClassWithGlobalReferenceCounterSample.currentNumberOfMyTestObjects == 0) { // if we reach this point, all test instances are gone, // ... however this never happens ... break; } // let's wait 1 seconds and try again ... Thread.sleep(1_000); log.debug( "[" + MyTestClassWithGlobalReferenceCounterSample.currentNumberOfMyTestObjects + "] test object(s) still exist."); } } private static void runTest() { // create TestNG class TestNG testng = new TestNG() { @Override @SuppressWarnings("deprecation") protected void finalize() { // it seems that this object will never be finalized !!! log.debug("TestNG finalized"); } }; // and set a test (which also will never be finalized ... see later) testng.setTestClasses( new Class[] { MyTestClassWithGlobalReferenceCounterSample.class, }); // lets run the test testng.run(); // At this point the test run through and we expect both instances // - testng and // - the test object of type (MyTest) // will be garbage collected when leaving this method // ... } } MyTestClassWithGlobalReferenceCounterSample.java000066400000000000000000000020031475274123300360470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1461package test.github1461; import org.testng.annotations.Test; import org.testng.log4testng.Logger; /** we create a test NG class here, which has a global counter, counting all instances. */ public class MyTestClassWithGlobalReferenceCounterSample { private static final Logger log = Logger.getLogger(MyTestClassWithGlobalReferenceCounterSample.class); /** global counter that keeps track on how many objects are currently on the heap */ public static int currentNumberOfMyTestObjects = 0; public MyTestClassWithGlobalReferenceCounterSample() { log.debug("constructor"); // increase the counter ++currentNumberOfMyTestObjects; } @Test public void aTestMethod1() { log.debug("test method 1"); } @Test public void aTestMethod2() { log.debug("test method 2"); } @Override @SuppressWarnings("deprecation") protected void finalize() { log.debug("finalize"); // this will be called when this object is removed from the heap --currentNumberOfMyTestObjects; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490/000077500000000000000000000000001475274123300245615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490/DataProviderHouse.java000066400000000000000000000014361475274123300310200ustar00rootroot00000000000000package test.github1490; import org.testng.annotations.DataProvider; import org.testng.internal.ConstructorOrMethod; public class DataProviderHouse { @DataProvider(name = "cookie-master") public static Object[][] cookies(ConstructorOrMethod method) { TestInfo value; if (method.getConstructor() != null) { value = (TestInfo) method.getConstructor().getAnnotation(TestInfo.class); } else { value = method.getMethod().getAnnotation(TestInfo.class); } String name = value.name(); if ("glutton".equalsIgnoreCase(name)) { return new Object[][] {{"oreo", 200}}; } if ("nibbler".equalsIgnoreCase(name)) { return new Object[][] {{"marie-gold", 10}}; } return new Object[][] { {"oreo", 200}, {"marie-gold", 10} }; } } FactoryPoweredDataProviderWithListenerAnnotationSample.java000066400000000000000000000013211475274123300403430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.github1490.LocalDataProviderListener; @Listeners(LocalDataProviderListener.class) public class FactoryPoweredDataProviderWithListenerAnnotationSample { private final int i; @Factory(dataProvider = "dp") public FactoryPoweredDataProviderWithListenerAnnotationSample(int i) { this.i = i; } @Test public void testMethod() { Assert.assertTrue(i > 0); } @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] {{1}, {2}}; } } FactoryPoweredDataProviderWithoutListenerAnnotationSample.java000066400000000000000000000011001475274123300410660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class FactoryPoweredDataProviderWithoutListenerAnnotationSample { private int i; @Factory(dataProvider = "dp") public FactoryPoweredDataProviderWithoutListenerAnnotationSample(int i) { this.i = i; } @Test public void testMethod() { Assert.assertTrue(i > 0); } @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] {{1}, {2}}; } } InstanceBasedDataProviderWithListenerAnnotationSample.java000066400000000000000000000010341475274123300401120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.github1490.DataProviderInfoProvider; @Listeners(DataProviderInfoProvider.class) public class InstanceBasedDataProviderWithListenerAnnotationSample { @Test(dataProvider = "getData") public void testMethod(int i) { Assert.assertTrue(i > 0); } @DataProvider public Object[][] getData() { return new Object[][] {{1}, {2}}; } } SimpleDataProviderWithListenerAnnotationSample.java000066400000000000000000000010271475274123300366420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.github1490.LocalDataProviderListener; @Listeners(LocalDataProviderListener.class) public class SimpleDataProviderWithListenerAnnotationSample { @Test(dataProvider = "getData") public void testMethod(int i) { Assert.assertTrue(i > 0); } @DataProvider public Object[][] getData() { return new Object[][] {{1}, {2}}; } } SimpleDataProviderWithListenerAnnotationSample1.java000066400000000000000000000011201475274123300367150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.github1490.LocalDataProviderListener; @Listeners(SimpleDataProviderWithListenerAnnotationSample1.class) public class SimpleDataProviderWithListenerAnnotationSample1 extends LocalDataProviderListener { @Test(dataProvider = "getData") public void testMethod(int i) { Assert.assertTrue(i > 0); } @DataProvider public Object[][] getData() { return new Object[][] {{1}, {2}}; } } SimpleDataProviderWithoutListenerAnnotationSample.java000066400000000000000000000006111475274123300373700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SimpleDataProviderWithoutListenerAnnotationSample { @Test(dataProvider = "getData") public void testMethod(int i) { Assert.assertTrue(i > 0); } @DataProvider public Object[][] getData() { return new Object[][] {{1}, {2}}; } } StaticDataProviderWithListenerAnnotationSample.java000066400000000000000000000012751475274123300366450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.github1490.DataProviderInfoProvider; @Listeners(DataProviderInfoProvider.class) public class StaticDataProviderWithListenerAnnotationSample { private int i; @Factory(dataProvider = "getStaticData") public StaticDataProviderWithListenerAnnotationSample(int i) { this.i = i; } @Test public void testMethod() { Assert.assertTrue(i > 0); } @DataProvider public static Object[][] getStaticData() { return new Object[][] {{1}, {2}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490/TestInfo.java000066400000000000000000000005551475274123300271640ustar00rootroot00000000000000package test.github1490; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD, CONSTRUCTOR}) public @interface TestInfo { String name() default ""; } TwoFactoriesShareSameDataProviderSampleOne.java000066400000000000000000000012151475274123300356570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class TwoFactoriesShareSameDataProviderSampleOne { private final String cookieName; private final int count; @TestInfo(name = "glutton") @Factory(dataProvider = "cookie-master", dataProviderClass = DataProviderHouse.class) public TwoFactoriesShareSameDataProviderSampleOne(String cookieName, int count) { this.cookieName = cookieName; this.count = count; } @Test public void testHowMuchMasterShifuAte() { Assert.assertEquals("oreo", cookieName); Assert.assertTrue(count > 100); } } TwoFactoriesShareSameDataProviderSampleTwo.java000066400000000000000000000012231475274123300357060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class TwoFactoriesShareSameDataProviderSampleTwo { private final String cookieName; private final int count; @TestInfo(name = "nibbler") @Factory(dataProvider = "cookie-master", dataProviderClass = DataProviderHouse.class) public TwoFactoriesShareSameDataProviderSampleTwo(String cookieName, int count) { this.cookieName = cookieName; this.count = count; } @Test public void testHowMuchMasterShifuAte() { Assert.assertEquals("marie-gold", cookieName); Assert.assertTrue(count < 100); } } TwoTestMethodsShareSameDataProviderSample.java000066400000000000000000000015141475274123300355430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.internal.ConstructorOrMethod; public class TwoTestMethodsShareSameDataProviderSample { @TestInfo(name = "glutton") @Test(dataProvider = "cookie-master") public void testHowMuchPoAte(String cookieName, int count) { Assert.assertEquals("oreo", cookieName); Assert.assertTrue(count > 100); } @TestInfo(name = "nibbler") @Test(dataProvider = "cookie-master") public void testHowMuchMasterShifuAte(String cookieName, int count) { Assert.assertEquals("marie-gold", cookieName); Assert.assertTrue(count < 100); } @DataProvider(name = "cookie-master") public Object[][] getCookies(ConstructorOrMethod method) { return DataProviderHouse.cookies(method); } } TwoTestMethodsShareSameDataProviderSampleTwo.java000066400000000000000000000012651475274123300362400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490package test.github1490; import org.testng.Assert; import org.testng.annotations.Test; public class TwoTestMethodsShareSameDataProviderSampleTwo { @TestInfo(name = "glutton") @Test(dataProvider = "cookie-master", dataProviderClass = DataProviderHouse.class) public void testHowMuchPoAte(String cookieName, int count) { Assert.assertEquals("oreo", cookieName); Assert.assertTrue(count > 100); } @TestInfo(name = "nibbler") @Test(dataProvider = "cookie-master", dataProviderClass = DataProviderHouse.class) public void testHowMuchMasterShifuAte(String cookieName, int count) { Assert.assertEquals("marie-gold", cookieName); Assert.assertTrue(count < 100); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github1490/VerifyDataProviderListener.java000066400000000000000000000144361475274123300327130ustar00rootroot00000000000000package test.github1490; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.IDataProviderMethod; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import test.listeners.github1490.DataProviderInfoProvider; import test.listeners.github1490.InstanceAwareLocalDataProviderListener; import test.listeners.github1490.LocalDataProviderListener; public class VerifyDataProviderListener extends SimpleBaseTest { @Test public void testInstanceBasedDataProviderInformation() { TestNG tng = create(InstanceBasedDataProviderWithListenerAnnotationSample.class); tng.run(); IDataProviderMethod before = DataProviderInfoProvider.before; IDataProviderMethod after = DataProviderInfoProvider.after; Assert.assertEquals(before, after); Assert.assertEquals(before.getInstance(), after.getInstance()); Assert.assertEquals(before.getMethod().getName(), "getData"); } @Test public void testStaticDataProviderInformation() { TestNG tng = create(StaticDataProviderWithListenerAnnotationSample.class); tng.run(); IDataProviderMethod before = DataProviderInfoProvider.before; IDataProviderMethod after = DataProviderInfoProvider.after; Assert.assertEquals(before, after); Assert.assertNull(before.getInstance()); Assert.assertEquals(before.getMethod().getName(), "getStaticData"); } @Test public void testMultipleTestMethodsShareSameDataProvider() { Class clazz = TwoTestMethodsShareSameDataProviderSample.class; runTest(1, clazz); String[] prefixes = {"before", "after"}; String[] methods = {"testHowMuchMasterShifuAte", "testHowMuchPoAte"}; List expected = new ArrayList<>(); for (String prefix : prefixes) { for (String method : methods) { String txt = prefix + ":" + clazz.getName() + "." + method; expected.add(txt); } } assertThat(InstanceAwareLocalDataProviderListener.messages).containsAll(expected); } @Test public void testMultipleFactoriesShareSameDataProvider() { Class[] classes = { TwoFactoriesShareSameDataProviderSampleOne.class, TwoFactoriesShareSameDataProviderSampleTwo.class }; runTest(0, classes); } @Test public void testMultipleMethodsFactoriesShareSampleDataProvider() { Class[] classes = { TwoFactoriesShareSameDataProviderSampleOne.class, TwoFactoriesShareSameDataProviderSampleTwo.class, TwoTestMethodsShareSameDataProviderSampleTwo.class }; runTest(1, classes); } @Test public void testSimpleDataProviderWithListenerAnnotation() { final String prefix = ":" + SimpleDataProviderWithListenerAnnotationSample.class.getName() + ".testMethod"; runTest(prefix, SimpleDataProviderWithListenerAnnotationSample.class, true); } @Test public void testFactoryPoweredDataProviderWithListenerAnnotation() { final String prefix = ":" + FactoryPoweredDataProviderWithListenerAnnotationSample.class.getName(); runTest(prefix, FactoryPoweredDataProviderWithListenerAnnotationSample.class, true); } @Test public void testSimpleDataProviderWithoutListenerAnnotation() { final String prefix = ":" + SimpleDataProviderWithoutListenerAnnotationSample.class.getName() + ".testMethod"; runTest(prefix, SimpleDataProviderWithoutListenerAnnotationSample.class, false); } @Test public void testFactoryPoweredDataProviderWithoutListenerAnnotation() { final String prefix = ":" + FactoryPoweredDataProviderWithoutListenerAnnotationSample.class.getName(); runTest(prefix, FactoryPoweredDataProviderWithoutListenerAnnotationSample.class, false); } @Test public void testSimpleDataProviderWithListenerViaSuiteXml() { final String prefix = ":" + SimpleDataProviderWithoutListenerAnnotationSample.class.getName() + ".testMethod"; runTestWithListenerViaSuiteXml(prefix, SimpleDataProviderWithoutListenerAnnotationSample.class); } @Test public void testFactoryPoweredDataProviderWithListenerViaSuiteXml() { final String prefix = ":" + FactoryPoweredDataProviderWithoutListenerAnnotationSample.class.getName(); runTestWithListenerViaSuiteXml( prefix, FactoryPoweredDataProviderWithoutListenerAnnotationSample.class); } @Test public void testSimpleDataProviderWithListenerAnnotationAndInvolvingInheritance() { final String prefix = ":" + SimpleDataProviderWithListenerAnnotationSample1.class.getName() + ".testMethod"; TestNG tng = create(SimpleDataProviderWithListenerAnnotationSample1.class); tng.run(); assertThat(LocalDataProviderListener.messages) .containsExactlyElementsOf(Arrays.asList("before" + prefix, "after" + prefix)); } @AfterMethod public void resetListenerMessages() { LocalDataProviderListener.messages.clear(); } private static void runTestWithListenerViaSuiteXml(String prefix, Class clazz) { XmlSuite xmlSuite = createXmlSuite("SampleSuite"); XmlTest xmlTest = createXmlTest(xmlSuite, "SampleTest"); createXmlClass(xmlTest, clazz); xmlSuite.addListener(LocalDataProviderListener.class.getName()); TestNG tng = create(xmlSuite); tng.run(); assertThat(LocalDataProviderListener.messages) .containsExactlyElementsOf(Arrays.asList("before" + prefix, "after" + prefix)); } private static void runTest(String prefix, Class clazz, boolean hasListenerAnnotation) { TestNG tng = create(clazz); if (!hasListenerAnnotation) { tng.addListener(new LocalDataProviderListener()); } tng.run(); assertThat(LocalDataProviderListener.messages) .containsExactlyElementsOf(Arrays.asList("before" + prefix, "after" + prefix)); } private static void runTest(int expected, Class... classes) { TestNG tng = create(classes); tng.addListener(new InstanceAwareLocalDataProviderListener()); tng.run(); assertThat(InstanceAwareLocalDataProviderListener.instanceCollectionBeforeExecution) .size() .isEqualTo(expected); assertThat(InstanceAwareLocalDataProviderListener.instanceCollectionAfterExecution) .size() .isEqualTo(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github765/000077500000000000000000000000001475274123300245055ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github765/DuplicateCallsSample.java000066400000000000000000000007621475274123300314100ustar00rootroot00000000000000package test.github765; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DuplicateCallsSample extends TestTemplate { private int i = 0; @Test(dataProvider = "testParameters") public void callExecuteTest(Integer testParameters) { Assert.assertTrue(testParameters > 0); } @DataProvider(name = "testParameters") public Object[][] getOnboardingTestParameters() { return new Object[][] {{4}}; } } ExcludeSyntheticMethodsFromTemplateCallsTest.java000066400000000000000000000013011475274123300362330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github765package test.github765; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class ExcludeSyntheticMethodsFromTemplateCallsTest extends SimpleBaseTest { @Test public void testMethod() { TestNG testng = create(DuplicateCallsSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); List methods = listener.getMethodsForTestClass(DuplicateCallsSample.class); Assert.assertEquals(methods.size(), 1); Assert.assertEquals(methods.get(0), "callExecuteTest"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github765/TestTemplate.java000066400000000000000000000002171475274123300277630ustar00rootroot00000000000000package test.github765; public abstract class TestTemplate { public abstract void callExecuteTest(T testParameters) throws Exception; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github799/000077500000000000000000000000001475274123300245145ustar00rootroot00000000000000EnsureInstancesAreOrderedViaFactories.java000066400000000000000000000034161475274123300346520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github799package test.github799; import java.util.List; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import test.SimpleBaseTest; public class EnsureInstancesAreOrderedViaFactories extends SimpleBaseTest { @Test public void testMethod() { System.setProperty("testng.order", "none"); runTest(TestSample.class, "1", "2", "3", "4"); } @Test public void randomOrderTestMethod() { System.setProperty("testng.order", "none"); runTest(ReverseOrderTestSample.class, "4", "1", "3", "2"); } @Test public void methodsOrderTest() { System.setProperty("testng.order", "methods"); runTest(MethodsTestSample.class, "android", "angry", "birds"); } @Test public void testInstancesOrder() { System.setProperty("testng.order", "instances"); runTest(InstanceTestSample.class, "Master Oogway:90", "Master Shifu:50"); } private void runTest(Class clazz, String... expected) { TestNG tng = create(clazz); OrderEavesdropper listener = new OrderEavesdropper(); tng.addListener(listener); tng.run(); for (int i = 0; i < expected.length; i++) { String actual = listener.messages.get(i); Assert.assertEquals(actual, expected[i]); } } public static class OrderEavesdropper implements IInvokedMethodListener { List messages = Lists.newArrayList(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { messages.addAll(Reporter.getOutput(testResult)); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github799/InstanceTestSample.java000066400000000000000000000013641475274123300311310ustar00rootroot00000000000000package test.github799; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class InstanceTestSample { private String name; private int age; @Factory(dataProvider = "dp") public InstanceTestSample(String name, int age) { this.name = name; this.age = age; } @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] { {"Master Shifu", 50}, {"Master Oogway", 90} }; } @Test public void testMethod() { Reporter.log(toString()); Assert.assertNotNull(this.name); } @Override public String toString() { return name + ":" + age; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github799/MethodsTestSample.java000066400000000000000000000013221475274123300307620ustar00rootroot00000000000000package test.github799; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.Test; public class MethodsTestSample { @Test public void angry() { String methodName = Reporter.getCurrentTestResult().getMethod().getMethodName(); Reporter.log(methodName); Assert.assertNotNull(methodName); } @Test public void birds() { String methodName = Reporter.getCurrentTestResult().getMethod().getMethodName(); Reporter.log(methodName); Assert.assertNotNull(methodName); } @Test public void android() { String methodName = Reporter.getCurrentTestResult().getMethod().getMethodName(); Reporter.log(methodName); Assert.assertNotNull(methodName); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github799/ReverseOrderTestSample.java000066400000000000000000000010551475274123300317710ustar00rootroot00000000000000package test.github799; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ReverseOrderTestSample { int num; @Factory(dataProvider = "data") public ReverseOrderTestSample(int n) { num = n; } @DataProvider public static Object[][] data() { return new Object[][] {{4}, {1}, {3}, {2}}; } @Test public void test() { Reporter.log(Integer.toString(num)); Assert.assertTrue(num > 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/github799/TestSample.java000066400000000000000000000010251475274123300274360ustar00rootroot00000000000000package test.github799; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class TestSample { int num; @Factory(dataProvider = "data") public TestSample(int n) { num = n; } @DataProvider public static Object[][] data() { return new Object[][] {{1}, {2}, {3}, {4}}; } @Test public void test() { Reporter.log(Integer.toString(num)); Assert.assertTrue(num > 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/graph/000077500000000000000000000000001475274123300240625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/graph/GraphVisualiserTest.java000066400000000000000000000021671475274123300307030ustar00rootroot00000000000000package test.graph; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class GraphVisualiserTest extends SimpleBaseTest { @Test(dataProvider = "dp") public void testVisualiserInvocation(Class testClass, boolean injectListener) { TestNG testng = create(); XmlSuite suite = createXmlSuite("test_suite"); LocalVisualiser visualiser = null; if (injectListener) { visualiser = new LocalVisualiser(); testng.addListener(visualiser); } createXmlTest(suite, "test", testClass); testng.setXmlSuites(Collections.singletonList(suite)); testng.run(); if (visualiser == null) { visualiser = LocalVisualiser.getInstance(); } assertThat(visualiser.getDefinitions()).hasSize(2); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { {TestSampleWithListener.class, true}, {TestSampleWithoutListener.class, false} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/graph/LocalVisualiser.java000066400000000000000000000013201475274123300300220ustar00rootroot00000000000000package test.graph; import java.util.List; import org.testng.IExecutionVisualiser; import org.testng.collections.Lists; public class LocalVisualiser implements IExecutionVisualiser { private List definitions = Lists.newArrayList(); private static LocalVisualiser instance; public LocalVisualiser() { setInstance(this); } private static void setInstance(LocalVisualiser visualiser) { instance = visualiser; } public static LocalVisualiser getInstance() { return instance; } @Override public void consumeDotDefinition(String dotDefinition) { definitions.add(dotDefinition.replaceAll("\\n", "")); } public List getDefinitions() { return definitions; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/graph/TestSampleWithListener.java000066400000000000000000000004171475274123300313520ustar00rootroot00000000000000package test.graph; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(LocalVisualiser.class) public class TestSampleWithListener { @Test public void parent() {} @Test(dependsOnMethods = "parent") public void child() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/graph/TestSampleWithoutListener.java000066400000000000000000000003071475274123300321000ustar00rootroot00000000000000package test.graph; import org.testng.annotations.Test; public class TestSampleWithoutListener { @Test public void parent() {} @Test(dependsOnMethods = "parent") public void child() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupbug/000077500000000000000000000000001475274123300246135ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupbug/GroupBugTest.java000066400000000000000000000016301475274123300300500ustar00rootroot00000000000000package test.groupbug; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class GroupBugTest extends SimpleBaseTest { @Test( description = "Comment out dependsOnGroups in ITCaseOne will fix the ordering, that's the bug") public void shouldOrderByClass() { TestNG tng = create(ITCaseOne.class, ITCaseTwo.class); tng.setGroupByInstances(true); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getInvokedMethodNames()) .containsExactly( "beforeClassOne", "one1", "one2", "afterClassOne", "beforeClassTwo", "two1", "two2", "afterClassTwo"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupbug/ITCaseOne.java000066400000000000000000000014731475274123300272350ustar00rootroot00000000000000package test.groupbug; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; public class ITCaseOne { private static final Logger log = Logger.getLogger(ITCaseOne.class); @BeforeClass public void beforeClassOne() { log.debug("RUN " + getClass() + ".beforeClass()"); } @AfterClass(alwaysRun = true) public void afterClassOne() { log.debug("RUN " + getClass() + ".afterClass()"); } @Test(groups = "std-one") public void one1() { log.debug("RUN " + getClass() + ".one1()"); } /** Commenting out dependsOnGroups fixes the ordering, that's the bug. */ @Test(groups = "logic-one", dependsOnGroups = "std-one") public void one2() { log.debug("RUN " + getClass() + ".one2()"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupbug/ITCaseTwo.java000066400000000000000000000013571475274123300272660ustar00rootroot00000000000000package test.groupbug; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; public class ITCaseTwo { private static final Logger log = Logger.getLogger(ITCaseTwo.class); @BeforeClass public void beforeClassTwo() { log.debug("RUN " + getClass() + ".beforeClass()"); } @AfterClass(alwaysRun = true) public void afterClassTwo() { log.debug("RUN " + getClass() + ".afterClass()"); } @Test(groups = "std-two") public void two1() { log.debug("RUN " + getClass() + ".one1()"); } @Test(groups = "logic-two", dependsOnGroups = "std-two") public void two2() { log.debug("RUN " + getClass() + ".one2()"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/000077500000000000000000000000001475274123300262075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/DummyTest.java000066400000000000000000000020611475274123300310040ustar00rootroot00000000000000package test.groupinvocation; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class DummyTest { private static Map s_externalClassGroups = new HashMap<>(); @Test(groups = {"a"}) public void testA() {} @Test(groups = {"b"}) public void testB() {} @Test(groups = {"a", "b"}) public void testAB() {} @AfterClass(alwaysRun = true) public void checkInvocations() { Integer hashCode1 = s_externalClassGroups.get("beforeGroups"); Assert.assertNotNull(hashCode1, "External @BeforeGroups not invoked"); Integer hashCode2 = s_externalClassGroups.get("afterGroups"); Assert.assertNotNull(hashCode2, "External @AfterGroups not invoked"); Assert.assertEquals( hashCode1, hashCode2, "External @BeforeGroups and @AfterGroups were not invoked on the" + " same class instance"); } public static void recordInvocation(String string, int i) { s_externalClassGroups.put(string, i); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/DummyTest2.java000066400000000000000000000006701475274123300310720ustar00rootroot00000000000000package test.groupinvocation; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class DummyTest2 { private boolean m_invoked = false; @Test(groups = {"A"}) public void dummyTest() { m_invoked = true; } @AfterClass(alwaysRun = true) public void checkInvocations() { Assert.assertFalse(m_invoked, "@Test method invoked even if @BeforeGroups failed"); } } FailingBeforeGroupMethod.java000066400000000000000000000004061475274123300336450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocationpackage test.groupinvocation; import org.testng.annotations.BeforeGroups; public class FailingBeforeGroupMethod { @BeforeGroups(groups = {"A"}) public void beforeGroupA() { throw new RuntimeException("Failing @BeforeGroups beforeGroupA method"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/GroupConfiguration.java000066400000000000000000000006271475274123300327030ustar00rootroot00000000000000package test.groupinvocation; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; public class GroupConfiguration { @BeforeGroups(groups = {"a"}) public void beforeGroups() { DummyTest.recordInvocation("beforeGroups", hashCode()); } @AfterGroups(groups = {"a"}) public void afterGroups() { DummyTest.recordInvocation("afterGroups", hashCode()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/GroupSuiteSampleTest.java000066400000000000000000000003401475274123300331570ustar00rootroot00000000000000package test.groupinvocation; import org.testng.annotations.Test; public class GroupSuiteSampleTest { @Test(groups = "a") public void a() {} @Test(groups = "b") public void b() {} @Test public void c() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/GroupSuiteSampleTest2.java000066400000000000000000000003441475274123300332450ustar00rootroot00000000000000package test.groupinvocation; import org.testng.annotations.Test; public class GroupSuiteSampleTest2 { @Test(groups = "a") public void a2() {} @Test(groups = "b") public void b2() {} @Test public void c2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/GroupSuiteTest.java000066400000000000000000000123051475274123300320210ustar00rootroot00000000000000package test.groupinvocation; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.base.Joiner; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; /** Test that tags can have g. */ public class GroupSuiteTest extends SimpleBaseTest { private static final File PARENT = new File(getPathToResource("groupinvocation")); @DataProvider private static Object[][] dp() { return new Object[][] { {new String[] {"suiteA.xml", "suiteB.xml"}, /* Group in xml */ true}, {new String[] {"suiteA.xml", "suiteB.xml"}, /* Group in TestNG */ false}, {new String[] {"parent-suiteA.xml", "parent-suiteB.xml"}, /* Group in xml */ true}, {new String[] {"parent-suiteA.xml", "parent-suiteB.xml"}, /* Group in TestNG */ false}, {new String[0], /* Group in xml */ true}, {new String[0], /* Group in TestNG */ false} }; } @Test(dataProvider = "dp") public void includeFromSuite0(String[] withSuiteFiles, boolean excludeWithXml) { runWithSuite(withSuiteFiles, excludeWithXml, "a", "b", "c", "a2", "b2", "c2"); } @Test(dataProvider = "dp") public void includeFromSuite1(String[] withSuiteFiles, boolean excludeWithXml) { runWithSuite(withSuiteFiles, excludeWithXml, g("a"), g(), "a", "a2"); } @Test(dataProvider = "dp") public void includeFromSuite2(String[] withSuiteFiles, boolean excludeWithXml) { runWithSuite(withSuiteFiles, excludeWithXml, g("a", "b"), g(), "a", "b", "a2", "b2"); } @Test(dataProvider = "dp") public void excludeFromSuite1(String[] withSuiteFiles, boolean excludeWithXml) { runWithSuite(withSuiteFiles, excludeWithXml, g(), g("a"), "b", "c", "b2", "c2"); } @Test(dataProvider = "dp") public void excludeFromSuite2(String[] withSuiteFiles, boolean excludeWithXml) { runWithSuite(withSuiteFiles, excludeWithXml, g(), g("a", "b"), "c", "c2"); } @Test(description = "Include in both suite and test") public void includeTestAndSuite1Xml() { runWithSuite(g("a"), g(), g("b"), g(), true, "a", "b", "a2", "b2"); } @Test(description = "Include in both suite and test") public void includeTestAndSuite1Cli() { runWithSuite(g("a"), g(), g("b"), g(), false, "a", "b", "a2", "b2"); } @Test(description = "Include in suite, exclude in test") public void excludeTestAndSuite2Xml() { runWithSuite(g("a", "b"), g(), g(), g("a"), true, "b", "b2"); } @Test(description = "Include in suite, exclude in test") public void excludeTestAndSuite2Cli() { runWithSuite(g("a", "b"), g(), g(), g("a"), false, "b", "b2"); } private void runWithSuite(String[] withSuiteFiles, boolean excludeWithXml, String... methods) { runWithSuite(withSuiteFiles, excludeWithXml, g(), g(), g(), g(), methods); } private void runWithSuite( String[] withSuiteFiles, boolean excludeWithXml, List suiteGroups, List excludedSuiteGroups, String... methods) { runWithSuite( withSuiteFiles, excludeWithXml, suiteGroups, excludedSuiteGroups, g(), g(), methods); } private void runWithSuite( List suiteGroups, List excludedSuiteGroups, List testGroups, List excludedTestGroups, boolean groupsWithXml, String... methods) { runWithSuite( new String[0], groupsWithXml, suiteGroups, excludedSuiteGroups, testGroups, excludedTestGroups, methods); } private void runWithSuite( String[] withSuiteFiles, boolean groupsWithXml, List suiteGroups, List excludedSuiteGroups, List testGroups, List excludedTestGroups, String... methods) { TestNG tng = create(); XmlSuite suite = createXmlSuite("Groups"); if (groupsWithXml) { suite.setIncludedGroups(suiteGroups); suite.setExcludedGroups(excludedSuiteGroups); } else { tng.setGroups(Joiner.on(',').join(suiteGroups)); tng.setExcludedGroups(Joiner.on(',').join(excludedSuiteGroups)); } if (withSuiteFiles.length != 0) { List suiteFiles = new ArrayList<>(withSuiteFiles.length); for (String suiteFile : withSuiteFiles) { suiteFiles.add(new File(PARENT, suiteFile).getAbsolutePath()); } suite.setSuiteFiles(suiteFiles); createXmlTest(suite, "Groups-test"); } else { XmlTest test = createXmlTest( suite, "Groups-test", GroupSuiteSampleTest.class, GroupSuiteSampleTest2.class); test.setIncludedGroups(testGroups); test.setExcludedGroups(excludedTestGroups); } tng.setXmlSuites(Collections.singletonList(suite)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getInvokedMethodNames()).containsExactly(methods); } private static List g(String... groups) { return Arrays.asList(groups); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/InvokerTest.java000066400000000000000000000032461475274123300313340ustar00rootroot00000000000000package test.groupinvocation; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class InvokerTest extends SimpleBaseTest { private static final String SMOKE = "smoketests"; private static final String FUNCTIONAL_TESTS = "functionaltests"; @Test public void testClassWithRedundantGroups() { Assert.assertEquals(2, privateRun(RedundantGroupNamesSample.class, SMOKE, FUNCTIONAL_TESTS)); } @Test public void testClassWithUniqueGroups() { Assert.assertEquals(2, privateRun(UniqueGroupNamesSample.class, SMOKE)); } private int privateRun(final Class className, String... groupNames) { XmlSuite suite = createXmlSuite("simple-suite"); XmlTest xmlTest = createXmlTest(suite, "simple-test", className); for (String group : groupNames) { xmlTest.addIncludedGroup(group); } TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); return listener.getInvokedMethodNames().size(); } public static class UniqueGroupNamesSample { @BeforeGroups(groups = {InvokerTest.SMOKE}) public void before() {} @Test(groups = {InvokerTest.SMOKE}) public void test() {} } public static class RedundantGroupNamesSample { @BeforeGroups(groups = {InvokerTest.SMOKE, InvokerTest.FUNCTIONAL_TESTS}) public void before() {} @Test(groups = {InvokerTest.SMOKE, InvokerTest.FUNCTIONAL_TESTS}) public void test() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groupinvocation/testng.xml000066400000000000000000000016611475274123300302410ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/000077500000000000000000000000001475274123300243005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue182/000077500000000000000000000000001475274123300256635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue182/ChildTest.java000066400000000000000000000002601475274123300304070ustar00rootroot00000000000000package test.groups.issue182; import org.testng.annotations.Test; @Test(groups = "myGroup") public class ChildTest extends ParentTest { public void childTestMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue182/IssueTest.java000066400000000000000000000015721475274123300304630ustar00rootroot00000000000000package test.groups.issue182; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Maps; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { private static final String MY_GROUP = "myGroup"; @Test public void ensureGroupsPresentInInheritedMethods() { TestNG testng = create(ChildTest.class); LocalListener listener = new LocalListener(); testng.addListener(listener); testng.run(); Map> expected = Maps.newHashMap(); expected.put("parentTestMethod", Collections.singletonList(MY_GROUP)); expected.put("childTestMethod", Collections.singletonList(MY_GROUP)); assertThat(listener.getMapping()).containsAllEntriesOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue182/LocalListener.java000066400000000000000000000012631475274123300312700ustar00rootroot00000000000000package test.groups.issue182; import java.util.Arrays; import java.util.List; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.collections.Maps; public class LocalListener implements IInvokedMethodListener { private Map> mapping = Maps.newHashMap(); @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String methodname = method.getTestMethod().getMethodName(); mapping.put(methodname, Arrays.asList(method.getTestMethod().getGroups())); } public Map> getMapping() { return mapping; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue182/ParentTest.java000066400000000000000000000002231475274123300306140ustar00rootroot00000000000000package test.groups.issue182; import org.testng.annotations.Test; @Test public abstract class ParentTest { public void parentTestMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue1834/000077500000000000000000000000001475274123300257505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue1834/IssueTest.java000066400000000000000000000031401475274123300305410ustar00rootroot00000000000000package test.groups.issue1834; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.util.Collections; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.reporters.Files; import test.SimpleBaseTest; import test.TestHelper; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-1834") public void ensureDependenciesDefinedInSuiteAreHonored() throws IOException { File file = File.createTempFile("1834", ".xml"); Files.writeFile(asSuite(), file); TestNG testng = create(); testng.setTestSuites(Collections.singletonList(file.getAbsolutePath())); OutputGatheringListener listener = new OutputGatheringListener(); testng.addListener(listener); testng.run(); assertThat(listener.getConsoleLogs()).containsExactly("Uncached", "Cached"); } private static String asSuite() { return TestHelper.SUITE_XML_HEADER + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + ""; } } OutputGatheringListener.java000066400000000000000000000007641475274123300334020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue1834package test.groups.issue1834; import java.util.List; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.TestListenerAdapter; import org.testng.collections.Lists; public class OutputGatheringListener extends TestListenerAdapter { private List consoleLogs = Lists.newArrayList(); @Override public void onTestSuccess(ITestResult tr) { consoleLogs.addAll(Reporter.getOutput(tr)); } public List getConsoleLogs() { return consoleLogs; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue1834/TestSample.java000066400000000000000000000005401475274123300306730ustar00rootroot00000000000000package test.groups.issue1834; import org.testng.Reporter; import org.testng.annotations.Test; public class TestSample { @Test(groups = "Cached") public void dataSuccessfullyReceivedFromCache() { Reporter.log("Cached"); } @Test(groups = "Uncached") public void dataSuccessfullyReceivedFromWhapi() { Reporter.log("Uncached"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2152/000077500000000000000000000000001475274123300257425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2152/IssueTest.java000066400000000000000000000010641475274123300305360ustar00rootroot00000000000000package test.groups.issue2152; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2152") public void ensureConfigurationsDontInheritGroupsWhenRunningWithoutGroupFiltering() { TestNG testng = create(TestClassSample.class); testng.run(); String[] expected = new String[] {"setup", "test1", "teardown"}; assertThat(TestClassSample.logs).containsExactly(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2152/TestClassSample.java000066400000000000000000000011131475274123300316500ustar00rootroot00000000000000package test.groups.issue2152; import java.util.ArrayList; import java.util.List; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = {"Group1", "Group2", "Group3", "Group4"}) public class TestClassSample { static List logs = new ArrayList<>(); @BeforeMethod public void setUp() { logs.add("setup"); } @AfterMethod public void tearDown(ITestResult result) { logs.add("teardown"); } public void test1() { logs.add("test1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2232/000077500000000000000000000000001475274123300257415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2232/IssueTest.java000066400000000000000000000062661475274123300305460ustar00rootroot00000000000000package test.groups.issue2232; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.testng.Reporter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlGroups; import org.testng.xml.XmlPackage; import org.testng.xml.XmlRun; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2232", invocationCount = 2) // This test case doesn't vet out the fix completely because the bug by itself is very // sporadic and is not easy to reproduce. That is why this test is being executed 10 times // to ensure that the issue can be reproduced in one of the executions public void ensureNoNPEThrownWhenRunningGroups() throws InterruptedException { TestNG testng = create(constructSuite()); testng.run(); assertThat(testng.getStatus()).isEqualTo(0); } private XmlSuite constructSuite() { XmlSuite xmlsuite = createXmlSuite("2232_suite"); xmlsuite.setConfigFailurePolicy(XmlSuite.FailurePolicy.CONTINUE); xmlsuite.setThreadCount(256); xmlsuite.setParallel(XmlSuite.ParallelMode.CLASSES); XmlTest xmltest = createXmlTest(xmlsuite, "2232_test"); XmlRun xmlrun = new XmlRun(); xmlrun.onInclude("Group2"); xmlrun.onExclude("Broken"); XmlGroups xmlgroup = new XmlGroups(); xmlgroup.setRun(xmlrun); xmltest.setGroups(xmlgroup); XmlPackage xmlpackage = new XmlPackage(); xmlpackage.setName(getClass().getPackage().getName() + ".samples.*"); xmltest.setPackages(Collections.singletonList(xmlpackage)); return xmlsuite; } @Test(invocationCount = 2, description = "GITHUB-2232") // Ensuring that the bug doesn't surface even when tests are executed via the command line mode public void commandlineTest() throws IOException, InterruptedException { Path suitefile = Files.write( Files.createTempFile("testng", ".xml"), constructSuite().toXml().getBytes(Charset.defaultCharset())); List args = Collections.singletonList(suitefile.toFile().getAbsolutePath()); int status = exec(Collections.emptyList(), args); assertThat(status).isEqualTo(0); } private int exec(List jvmArgs, List args) throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); String className = TestNG.class.getName(); List command = new ArrayList<>(); command.add(javaBin); command.addAll(jvmArgs); command.add("-cp"); command.add(classpath); command.add(className); command.addAll(args); Reporter.log("Executing the command " + command, 2, true); ProcessBuilder builder = new ProcessBuilder(command); Process process = builder.inheritIO().start(); process.waitFor(); return process.exitValue(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2232/samples/000077500000000000000000000000001475274123300274055ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2232/samples/SampleTest.java000066400000000000000000000012411475274123300323270ustar00rootroot00000000000000package test.groups.issue2232.samples; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = {"Group1", "Group2", "Group3"}) public class SampleTest { private int variable = 0; @BeforeClass public void setUp() { variable += 1; } @AfterMethod public void tearDown() { variable += 1; } @DataProvider(name = "testData1") public Object[][] testData1() { return new Object[][] { {"Test1"}, {"Test2"}, }; } @Test(dataProvider = "testData1") public void test1(String test) { variable += 1; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/groups/issue2232/samples/SampleTest2.java000066400000000000000000000013731475274123300324170ustar00rootroot00000000000000package test.groups.issue2232.samples; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = {"Group1", "Group2", "Group3"}) public class SampleTest2 { private int variable = 0; @BeforeClass public void setUp() throws Exception { variable += 1; if (variable == 4) { throw new Exception("Exception!"); } } @AfterMethod public void tearDown() { variable += 1; } @DataProvider(name = "testData2") public Object[][] testData2() { return new Object[][] { {"Test3"}, {"Test4"}, }; } @Test(dataProvider = "testData2") public void test2(String test) { variable += 1; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/000077500000000000000000000000001475274123300240555ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/ExampleSingleton.java000066400000000000000000000001711475274123300301750ustar00rootroot00000000000000package test.guice; public class ExampleSingleton implements ISingleton { @Override public void doSomething() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/FakeInjector.java000066400000000000000000000053651475274123300272750ustar00rootroot00000000000000package test.guice; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.MembersInjector; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.TypeLiteral; import com.google.inject.spi.Element; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.TypeConverterBinding; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.internal.objects.InstanceCreator; public class FakeInjector implements Injector { private static FakeInjector instance; public FakeInjector() {} private static void setInstance(FakeInjector i) { instance = i; } public static FakeInjector getInstance() { return instance; } @Override public void injectMembers(Object instance) {} @Override public MembersInjector getMembersInjector(TypeLiteral typeLiteral) { return null; } @Override public MembersInjector getMembersInjector(Class type) { return null; } @Override public Map, Binding> getBindings() { return null; } @Override public Map, Binding> getAllBindings() { return null; } @Override public Binding getBinding(Key key) { return null; } @Override public Binding getBinding(Class type) { return null; } @Override public Binding getExistingBinding(Key key) { return null; } @Override public List> findBindingsByType(TypeLiteral type) { return null; } @Override public Provider getProvider(Key key) { return null; } @Override public Provider getProvider(Class type) { return null; } @Override public T getInstance(Key key) { return null; } @Override public T getInstance(Class type) { try { setInstance(this); return InstanceCreator.newInstance(type); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Injector getParent() { return null; } @Override public Injector createChildInjector(Iterable modules) { return null; } @Override public Injector createChildInjector(Module... modules) { return null; } @Override public Map, Scope> getScopeBindings() { return null; } @Override public Set getTypeConverterBindings() { return null; } @Override public List getElements() { return null; } @Override public Map, List> getAllMembersInjectorInjectionPoints() { return null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/Guice1Test.java000066400000000000000000000006511475274123300266770ustar00rootroot00000000000000package test.guice; import com.google.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; import test.SimpleBaseTest; @Guice(modules = GuiceExampleModule.class) public class Guice1Test extends SimpleBaseTest { static ISingleton m_object; @Inject ISingleton m_singleton; @Test public void singletonShouldWork() { m_singleton.doSomething(); m_object = m_singleton; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/Guice2Test.java000066400000000000000000000006121475274123300266750ustar00rootroot00000000000000package test.guice; import com.google.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; import test.SimpleBaseTest; @Guice(modules = GuiceExampleModule.class) public class Guice2Test extends SimpleBaseTest { static ISingleton m_object; @Inject ISingleton m_singleton; @Test public void singletonShouldWork() { m_object = m_singleton; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceBase.java000066400000000000000000000002001475274123300265370ustar00rootroot00000000000000package test.guice; import org.testng.annotations.Guice; @Guice(modules = GuiceExampleModule.class) public class GuiceBase {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceExampleModule.java000066400000000000000000000004761475274123300304450ustar00rootroot00000000000000package test.guice; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Singleton; public class GuiceExampleModule implements Module { @Override public void configure(Binder binder) { binder.bind(ISingleton.class).to(ExampleSingleton.class).in(Singleton.class); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceInheritanceTest.java000066400000000000000000000004101475274123300307610ustar00rootroot00000000000000package test.guice; import com.google.inject.Inject; import org.testng.annotations.Test; public class GuiceInheritanceTest extends GuiceBase { @Inject ISingleton m_singleton; @Test public void singletonShouldWork() { m_singleton.doSomething(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceModuleFactoryTest.java000066400000000000000000000005111475274123300313070ustar00rootroot00000000000000package test.guice; import com.google.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice(moduleFactory = ModuleFactory.class) public class GuiceModuleFactoryTest { @Inject ISingleton m_singleton; @Test public void singletonShouldWork() { m_singleton.doSomething(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceNoModuleTest.java000066400000000000000000000002471475274123300302620ustar00rootroot00000000000000package test.guice; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice public class GuiceNoModuleTest { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceParentModule.java000066400000000000000000000010401475274123300302670ustar00rootroot00000000000000package test.guice; import com.google.inject.AbstractModule; import com.google.inject.Singleton; import org.testng.ITestContext; public class GuiceParentModule extends AbstractModule { private final ITestContext context; public GuiceParentModule(ITestContext context) { this.context = context; } @Override protected void configure() { bind(MyService.class).toProvider(MyServiceProvider.class); bind(MyContext.class).to(MyContextImpl.class).in(Singleton.class); bind(ITestContext.class).toInstance(context); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceParentModuleTest.java000066400000000000000000000012401475274123300311310ustar00rootroot00000000000000package test.guice; import com.google.inject.Inject; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Test @Guice(modules = GuiceTestModule.class) public class GuiceParentModuleTest { @Inject MySession mySession; @Inject MyService myService; @Inject ITestContext context; public void testService() { Assert.assertNotNull(myService); Assert.assertNotNull(mySession); myService.serve(mySession); Assert.assertNotNull(context); Assert.assertEquals(context.getName(), "Guice"); Assert.assertEquals(context.getSuite().getName(), "parent-module-suite"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceTest.java000066400000000000000000000075441475274123300266260ustar00rootroot00000000000000package test.guice; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertEquals; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; import test.guice.issue2343.Person; import test.guice.issue2343.SampleA; import test.guice.issue2343.SampleB; import test.guice.issue2343.modules.ParentModule; import test.guice.issue2355.AnotherParentModule; import test.guice.issue2427.Test1; import test.guice.issue2427.Test2; import test.guice.issue2427.modules.TestModuleOne; import test.guice.issue2427.modules.TestModuleTwo; import test.guice.issue2427.modules.TestParentConfigModule; import test.guice.issue2570.GuicePoweredConstructorInjectedRetry; import test.guice.issue2570.GuicePoweredConstructorInjectedRetryForDPTest; import test.guice.issue2570.GuicePoweredSetterInjectedRetry; import test.guice.issue2570.SampleTestClass; public class GuiceTest extends SimpleBaseTest { @Test public void guiceTest() { TestNG tng = create(Guice1Test.class, Guice2Test.class); Guice1Test.m_object = null; Guice2Test.m_object = null; tng.run(); assertThat(Guice1Test.m_object).isNotNull(); assertThat(Guice2Test.m_object).isNotNull(); assertThat(Guice1Test.m_object).isEqualTo(Guice2Test.m_object); } @Test public void guiceWithNoModules() { TestNG tng = create(GuiceNoModuleTest.class); tng.run(); } @Test(description = "GITHUB-2199") public void guiceWithExternalDependencyInjector() { TestNG testng = create(Guice1Test.class); testng.setInjectorFactory((stage, modules) -> new FakeInjector()); testng.run(); assertThat(FakeInjector.getInstance()).isNotNull(); } @Test(description = "GITHUB-2343") public void ensureInjectorsAreReUsed() { XmlSuite suite = createXmlSuite("sample_suite", "sample_test", SampleA.class, SampleB.class); suite.setParentModule(ParentModule.class.getCanonicalName()); TestNG testng = create(suite); testng.run(); assertThat(Person.counter).isEqualTo(1); } @Test(description = "GITHUB-2355") public void ensureMultipleInjectorsAreNotCreated() { Person.counter = 0; XmlSuite suite = createXmlSuite("sample_suite", "sample_test", SampleA.class, SampleB.class); suite.setParentModule(AnotherParentModule.class.getCanonicalName()); TestNG testng = create(suite); testng.run(); assertThat(AnotherParentModule.getCounter()).isEqualTo(1); assertThat(Person.counter).isEqualTo(1); } @Test(description = "GITHUB-2427") public void ensureConfigureMethodCalledOnceForModule() { XmlSuite suite = createXmlSuite("sample_suite", "sample_test", Test1.class, Test2.class); suite.setParentModule(TestParentConfigModule.class.getCanonicalName()); TestNG testng = create(suite); testng.run(); assertEquals( TestParentConfigModule.counter.get(), 1, "TestParentModule configuration called times"); assertEquals(TestModuleOne.counter.get(), 1, "TestModuleOne configuration called times"); assertEquals(TestModuleTwo.counter.get(), 1, "TestModuleTwo configuration called times"); } @Test(description = "GITHUB-2570") public void ensureRetryAnalyzersAreGuiceAware() { TestNG testng = create(SampleTestClass.class); testng.run(); assertThat(GuicePoweredConstructorInjectedRetry.getDragonWarrior()) .withFailMessage( "The Retry Analyzer should have been created via Guice constructor injection.") .isEqualTo("Kungfu-Panda"); assertThat(GuicePoweredSetterInjectedRetry.getTerminator()) .withFailMessage("The Retry Analyzer should have been created via Guice setter injection.") .isEqualTo("Arnold"); assertThat(GuicePoweredConstructorInjectedRetryForDPTest.getCounter()) .withFailMessage("There should have been 2 retry analyser instances created by Guice") .isEqualTo(2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/GuiceTestModule.java000066400000000000000000000006031475274123300277610ustar00rootroot00000000000000package test.guice; import com.google.inject.AbstractModule; import com.google.inject.Inject; public class GuiceTestModule extends AbstractModule { private final MyContext myContext; @Inject GuiceTestModule(MyContext myContext) { this.myContext = myContext; } @Override protected void configure() { bind(MySession.class).toInstance(myContext.getSession()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/ISingleton.java000066400000000000000000000001141475274123300267670ustar00rootroot00000000000000package test.guice; public interface ISingleton { void doSomething(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/ModuleFactory.java000066400000000000000000000013211475274123300274720ustar00rootroot00000000000000package test.guice; import com.google.inject.Module; import org.testng.IModuleFactory; import org.testng.ITestContext; public class ModuleFactory implements IModuleFactory { @Override public Module createModule(ITestContext context, Class testClass) { String parameter = context.getCurrentXmlTest().getParameter("inject"); String expected = "guice"; if (!expected.equals(parameter)) { throw new RuntimeException("Excepted parameter to be " + expected + ", got " + parameter); } if (GuiceModuleFactoryTest.class == testClass) { return new GuiceExampleModule(); } else { throw new RuntimeException("Don't know how to create a module for class " + testClass); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/MyContext.java000066400000000000000000000001171475274123300266510ustar00rootroot00000000000000package test.guice; public interface MyContext { MySession getSession(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/MyContextImpl.java000066400000000000000000000003111475274123300274670ustar00rootroot00000000000000package test.guice; public class MyContextImpl implements MyContext { private final MySession mySession = new MySession(); @Override public MySession getSession() { return mySession; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/MyService.java000066400000000000000000000001301475274123300266200ustar00rootroot00000000000000package test.guice; public interface MyService { void serve(MySession mySession); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/MyServiceProvider.java000066400000000000000000000003031475274123300303350ustar00rootroot00000000000000package test.guice; import com.google.inject.Provider; public class MyServiceProvider implements Provider { @Override public MyService get() { return mySession -> {}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/MySession.java000066400000000000000000000000571475274123300266530ustar00rootroot00000000000000package test.guice; public class MySession {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2343/000077500000000000000000000000001475274123300255215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2343/Person.java000066400000000000000000000001751475274123300276350ustar00rootroot00000000000000package test.guice.issue2343; public class Person { public static int counter; public Person() { ++counter; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2343/SampleA.java000066400000000000000000000004041475274123300277040ustar00rootroot00000000000000package test.guice.issue2343; import javax.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice public class SampleA { @Inject public SampleA(final Person person) {} @Test public void testAnotherApp() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2343/SampleB.java000066400000000000000000000003751475274123300277140ustar00rootroot00000000000000package test.guice.issue2343; import javax.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice public class SampleB { @Inject public SampleB(final Person person) {} @Test public void testApp() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2343/modules/000077500000000000000000000000001475274123300271715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2343/modules/ParentModule.java000066400000000000000000000010771475274123300324400ustar00rootroot00000000000000package test.guice.issue2343.modules; import com.google.inject.AbstractModule; import java.util.Objects; import javax.inject.Singleton; import test.guice.issue2343.Person; public class ParentModule extends AbstractModule { @Override protected void configure() { bind(Person.class).in(Singleton.class); } @Override public boolean equals(final Object object) { if (object == null) { return false; } return Objects.equals(getClass(), object.getClass()); } @Override public int hashCode() { return this.getClass().hashCode(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2355/000077500000000000000000000000001475274123300255245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2355/AnotherParentModule.java000066400000000000000000000014751475274123300323160ustar00rootroot00000000000000package test.guice.issue2355; import com.google.inject.AbstractModule; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Singleton; import test.guice.issue2343.Person; public class AnotherParentModule extends AbstractModule { private static final AtomicInteger counter = new AtomicInteger(0); public AnotherParentModule() { counter.incrementAndGet(); } public static int getCounter() { return counter.get(); } @Override protected void configure() { bind(Person.class).in(Singleton.class); } @Override public boolean equals(final Object object) { if (object == null) { return false; } return Objects.equals(getClass(), object.getClass()); } @Override public int hashCode() { return this.getClass().hashCode(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/000077500000000000000000000000001475274123300255245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/Test1.java000066400000000000000000000005171475274123300273720ustar00rootroot00000000000000package test.guice.issue2427; import org.testng.annotations.Guice; import org.testng.annotations.Test; import test.guice.issue2427.modules.TestModuleOne; @Guice(modules = {TestModuleOne.class}) @Test() public class Test1 { public void shouldInstatiateModulesOnlyOnce() { // do nothing as test is about configuration part } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/Test2.java000066400000000000000000000005171475274123300273730ustar00rootroot00000000000000package test.guice.issue2427; import org.testng.annotations.Guice; import org.testng.annotations.Test; import test.guice.issue2427.modules.TestModuleTwo; @Guice(modules = {TestModuleTwo.class}) @Test() public class Test2 { public void shouldInstatiateModulesOnlyOnce() { // do nothing as test is about configuration part } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/modules/000077500000000000000000000000001475274123300271745ustar00rootroot00000000000000TestAbstractModule.java000066400000000000000000000011631475274123300335320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/modulespackage test.guice.issue2427.modules; import com.google.inject.AbstractModule; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; abstract class TestAbstractModule extends AbstractModule { private final AtomicInteger counter; protected TestAbstractModule(AtomicInteger counter) { this.counter = counter; } @Override protected void configure() { counter.incrementAndGet(); } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return obj != null && Objects.equals(getClass(), obj.getClass()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/modules/TestModuleOne.java000066400000000000000000000004061475274123300325660ustar00rootroot00000000000000package test.guice.issue2427.modules; import java.util.concurrent.atomic.AtomicInteger; public class TestModuleOne extends TestAbstractModule { public static AtomicInteger counter = new AtomicInteger(0); public TestModuleOne() { super(counter); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/modules/TestModuleTwo.java000066400000000000000000000004061475274123300326160ustar00rootroot00000000000000package test.guice.issue2427.modules; import java.util.concurrent.atomic.AtomicInteger; public class TestModuleTwo extends TestAbstractModule { public static AtomicInteger counter = new AtomicInteger(0); public TestModuleTwo() { super(counter); } } TestParentConfigModule.java000066400000000000000000000004301475274123300343420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2427/modulespackage test.guice.issue2427.modules; import java.util.concurrent.atomic.AtomicInteger; public class TestParentConfigModule extends TestAbstractModule { public static AtomicInteger counter = new AtomicInteger(0); public TestParentConfigModule() { super(counter); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2570/000077500000000000000000000000001475274123300255235ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2570/GuiceModule.java000066400000000000000000000014151475274123300305710ustar00rootroot00000000000000package test.guice.issue2570; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.inject.AbstractModule; import com.google.inject.Provides; import java.lang.annotation.Retention; import javax.inject.Qualifier; import org.testng.IRetryAnalyzer; public class GuiceModule extends AbstractModule { @Override protected void configure() { bind(IRetryAnalyzer.class).to(GuicePoweredConstructorInjectedRetry.class); } @Provides @DragonWarrior public static String dragonWarriorName() { return "Kungfu-Panda"; } @Provides @Terminator public static String terminatorName() { return "Arnold"; } @Qualifier @Retention(RUNTIME) @interface DragonWarrior {} @Qualifier @Retention(RUNTIME) @interface Terminator {} } GuicePoweredConstructorInjectedRetry.java000066400000000000000000000014241475274123300356340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2570package test.guice.issue2570; import com.google.inject.Inject; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.Guice; import test.guice.issue2570.GuiceModule.DragonWarrior; @Guice(modules = GuiceModule.class) public class GuicePoweredConstructorInjectedRetry implements IRetryAnalyzer { private static String dragonWarrior; private static void setName(String warriorName) { dragonWarrior = warriorName; } public static String getDragonWarrior() { return dragonWarrior; } @Inject public GuicePoweredConstructorInjectedRetry(@DragonWarrior String name) { setName(name); } private int count = 1; @Override public boolean retry(ITestResult result) { return !result.isSuccess() && count-- > 0; } } GuicePoweredConstructorInjectedRetryForDPTest.java000066400000000000000000000014311475274123300373650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2570package test.guice.issue2570; import com.google.inject.Inject; import java.util.concurrent.atomic.AtomicInteger; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.Guice; import test.guice.issue2570.GuiceModule.DragonWarrior; @Guice(modules = GuiceModule.class) public class GuicePoweredConstructorInjectedRetryForDPTest implements IRetryAnalyzer { private static AtomicInteger counter = new AtomicInteger(0); public static int getCounter() { return counter.get(); } @Inject public GuicePoweredConstructorInjectedRetryForDPTest(@DragonWarrior String name) { counter.incrementAndGet(); } private int count = 1; @Override public boolean retry(ITestResult result) { return !result.isSuccess() && count-- > 0; } } GuicePoweredSetterInjectedRetry.java000066400000000000000000000013471475274123300345610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2570package test.guice.issue2570; import com.google.inject.Inject; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.Guice; import test.guice.issue2570.GuiceModule.Terminator; @Guice(modules = GuiceModule.class) public class GuicePoweredSetterInjectedRetry implements IRetryAnalyzer { private int count = 1; private static String terminator; @Inject public void setName(@Terminator String name) { setValue(name); } private static void setValue(String warriorName) { terminator = warriorName; } public static String getTerminator() { return terminator; } @Override public boolean retry(ITestResult result) { return !result.isSuccess() && count-- > 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue2570/SampleTestClass.java000066400000000000000000000012331475274123300314340ustar00rootroot00000000000000package test.guice.issue2570; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestClass { @Test(retryAnalyzer = GuicePoweredConstructorInjectedRetry.class) public void test() { Assert.fail(); } @Test(retryAnalyzer = GuicePoweredSetterInjectedRetry.class) public void anotherTest() { Assert.fail(); } @Test(dataProvider = "dp", retryAnalyzer = GuicePoweredConstructorInjectedRetryForDPTest.class) public void dataDrivenTest(int i) { Assert.fail(); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/000077500000000000000000000000001475274123300254475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/Car.java000066400000000000000000000001541475274123300270170ustar00rootroot00000000000000package test.guice.issue279; public class Car implements Vehicle { @Override public void drive() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/DummyReporter.java000066400000000000000000000012141475274123300311260ustar00rootroot00000000000000package test.guice.issue279; import com.google.inject.Inject; import java.util.List; import org.testng.IReporter; import org.testng.ISuite; import org.testng.annotations.Guice; import org.testng.xml.XmlSuite; @Guice(moduleFactory = TestDIFactory.class) public class DummyReporter implements IReporter { @Inject private Greeter greeter; private static Greeter instance; @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { instance = greeter; } public static Greeter getInstance() { return instance; } static void clearInstance() { instance = null; } } DummyReporterWithoutModuleFactory.java000066400000000000000000000011731475274123300351350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279package test.guice.issue279; import com.google.inject.Inject; import java.util.List; import org.testng.IReporter; import org.testng.ISuite; import org.testng.annotations.Guice; import org.testng.xml.XmlSuite; @Guice public class DummyReporterWithoutModuleFactory implements IReporter { @Inject private Vehicle vehicle; private static Vehicle instance; @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { instance = vehicle; } public static Vehicle getInstance() { return instance; } static void clearInstance() { instance = null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/Greeter.java000066400000000000000000000001311475274123300277020ustar00rootroot00000000000000package test.guice.issue279; public interface Greeter { String greet(String name); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/IssueTest.java000066400000000000000000000036421475274123300302470ustar00rootroot00000000000000package test.guice.issue279; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @BeforeMethod public void cleanup() { MyListener.clearInstance(); DummyReporter.clearInstance(); DummyReporterWithoutModuleFactory.clearInstance(); } @Test public void classWithListenerAnnotation() { TestNG testng = create(TestClassWithListener.class); testng.run(); assertThat(MyListener.getInstance()).isInstanceOf(TextGreeter.class); assertThat(DummyReporter.getInstance()).isInstanceOf(TextGreeter.class); } @Test public void classWithoutListenerAnnotation() { XmlSuite xmlSuite = createXmlSuite("sample_suite"); xmlSuite.setListeners(Arrays.asList(MyListener.class.getName(), DummyReporter.class.getName())); createXmlTest(xmlSuite, "sample_test", TestClassWithoutListener.class); TestNG testng = create(xmlSuite); testng.run(); assertThat(MyListener.getInstance()).isInstanceOf(TextGreeter.class); assertThat(DummyReporter.getInstance()).isInstanceOf(TextGreeter.class); } @Test public void classWithModuleDefinedInSuite() { XmlSuite xmlSuite = createXmlSuite("sample_suite"); xmlSuite.setParentModule(SampleModule.class.getName()); xmlSuite.setListeners( Arrays.asList( MyListenerWithoutModuleFactory.class.getName(), DummyReporterWithoutModuleFactory.class.getName())); createXmlTest(xmlSuite, "sample_test", TestClassWithoutListener.class); TestNG testng = create(xmlSuite); testng.run(); assertThat(MyListenerWithoutModuleFactory.getInstance()).isInstanceOf(TextGreeter.class); assertThat(DummyReporterWithoutModuleFactory.getInstance()).isInstanceOf(Car.class); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/MyListener.java000066400000000000000000000011571475274123300304110ustar00rootroot00000000000000package test.guice.issue279; import com.google.inject.Inject; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.Guice; @Guice(moduleFactory = TestDIFactory.class) public class MyListener implements IInvokedMethodListener { @Inject private Greeter greeter; private static Greeter instance; @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { instance = greeter; } static Greeter getInstance() { return instance; } static void clearInstance() { instance = null; } } MyListenerWithoutModuleFactory.java000066400000000000000000000011361475274123300344110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279package test.guice.issue279; import com.google.inject.Inject; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.Guice; @Guice public class MyListenerWithoutModuleFactory implements IInvokedMethodListener { @Inject private Greeter greeter; private static Greeter instance; @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { instance = greeter; } static Greeter getInstance() { return instance; } static void clearInstance() { instance = null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/SampleModule.java000066400000000000000000000004511475274123300307010ustar00rootroot00000000000000package test.guice.issue279; import com.google.inject.AbstractModule; public class SampleModule extends AbstractModule { @Override protected void configure() { bind(Greeter.class).to(TextGreeter.class).asEagerSingleton(); bind(Vehicle.class).to(Car.class).asEagerSingleton(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/TestClassWithListener.java000066400000000000000000000003561475274123300325650ustar00rootroot00000000000000package test.guice.issue279; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners({MyListener.class, DummyReporter.class}) public class TestClassWithListener { @Test public void testMethod() {} } TestClassWithoutListener.java000066400000000000000000000002241475274123300332300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279package test.guice.issue279; import org.testng.annotations.Test; public class TestClassWithoutListener { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/TestDIFactory.java000066400000000000000000000004641475274123300310020ustar00rootroot00000000000000package test.guice.issue279; import com.google.inject.Module; import org.testng.IModuleFactory; import org.testng.ITestContext; public class TestDIFactory implements IModuleFactory { @Override public Module createModule(ITestContext context, Class testClass) { return new SampleModule(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/TextGreeter.java000066400000000000000000000002401475274123300305500ustar00rootroot00000000000000package test.guice.issue279; public class TextGreeter implements Greeter { @Override public String greet(String name) { return "hello " + name; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/issue279/Vehicle.java000066400000000000000000000001131475274123300276640ustar00rootroot00000000000000package test.guice.issue279; public interface Vehicle { void drive(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/jitbinding/000077500000000000000000000000001475274123300261765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/jitbinding/FirstModuleSample.java000066400000000000000000000011541475274123300324410ustar00rootroot00000000000000package test.guice.jitbinding; import static org.assertj.core.api.Assertions.assertThat; import com.google.inject.AbstractModule; import javax.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice(modules = FirstModuleSample.FirstModule.class) public class FirstModuleSample { static class FirstModule extends AbstractModule { @Override protected void configure() { // no explicit binding, so value will be just in time bound to `new String()` } } @Inject String value; @Test public void testInject() { assertThat(value).isEqualTo(""); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/jitbinding/JitBindingTest.java000066400000000000000000000012261475274123300317230ustar00rootroot00000000000000package test.guice.jitbinding; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class JitBindingTest extends SimpleBaseTest { @Test public void testConflictingJitBinding() { TestNG tng = create(FirstModuleSample.class, SecondModuleSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/guice/jitbinding/SecondModuleSample.java000066400000000000000000000011331475274123300325620ustar00rootroot00000000000000package test.guice.jitbinding; import static org.assertj.core.api.Assertions.assertThat; import com.google.inject.AbstractModule; import javax.inject.Inject; import org.testng.annotations.Guice; import org.testng.annotations.Test; @Guice(modules = SecondModuleSample.SecondModule.class) public class SecondModuleSample { static class SecondModule extends AbstractModule { @Override protected void configure() { bind(String.class).toInstance(new String("Hello")); } } @Inject String value; @Test public void testInject() { assertThat(value).isEqualTo("Hello"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/000077500000000000000000000000001475274123300237215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/BaseConfigurable.java000066400000000000000000000013661475274123300277650ustar00rootroot00000000000000package test.hook; import java.lang.reflect.Method; import org.testng.IConfigurable; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public abstract class BaseConfigurable implements IConfigurable { static int m_hookCount = 0; static boolean m_bs = false; static boolean m_bt = false; static boolean m_bm = false; static boolean m_bc = false; static String m_methodName = null; @BeforeSuite public void bs() { m_bs = true; } @BeforeTest public void bt() { m_bt = true; } @BeforeMethod public void bm(Method m) { m_bm = true; } @BeforeClass public void bc() { m_bc = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/ConfigurableFailureTest.java000066400000000000000000000007201475274123300313330ustar00rootroot00000000000000package test.hook; import org.testng.Assert; import org.testng.IConfigureCallBack; import org.testng.ITestResult; import org.testng.annotations.Test; public class ConfigurableFailureTest extends BaseConfigurable { @Override public void run(IConfigureCallBack callBack, ITestResult testResult) { m_hookCount++; // Not calling the callback } @Test public void hookWasNotRun() { Assert.assertFalse(m_bc); Assert.assertFalse(m_bm); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/ConfigurableListener.java000066400000000000000000000011111475274123300306640ustar00rootroot00000000000000package test.hook; import java.lang.reflect.Method; import org.testng.IConfigurable; import org.testng.IConfigureCallBack; import org.testng.ITestResult; public class ConfigurableListener implements IConfigurable { static int m_hookCount = 0; static String m_methodName; @Override public void run(IConfigureCallBack callBack, ITestResult testResult) { m_hookCount++; Object[] parameters = callBack.getParameters(); if (parameters.length > 0) { m_methodName = ((Method) parameters[0]).getName(); } callBack.runConfigurationMethod(testResult); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/ConfigurableSuccessTest.java000066400000000000000000000012101475274123300313470ustar00rootroot00000000000000package test.hook; import java.lang.reflect.Method; import org.testng.IConfigurable; import org.testng.IConfigureCallBack; import org.testng.ITestResult; import org.testng.annotations.Test; /** Test harness for {@link IConfigurable} */ public class ConfigurableSuccessTest extends BaseConfigurable { @Override public void run(IConfigureCallBack callBack, ITestResult testResult) { m_hookCount++; Object[] parameters = callBack.getParameters(); if (parameters.length > 0) { m_methodName = ((Method) parameters[0]).getName(); } callBack.runConfigurationMethod(testResult); } @Test public void hookWasRun() {} } ConfigurableSuccessWithListenerTest.java000066400000000000000000000015731475274123300336460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hookpackage test.hook; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ConfigurableListener.class) public class ConfigurableSuccessWithListenerTest { static boolean m_bm = false; static boolean m_bc = false; static boolean m_bt; static boolean m_bs; @BeforeSuite public void bs() { m_bs = true; } @BeforeMethod public void bt() { m_bt = true; } @BeforeMethod public void bm(Method m) { m_bm = true; } @BeforeClass public void bc() { m_bc = true; } @Test public void hookWasRun() { Assert.assertEquals(ConfigurableListener.m_hookCount, 2); Assert.assertTrue(m_bc); Assert.assertTrue(m_bm); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookFailureTest.java000066400000000000000000000007731475274123300276430ustar00rootroot00000000000000package test.hook; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.annotations.Test; public class HookFailureTest implements IHookable { static boolean m_hook = false; static boolean m_testWasRun = false; @Override public void run(IHookCallBack callBack, ITestResult testResult) { m_hook = true; // Not invoking the callback: the method should not be run } @Test public void verify() { m_testWasRun = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookListener.java000066400000000000000000000005351475274123300271750ustar00rootroot00000000000000package test.hook; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; public class HookListener implements IHookable { public static boolean m_hook = false; @Override public void run(IHookCallBack callBack, ITestResult testResult) { m_hook = true; callBack.runTestMethod(testResult); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookSuccess599Test.java000066400000000000000000000020441475274123300301240ustar00rootroot00000000000000package test.hook; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test harness for {@link IHookable} * * @author Cedric Beust * @since Aug 01, 2006 */ public class HookSuccess599Test implements IHookable { static boolean m_hook = false; static boolean m_testWasRun = false; static String m_parameter = null; @Override public void run(IHookCallBack callBack, ITestResult testResult) { m_hook = true; Object[] parameters = callBack.getParameters(); if (parameters.length > 0) { m_parameter = parameters[0].toString(); } callBack.runTestMethod(testResult); } @DataProvider public Object[][] dp() { return new Object[][] {new Object[] {"foo"}}; } @Test(dataProvider = "dp", timeOut = 100) public void verify(String name) { m_testWasRun = true; Reporter.log("output from hook test.verify"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookSuccess862Test.java000066400000000000000000000021721475274123300301170ustar00rootroot00000000000000package test.hook; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.inject.Named; import org.testng.*; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class HookSuccess862Test implements IHookable { @Override public void run(IHookCallBack callBack, ITestResult testResult) { Method method = testResult.getMethod().getConstructorOrMethod().getMethod(); for (int i = 0; i < callBack.getParameters().length; i++) { Annotation[] annotations = method.getParameterAnnotations()[i]; for (Annotation annotation : annotations) { if (annotation instanceof Named) { Named named = (Named) annotation; callBack.getParameters()[0] = callBack.getParameters()[0] + named.value(); } } } callBack.runTestMethod(testResult); } @DataProvider public Object[][] dp() { return new Object[][] {new Object[] {"foo", "test"}}; } @Test(dataProvider = "dp") public void verify(@Named("bar") String bar, String test) { Assert.assertEquals(bar, "foobar"); Assert.assertEquals(test, "test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookSuccessTest.java000066400000000000000000000016141475274123300276570ustar00rootroot00000000000000package test.hook; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class HookSuccessTest implements IHookable { static boolean m_hook = false; static boolean m_testWasRun = false; static String m_parameter = null; @Override public void run(IHookCallBack callBack, ITestResult testResult) { m_hook = true; Object[] parameters = callBack.getParameters(); if (parameters.length > 0) { m_parameter = parameters[0].toString(); } callBack.runTestMethod(testResult); } @DataProvider public Object[][] dp() { return new Object[][] {new Object[] {"foo"}}; } @Test(dataProvider = "dp") public void verify(String name) { m_testWasRun = true; Reporter.log("output from hook test.verify"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookSuccessWithListenerTest.java000066400000000000000000000004321475274123300322160ustar00rootroot00000000000000package test.hook; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(HookListener.class) public class HookSuccessWithListenerTest { @Test public void verify() { Assert.assertTrue(HookListener.m_hook); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/HookableTest.java000066400000000000000000000077421475274123300271620ustar00rootroot00000000000000package test.hook; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import test.BaseTest; /** * Because IHookable and IConfigurable are global, it's safer to run them in a sub-TestNG object, * otherwise they will be run for your entire test suite... * * @author cbeust */ public class HookableTest extends BaseTest { @BeforeMethod public void bm() { HookSuccessTest.m_hook = false; HookSuccessTest.m_testWasRun = false; HookSuccessTest.m_parameter = null; HookSuccess599Test.m_hook = false; HookSuccess599Test.m_testWasRun = false; HookSuccess599Test.m_parameter = null; HookFailureTest.m_hook = false; HookFailureTest.m_testWasRun = false; HookListener.m_hook = false; BaseConfigurable.m_hookCount = 0; BaseConfigurable.m_bc = false; BaseConfigurable.m_bm = false; BaseConfigurable.m_bs = false; BaseConfigurable.m_bt = false; BaseConfigurable.m_methodName = null; ConfigurableListener.m_hookCount = 0; ConfigurableListener.m_methodName = null; ConfigurableSuccessWithListenerTest.m_bc = false; ConfigurableSuccessWithListenerTest.m_bm = false; } @Test public void hookSuccess() { addClass(HookSuccessTest.class); run(); verifyTests("Passed", new String[] {"verify"}, getPassedTests()); Assert.assertTrue(HookSuccessTest.m_hook); Assert.assertTrue(HookSuccessTest.m_testWasRun); Assert.assertEquals(HookSuccessTest.m_parameter, "foo"); } @Test(description = "https://github.com/cbeust/testng/issues/599") public void issue599() { addClass(HookSuccess599Test.class); run(); verifyTests("Passed", new String[] {"verify"}, getPassedTests()); Assert.assertTrue(HookSuccess599Test.m_hook); Assert.assertTrue(HookSuccess599Test.m_testWasRun); Assert.assertEquals(HookSuccess599Test.m_parameter, "foo"); } @Test(description = "https://github.com/cbeust/testng/pull/862") public void issue862() { addClass(HookSuccess862Test.class); run(); verifyTests("Passed", new String[] {"verify"}, getPassedTests()); } @Test public void hookSuccessWithListener() { addClass(HookSuccessWithListenerTest.class); run(); verifyTests("Passed", new String[] {"verify"}, getPassedTests()); Assert.assertTrue(HookListener.m_hook); } @Test public void hookFailure() { addClass(HookFailureTest.class); run(); // To investigate: TestNG still thinks the test passed since it can't know whether // the hook ended up invoking the test or not. // verifyTests("Passed", new String[] { }, getPassedTests()); Assert.assertTrue(HookFailureTest.m_hook); Assert.assertFalse(HookFailureTest.m_testWasRun); } @Test public void configurableSuccess() { addClass(ConfigurableSuccessTest.class); run(); Assert.assertEquals(BaseConfigurable.m_hookCount, 4); Assert.assertTrue(BaseConfigurable.m_bc); Assert.assertTrue(BaseConfigurable.m_bm); Assert.assertTrue(BaseConfigurable.m_bs); Assert.assertTrue(BaseConfigurable.m_bt); Assert.assertEquals(BaseConfigurable.m_methodName, "hookWasRun"); } @Test public void configurableSuccessWithListener() { addClass(ConfigurableSuccessWithListenerTest.class); run(); Assert.assertEquals(ConfigurableListener.m_hookCount, 4); Assert.assertTrue(ConfigurableSuccessWithListenerTest.m_bs); Assert.assertTrue(ConfigurableSuccessWithListenerTest.m_bt); Assert.assertTrue(ConfigurableSuccessWithListenerTest.m_bc); Assert.assertTrue(ConfigurableSuccessWithListenerTest.m_bm); Assert.assertEquals(ConfigurableListener.m_methodName, "hookWasRun"); } @Test public void configurableFailure() { addClass(ConfigurableFailureTest.class); run(); Assert.assertEquals(BaseConfigurable.m_hookCount, 4); Assert.assertFalse(BaseConfigurable.m_bc); Assert.assertFalse(BaseConfigurable.m_bm); Assert.assertFalse(BaseConfigurable.m_bs); Assert.assertFalse(BaseConfigurable.m_bt); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2251/000077500000000000000000000000001475274123300253635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2251/AbstractBaseTestCase.java000066400000000000000000000024741475274123300322270ustar00rootroot00000000000000package test.hook.issue2251; import java.lang.reflect.InvocationTargetException; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; /** * This test class apes on a bare essential What Spring TestNG provides as a base class in terms of * running Spring based tests. The following methods have been duplicated from * org.springframework.test.context.testng.AbstractTestNGSpringContextTests to simulate the bug. 1. * throwAsUncheckedException() 2. getTestResultException() 3. throwAs() */ public class AbstractBaseTestCase implements IHookable { @Override public void run(IHookCallBack callBack, ITestResult testResult) { callBack.runTestMethod(testResult); Throwable t = getTestResultException(testResult); if (t != null) { throwAsUncheckedException(t); } } @SuppressWarnings("unchecked") private void throwAs(Throwable t) throws T { throw (T) t; } private void throwAsUncheckedException(Throwable t) { throwAs(t); } private Throwable getTestResultException(ITestResult testResult) { Throwable testResultException = testResult.getThrowable(); if (testResultException instanceof InvocationTargetException) { testResultException = testResultException.getCause(); } return testResultException; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2251/IssueTest.java000066400000000000000000000011271475274123300301570ustar00rootroot00000000000000package test.hook.issue2251; import org.assertj.core.api.Assertions; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2251") public void runTest() { TestNG testng = create(SampleTestCase.class); TestListenerAdapter l = new TestListenerAdapter(); testng.addListener(l); testng.run(); Throwable t = l.getFailedTests().get(0).getThrowable(); Assertions.assertThat(t).isInstanceOf(NullPointerException.class); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2251/SampleTestCase.java000066400000000000000000000006321475274123300311040ustar00rootroot00000000000000package test.hook.issue2251; import org.testng.annotations.Test; public class SampleTestCase extends AbstractBaseTestCase { static class NullExObj { @Override public String toString() { throw new NullPointerException("expected"); } } @Test(timeOut = 1000000) // removing timeout fixes error output public void testError() throws Exception { new NullExObj().toString(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2257/000077500000000000000000000000001475274123300253715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2257/IssueTest.java000066400000000000000000000012451475274123300301660ustar00rootroot00000000000000package test.hook.issue2257; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2257") public void ensureConfigurationsCanBeRetriedViaCallBacks() { TestNG testng = create(TestClassSample.class); TestListenerAdapter listener = new TestListenerAdapter(); testng.run(); assertThat(listener.getConfigurationSkips()).isEmpty(); assertThat(listener.getConfigurationFailures()).isEmpty(); assertThat(testng.getStatus()).isEqualTo(0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2257/TestClassSample.java000066400000000000000000000023731475274123300313100ustar00rootroot00000000000000package test.hook.issue2257; import org.testng.Assert; import org.testng.IConfigurable; import org.testng.IConfigureCallBack; import org.testng.ITestResult; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class TestClassSample implements IConfigurable { private int counter = 1; @Override public void run(IConfigureCallBack callBack, ITestResult testResult) { callBack.runConfigurationMethod(testResult); if (testResult.getThrowable() != null) { for (int i = 0; i <= 3; i++) { callBack.runConfigurationMethod(testResult); if (testResult.getThrowable() == null) { break; } } } } @BeforeSuite public void beforeSuite() { runConfiguration(); } @BeforeTest public void beforeTest() { runConfiguration(); } @BeforeClass public void beforeClass() { runConfiguration(); } @BeforeMethod public void beforeMethod() { runConfiguration(); } @Test public void runTest() {} private void runConfiguration() { if (counter++ == 2) { counter = 1; } else { Assert.fail(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2266/000077500000000000000000000000001475274123300253715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2266/IssueTest.java000066400000000000000000000012631475274123300301660ustar00rootroot00000000000000package test.hook.issue2266; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2266") public void ensureTestsCanBeRetriedViaCallBacks() { TestNG testng = create(TestClassSample.class); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); assertThat(listener.getFailedTests()).isEmpty(); assertThat(listener.getSkippedTests()).isEmpty(); assertThat(listener.getPassedTests()).hasSize(1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/hook/issue2266/TestClassSample.java000066400000000000000000000013321475274123300313020ustar00rootroot00000000000000package test.hook.issue2266; import org.testng.Assert; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.annotations.Test; public class TestClassSample implements IHookable { private int counter = 1; @Override public void run(IHookCallBack callBack, ITestResult testResult) { callBack.runTestMethod(testResult); if (testResult.getThrowable() != null) { for (int i = 0; i <= 3; i++) { callBack.runTestMethod(testResult); if (testResult.getThrowable() == null) { break; } } } } @Test(description = "GITHUB-2266") public void runTest() { if (counter++ != 2) { Assert.fail(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/000077500000000000000000000000001475274123300242445ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ChildClassTestSample.java000066400000000000000000000002601475274123300311200ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Ignore; @Ignore public class ChildClassTestSample extends ParentClassTestSample { @Override protected void hook() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ChildSample.java000066400000000000000000000002311475274123300272700ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Test; public class ChildSample extends IgnoreClassParentSample { @Test public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/IgnoreClassParentSample.java000066400000000000000000000002711475274123300316340ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Ignore; import org.testng.annotations.Test; @Ignore public class IgnoreClassParentSample { @Test public void parentTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/IgnoreClassSample.java000066400000000000000000000003441475274123300304630ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Ignore; import org.testng.annotations.Test; @Ignore public class IgnoreClassSample extends ParentSample { @Test public void test() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/IgnoreTest.java000066400000000000000000000057061475274123300272020ustar00rootroot00000000000000package test.ignore; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.InvokedMethodListener; import test.SimpleBaseTest; import test.ignore.ignorePackage.IgnorePackageSample; import test.ignore.ignorePackage.subPackage.SubPackageSample; import test.ignore.issue2396.FirstTest; import test.ignore.issue2613.LocalClassListener; import test.ignore.issue2613.SampleTestClassWithEnabledDisabledIgnoredTestMethods; import test.ignore.issue2613.SampleTestClassWithEnabledIgnoredTestMethods; public class IgnoreTest extends SimpleBaseTest { @Test public void ignore_class_should_not_run_tests() { InvokedMethodListener listener = runTest(IgnoreClassSample.class); assertThat(listener.getInvokedMethods()).isEmpty(); } @Test public void ignore_class_with_inheritance_should_not_run_tests() { InvokedMethodListener listener = runTest(ChildSample.class); assertThat(listener.getInvokedMethods()).isEmpty(); } @Test public void ignore_test_should_not_run_test() { InvokedMethodListener listener = runTest(IgnoreTestSample.class); assertThat(listener.getInvokedMethods()).containsExactly("test"); } @Test public void ignore_package_should_not_run_test() { InvokedMethodListener listener = runTest(IgnorePackageSample.class, SubPackageSample.class); assertThat(listener.getInvokedMethods()).isEmpty(); } @Test(description = "GITHUB-1709") public void test_parent_class_tests_ignored_when_ignored_at_child() { InvokedMethodListener listener = runTest(ChildClassTestSample.class); assertThat(listener.getInvokedMethods()).isEmpty(); } @Test(description = "GITHUB-2396") public void test_ignore_happens_for_class_level_methods() { InvokedMethodListener listener = runTest(FirstTest.class); assertThat(listener.getInvokedMethods()).containsExactly("testShouldBeInvoked"); } @Test(description = "GITHUB-2613", dataProvider = "getTestData") public void test_ignored_test_methods_are_retrieved_in_mixed_test_class( Class cls, String[] expected) { TestNG tng = create(cls); LocalClassListener listener = new LocalClassListener(); tng.addListener(listener); tng.run(); assertThat(listener.getMethods()).containsExactlyInAnyOrder(expected); } @DataProvider(name = "getTestData") public Object[][] getTestData() { return new Object[][] { { SampleTestClassWithEnabledDisabledIgnoredTestMethods.class, new String[] {"enabledTest", "disabledTest", "ignoredTest"} }, { SampleTestClassWithEnabledIgnoredTestMethods.class, new String[] {"enabledTest", "ignoredTest"} } }; } private static InvokedMethodListener runTest(Class... classes) { TestNG tng = create(classes); InvokedMethodListener listener = new InvokedMethodListener(); tng.addListener(listener); tng.run(); return listener; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/IgnoreTestSample.java000066400000000000000000000003261475274123300303350ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Ignore; import org.testng.annotations.Test; public class IgnoreTestSample { @Test public void test() {} @Test @Ignore public void ignoredTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ParentClassTestSample.java000066400000000000000000000004211475274123300313250ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Test; public class ParentClassTestSample { @Test public void testa() { hook(); } @Test public void testb() { hook(); } @Test public void testc() { hook(); } protected void hook() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ParentSample.java000066400000000000000000000002001475274123300274720ustar00rootroot00000000000000package test.ignore; import org.testng.annotations.Test; public class ParentSample { @Test public void parentTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ignorePackage/000077500000000000000000000000001475274123300270035ustar00rootroot00000000000000IgnorePackageSample.java000066400000000000000000000002611475274123300334270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ignorePackagepackage test.ignore.ignorePackage; import org.testng.annotations.Test; public class IgnorePackageSample { @Test public void test() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ignorePackage/package-info.java000066400000000000000000000001221475274123300321650ustar00rootroot00000000000000@Ignore package test.ignore.ignorePackage; import org.testng.annotations.Ignore; jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ignorePackage/subPackage/000077500000000000000000000000001475274123300310505ustar00rootroot00000000000000SubPackageSample.java000066400000000000000000000002271475274123300350040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/ignorePackage/subPackagepackage test.ignore.ignorePackage.subPackage; import org.testng.annotations.Test; public class SubPackageSample { @Test public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/issue2396/000077500000000000000000000000001475274123300257205ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/issue2396/FirstTest.java000066400000000000000000000003611475274123300305120ustar00rootroot00000000000000package test.ignore.issue2396; import org.testng.annotations.Ignore; import org.testng.annotations.Test; @Test public class FirstTest { public void testShouldBeInvoked() {} @Ignore public void testShouldBeIgnored(String name) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/issue2613/000077500000000000000000000000001475274123300257105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/issue2613/LocalClassListener.java000066400000000000000000000011201475274123300322730ustar00rootroot00000000000000package test.ignore.issue2613; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.testng.IClassListener; import org.testng.ITestClass; public class LocalClassListener implements IClassListener { private List methods; @Override public void onBeforeClass(ITestClass testClass) { methods = Arrays.stream(testClass.getTestMethods()) .map(each -> each.getConstructorOrMethod().getMethod().getName()) .collect(Collectors.toList()); } public List getMethods() { return methods; } } SampleTestClassWithEnabledDisabledIgnoredTestMethods.java000066400000000000000000000005051475274123300407760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/issue2613package test.ignore.issue2613; import org.testng.annotations.Ignore; import org.testng.annotations.Test; public class SampleTestClassWithEnabledDisabledIgnoredTestMethods { @Test public void enabledTest() {} @Test(enabled = false) public void disabledTest() {} @Test @Ignore public void ignoredTest() {} } SampleTestClassWithEnabledIgnoredTestMethods.java000066400000000000000000000004031475274123300373430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/ignore/issue2613package test.ignore.issue2613; import org.testng.annotations.Ignore; import org.testng.annotations.Test; public class SampleTestClassWithEnabledIgnoredTestMethods { @Test public void enabledTest() {} @Test @Ignore public void ignoredTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/000077500000000000000000000000001475274123300252525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/BaseClassScope.java000066400000000000000000000001451475274123300307470ustar00rootroot00000000000000package test.inheritance; import org.testng.annotations.Test; @Test public class BaseClassScope {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/Child_1.java000066400000000000000000000005171475274123300273630ustar00rootroot00000000000000package test.inheritance; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class Child_1 extends ZBase_0 { @BeforeMethod public void initDialog() { m_methodList.add("initDialog"); } @AfterMethod public void tearDownDialog() { m_methodList.add("tearDownDialog"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/ClassScopeTest.java000066400000000000000000000005231475274123300310140ustar00rootroot00000000000000package test.inheritance; import org.testng.Assert; import org.testng.annotations.Test; public class ClassScopeTest extends BaseClassScope { private boolean m_verify = false; public void setVerify() { m_verify = true; } @Test(dependsOnMethods = "setVerify") public void verify() { Assert.assertTrue(m_verify); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/DChild_2.java000066400000000000000000000013101475274123300274600ustar00rootroot00000000000000package test.inheritance; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Make sure that configuration inherited methods are invoked in the right order. The funny naming * is to make sure that the class names do not play any role in the ordering of methods. * *

Created on Sep 8, 2005 * * @author cbeust */ public class DChild_2 extends Child_1 { @BeforeMethod public void initDialog2() { m_methodList.add("initDialog2"); } @AfterMethod public void tearDownDialog2() { m_methodList.add("tearDownDialog2"); } @Test(groups = {"before"}) public void test() { m_methodList.add("test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/InheritanceConfigTest.java000066400000000000000000000015261475274123300323400ustar00rootroot00000000000000package test.inheritance; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlTest; import test.SampleInheritance; import test.SimpleBaseTest; public class InheritanceConfigTest extends SimpleBaseTest { @Test public void testMethod() { XmlTest xmlTest = createXmlTest("xml_suite", "xml_test"); xmlTest.setXmlClasses(Collections.singletonList(new XmlClass(SampleInheritance.class))); xmlTest.addIncludedGroup("configuration0"); xmlTest.addIncludedGroup("configuration1"); xmlTest.addIncludedGroup("inheritedTestMethod"); xmlTest.addIncludedGroup("final"); TestNG tng = create(xmlTest.getSuite()); tng.run(); assertThat(tng.getStatus()).isEqualTo(0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/VerifyTest.java000066400000000000000000000011341475274123300302200ustar00rootroot00000000000000package test.inheritance; import java.util.List; import org.testng.AssertJUnit; import org.testng.annotations.Test; public class VerifyTest { @Test(dependsOnGroups = {"before"}) public void verify() { String[] expected = { "initApplication", "initDialog", "initDialog2", "test", "tearDownDialog2", "tearDownDialog", "tearDownApplication" }; int i = 0; List l = ZBase_0.getMethodList(); AssertJUnit.assertEquals(expected.length, l.size()); for (String s : l) { AssertJUnit.assertEquals(expected[i++], s); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/ZBase_0.java000066400000000000000000000012251475274123300273400ustar00rootroot00000000000000package test.inheritance; import java.util.ArrayList; import java.util.List; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; public class ZBase_0 { protected static List m_methodList = new ArrayList<>(); @BeforeTest public void beforeTest() { m_methodList = new ArrayList<>(); } @BeforeMethod public void initApplication() { m_methodList.add("initApplication"); } @AfterMethod public void tearDownApplication() { m_methodList.add("tearDownApplication"); } public static List getMethodList() { return m_methodList; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949/000077500000000000000000000000001475274123300270025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949/ChildClassSample.java000066400000000000000000000003171475274123300330210ustar00rootroot00000000000000package test.inheritance.github949; import org.testng.annotations.Test; public class ChildClassSample extends ParentClassSample { @Override @Test public void independent() { logMessage(); } } ChildClassWithAlwasyRunEnabledSample.java000066400000000000000000000003671475274123300367240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949package test.inheritance.github949; import org.testng.annotations.Test; public class ChildClassWithAlwasyRunEnabledSample extends ParentClassWithAlwasyRunEnabledSample { @Override @Test public void independent() { logMessage(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949/CommonBaseClass.java000066400000000000000000000007761475274123300326700ustar00rootroot00000000000000package test.inheritance.github949; import java.util.ArrayList; import java.util.List; import org.testng.ITestResult; import org.testng.Reporter; public class CommonBaseClass { static List messages = new ArrayList<>(); protected static void logMessage() { ITestResult iTestResult = Reporter.getCurrentTestResult(); String method = iTestResult.getMethod().getMethodName(); String clazz = iTestResult.getMethod().getTestClass().getName(); messages.add(clazz + "." + method); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949/Github949Test.java000066400000000000000000000015241475274123300321770ustar00rootroot00000000000000package test.inheritance.github949; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; public class Github949Test extends SimpleBaseTest { @Test(dataProvider = "getdata") public void runTest(Class child) { TestNG testng = create(child); testng.run(); String prefix = child.getName() + "."; assertThat(CommonBaseClass.messages) .containsExactly(prefix + "independent", prefix + "dependent"); } @AfterMethod public void cleanup() { CommonBaseClass.messages.clear(); } @DataProvider public Object[][] getdata() { return new Object[][] {{ChildClassSample.class}, {ChildClassWithAlwasyRunEnabledSample.class}}; } } ParentClassSample.java000066400000000000000000000004361475274123300331520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949package test.inheritance.github949; import org.testng.annotations.Test; public class ParentClassSample extends CommonBaseClass { @Test public void independent() { logMessage(); } @Test(dependsOnMethods = "independent") public void dependent() { logMessage(); } } ParentClassWithAlwasyRunEnabledSample.java000066400000000000000000000005041475274123300371230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github949package test.inheritance.github949; import org.testng.annotations.Test; public class ParentClassWithAlwasyRunEnabledSample extends CommonBaseClass { @Test public void independent() { logMessage(); } @Test(dependsOnMethods = "independent", alwaysRun = true) public void dependent() { logMessage(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github980/000077500000000000000000000000001475274123300267755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github980/ChildClassSample.java000066400000000000000000000004331475274123300330130ustar00rootroot00000000000000package test.inheritance.github980; import org.testng.Assert; import org.testng.annotations.Test; public class ChildClassSample extends ParentClassSample { @Test public void c() { Assert.assertTrue(true); } @Test public void d() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github980/Github980Test.java000066400000000000000000000025111475274123300321620ustar00rootroot00000000000000package test.inheritance.github980; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class Github980Test extends SimpleBaseTest { @Test public void testToEnsureDuplicateMethodsAreNotExecuted() { XmlSuite suite = createXmlSuite("980_suite"); XmlTest xmltest = createXmlTest(suite, "980_test"); XmlClass parentClass = createXmlClass(xmltest, ParentClassSample.class); createXmlInclude(parentClass, "a"); createXmlInclude(parentClass, "b"); XmlClass childClass = createXmlClass(xmltest, ChildClassSample.class); createXmlInclude(childClass, "c"); createXmlInclude(childClass, "d"); InvokedMethodNameListener listener = new InvokedMethodNameListener(); TestNG tng = create(suite); tng.addListener(listener); tng.run(); List parentClassMethods = listener.getMethodsForTestClass(ParentClassSample.class); assertThat(parentClassMethods).containsExactly("a", "b"); List childClassMethods = listener.getMethodsForTestClass(ChildClassSample.class); assertThat(childClassMethods).containsExactly("c", "d"); } } ParentClassSample.java000066400000000000000000000004021475274123300331360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/github980package test.inheritance.github980; import org.testng.Assert; import org.testng.annotations.Test; public class ParentClassSample { @Test public void a() { Assert.assertTrue(true); } @Test public void b() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/issue2489/000077500000000000000000000000001475274123300267315ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/issue2489/IssueTest.java000066400000000000000000000030431475274123300315240ustar00rootroot00000000000000package test.inheritance.issue2489; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlPackage; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import test.inheritance.issue2489.tests.BaseClassA; import test.inheritance.issue2489.tests.TestClassA; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2489") public void verifyConfigInvocationOrderInInheritance() { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("2489_suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "2489_test"); XmlPackage xmlPackage = new XmlPackage(); xmlPackage.setName(TestClassA.class.getPackage().getName() + ".*"); xmlTest.setPackages(Collections.singletonList(xmlPackage)); TestNG testng = create(xmlSuite); testng.run(); List expected = Arrays.asList( "beforeSuite_BaseClass_A", "beforeClasses_BaseClass_A", "beforeClass_TestClass_A", "beforeMethod_TestClass_A", "test1_TestClass_A", "afterMethod_TestClass_A", "beforeMethod_TestClass_A", "test2_TestClass_A", "afterMethod_TestClass_A", "afterClass_TestClass_A", "afterClasses_BaseClass_A", "afterSuite_BaseClass_A"); assertThat(BaseClassA.logs).containsExactlyElementsOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/issue2489/tests/000077500000000000000000000000001475274123300300735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/issue2489/tests/BaseClassA.java000066400000000000000000000015401475274123300326770ustar00rootroot00000000000000package test.inheritance.issue2489.tests; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.testng.collections.Lists; public class BaseClassA { public static final List logs = Lists.newArrayList(); @BeforeSuite(groups = "a") public void beforeSuite() { print("beforeSuite_BaseClass_A"); } @AfterSuite(groups = "a") public void afterSuite() { print("afterSuite_BaseClass_A"); } @BeforeClass(groups = "a") public void beforeAllClasses() { print("beforeClasses_BaseClass_A"); } @AfterClass(groups = "a") public void afterAllClasses() { print("afterClasses_BaseClass_A"); } protected synchronized void print(String message) { logs.add(message); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/issue2489/tests/TestClassA.java000066400000000000000000000015511475274123300327460ustar00rootroot00000000000000package test.inheritance.issue2489.tests; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestClassA extends BaseClassA { @BeforeClass(groups = "a") public void beforeClass() { print("beforeClass_TestClass_A"); } @AfterClass(groups = "a") public void afterClass() { print("afterClass_TestClass_A"); } @BeforeMethod(groups = "a") public void beforeMethod() { print("beforeMethod_TestClass_A"); } @AfterMethod(groups = "a") public void afterMethod() { print("afterMethod_TestClass_A"); } @Test(groups = "a") public void test1() { print("test1_TestClass_A"); } @Test(groups = "a") public void test2() { print("test2_TestClass_A"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng234/000077500000000000000000000000001475274123300270075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng234/ChildTest.java000066400000000000000000000005771475274123300315460ustar00rootroot00000000000000package test.inheritance.testng234; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ChildTest extends ParentTest { @BeforeClass public void beforeClassMethod() { Assert.assertTrue(false, "This is so sad... I must skip all my tests ..."); } @Override @Test public void polymorphicMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng234/ParentTest.java000066400000000000000000000003241475274123300317420ustar00rootroot00000000000000package test.inheritance.testng234; import org.testng.annotations.Test; public abstract class ParentTest { @Test public void executePolymorphicMethod() {} protected abstract void polymorphicMethod(); } PolymorphicFailureTest.java000066400000000000000000000013271475274123300342530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng234package test.inheritance.testng234; import java.util.Arrays; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class PolymorphicFailureTest extends SimpleBaseTest { @Test public void superclassFailureShouldCauseFailure() { TestNG tng = create(ChildTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); assertTestResultsEqual( tla.getSkippedTests(), Arrays.asList("polymorphicMethod", "executePolymorphicMethod")); Assert.assertEquals(0, tla.getPassedTests().size()); Assert.assertEquals(0, tla.getFailedTests().size()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/000077500000000000000000000000001475274123300270125ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/Class1.java000066400000000000000000000006641475274123300310110ustar00rootroot00000000000000package test.inheritance.testng471; import org.junit.Assert; import org.testng.annotations.*; public class Class1 extends SuperClass1 { @BeforeClass public void beforeClass1() {} @AfterClass public void afterClass1() {} @BeforeMethod public void beforeMethodClass1() {} @AfterMethod public void afterMethodClass1() { Assert.fail(); } @Test public void test1_1() {} @Test public void test1_2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/Class2.java000066400000000000000000000006051475274123300310050ustar00rootroot00000000000000package test.inheritance.testng471; import org.testng.annotations.*; public class Class2 extends SuperClass1 { @BeforeClass public void beforeClass2() {} @AfterClass public void afterClass2() {} @BeforeMethod public void beforeMethodClass2() {} @AfterMethod public void afterMethodClass2() {} @Test public void test2_1() {} @Test public void test2_2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/Class3.java000066400000000000000000000010641475274123300310060ustar00rootroot00000000000000package test.inheritance.testng471; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Class3 extends SuperClass2 { @BeforeClass public void beforeClass3() {} @AfterClass public void afterClass3() {} @BeforeMethod public void beforeMethodClass3() {} @AfterMethod public void afterMethodClass3() {} @Test public void test3_1() {} @Test public void test3_2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/SuperClass1.java000066400000000000000000000002431475274123300320210ustar00rootroot00000000000000package test.inheritance.testng471; import org.testng.annotations.BeforeClass; public class SuperClass1 { @BeforeClass public void beforeSuperClass1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/SuperClass2.java000066400000000000000000000002431475274123300320220ustar00rootroot00000000000000package test.inheritance.testng471; import org.testng.annotations.BeforeClass; public class SuperClass2 { @BeforeClass public void beforeSuperClass2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng471/TestNG471.java000066400000000000000000000031731475274123300312610ustar00rootroot00000000000000package test.inheritance.testng471; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class TestNG471 extends SimpleBaseTest { @Test public void test_classes_should_not_be_skipped_when_a_after_method_fails() { TestNG tng = create(Class1.class, Class2.class, Class3.class); tng.setPreserveOrder(true); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.setPreserveOrder(true); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).containsExactly("afterMethodClass1"); assertThat(listener.getSkippedMethodNames()).containsExactly("test1_2"); assertThat(listener.getSucceedMethodNames()) .containsExactly( "beforeSuperClass1", "beforeClass1", "beforeMethodClass1", "test1_1", // "afterMethodClass1" failed // "beforeMethodClass1", "test1_2" and "afterMethodClass1" skipped // "afterClass1" skipped "beforeSuperClass1", "beforeClass2", "beforeMethodClass2", "test2_1", "afterMethodClass2", "beforeMethodClass2", "test2_2", "afterMethodClass2", "afterClass2", "beforeSuperClass2", "beforeClass3", "beforeMethodClass3", "test3_1", "afterMethodClass3", "beforeMethodClass3", "test3_2", "afterMethodClass3", "afterClass3"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng739/000077500000000000000000000000001475274123300270215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng739/A.java000066400000000000000000000004341475274123300300450ustar00rootroot00000000000000package test.inheritance.testng739; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class A extends BaseClass { @BeforeClass public void beforeClassA() { Assert.fail(); } @Test public void testA() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng739/B.java000066400000000000000000000002211475274123300300400ustar00rootroot00000000000000package test.inheritance.testng739; import org.testng.annotations.Test; public class B extends BaseClass { @Test public void testB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng739/BaseClass.java000066400000000000000000000002371475274123300315260ustar00rootroot00000000000000package test.inheritance.testng739; import org.testng.annotations.BeforeClass; public class BaseClass { @BeforeClass public void beforeBaseClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inheritance/testng739/TestNG739.java000066400000000000000000000015461475274123300313010ustar00rootroot00000000000000package test.inheritance.testng739; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class TestNG739 extends SimpleBaseTest { @Test public void test_classes_should_be_skipped_when_a_before_class_fails() { TestNG tng = create(A.class, B.class); tng.setPreserveOrder(true); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.setPreserveOrder(true); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()) .containsExactly("beforeBaseClass", "beforeBaseClass", "testB"); assertThat(listener.getFailedMethodNames()).containsExactly("beforeClassA"); assertThat(listener.getSkippedMethodNames()).containsExactly("testA"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/000077500000000000000000000000001475274123300242355ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/Github1298Test.java000066400000000000000000000011611475274123300275050ustar00rootroot00000000000000package test.inject; import org.testng.Assert; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Github1298Test { @BeforeMethod public void setUp(ITestResult tr) { tr.setAttribute("class", getClass().getName()); tr.setAttribute("toString", tr.toString()); } @Test public void testPlugin() { ITestResult result = Reporter.getCurrentTestResult(); Assert.assertEquals(result.getAttribute("class").toString(), getClass().getName()); Assert.assertNotNull(result.getAttribute("toString")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/Github1649Test.java000066400000000000000000000105061475274123300275100ustar00rootroot00000000000000package test.inject; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class Github1649Test extends SimpleBaseTest { @Test public void testHappyFlowForNativeInjectionOnTestMethods() { Map> mapping = Maps.newHashMap(); mapping.put("m1", Collections.singletonList(Method.class.getName())); mapping.put("m2", Collections.singletonList(ITestContext.class.getName())); mapping.put("m3", Collections.singletonList(XmlTest.class.getName())); mapping.put("m4", Arrays.asList(ITestContext.class.getName(), XmlTest.class.getName())); mapping.put("m5", Arrays.asList(XmlTest.class.getName(), ITestContext.class.getName())); mapping.put("m6", Arrays.asList(Method.class.getName(), ITestContext.class.getName())); mapping.put("m7", Arrays.asList(ITestContext.class.getName(), Method.class.getName())); mapping.put("m8", Arrays.asList(Method.class.getName(), XmlTest.class.getName())); mapping.put("m9", Arrays.asList(XmlTest.class.getName(), Method.class.getName())); mapping.put( "m10", Arrays.asList( Method.class.getName(), XmlTest.class.getName(), ITestContext.class.getName())); mapping.put( "m11", Arrays.asList( Method.class.getName(), ITestContext.class.getName(), XmlTest.class.getName())); mapping.put( "m12", Arrays.asList( XmlTest.class.getName(), Method.class.getName(), ITestContext.class.getName())); mapping.put( "m13", Arrays.asList( XmlTest.class.getName(), ITestContext.class.getName(), Method.class.getName())); mapping.put( "m14", Arrays.asList( ITestContext.class.getName(), Method.class.getName(), XmlTest.class.getName())); mapping.put( "m15", Arrays.asList( ITestContext.class.getName(), XmlTest.class.getName(), Method.class.getName())); TestNG testng = create(HappyPathNativeInjectionTestSample.class); Github1649TestListener listener = new Github1649TestListener(); testng.addListener(listener); testng.run(); assertThat(listener.mapping).containsAllEntriesOf(mapping); } @Test public void testNegativeFlowForNativeInjectionOnTestMethods() { Map failures = Maps.newHashMap(); failures.put( "m1", "Cannot inject @Test annotated Method [m1] with [interface org.testng.ITestResult]."); failures.put("m2", "Cannot inject @Test annotated Method [m2] with [int]."); TestNG testng = create(NegativeNativeInjectionTestSample.class); Github1649TestListener listener = new Github1649TestListener(); testng.addListener(listener); testng.run(); assertThat(listener.failures).containsAllEntriesOf(failures); } public static class Github1649TestListener extends TestListenerAdapter implements IInvokedMethodListener { Map> mapping = Maps.newHashMap(); Map failures = Maps.newHashMap(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void onTestFailure(ITestResult testResult) { String methodName = testResult.getMethod().getMethodName(); String raw = testResult.getThrowable().getMessage(); String actual = raw.split("\n")[1]; failures.put(methodName, actual); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String methodName = testResult.getMethod().getMethodName(); List paramTypes = Lists.newArrayList(); for (Object parameter : testResult.getParameters()) { String value = parameter.getClass().getName(); if (parameter instanceof ITestContext) { value = ITestContext.class.getName(); } paramTypes.add(value); } mapping.put(methodName, paramTypes); } } } HappyPathNativeInjectionTestSample.java000066400000000000000000000022601475274123300337330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/injectpackage test.inject; import java.lang.reflect.Method; import org.testng.ITestContext; import org.testng.annotations.Test; import org.testng.xml.XmlTest; public class HappyPathNativeInjectionTestSample { @Test public void m1(Method object) {} @Test public void m2(ITestContext object) {} @Test public void m3(XmlTest object) {} @Test public void m4(ITestContext ctx, XmlTest xmlTest) {} @Test public void m5(XmlTest xmlTest, ITestContext ctx) {} @Test public void m6(Method method, ITestContext ctx) {} @Test public void m7(ITestContext ctx, Method method) {} @Test public void m8(Method method, XmlTest xmlTest) {} @Test public void m9(XmlTest xmlTest, Method method) {} @Test public void m10(Method method, XmlTest xmlTest, ITestContext ctx) {} @Test public void m11(Method method, ITestContext ctx, XmlTest xmlTest) {} @Test public void m12(XmlTest xmlTest, Method method, ITestContext ctx) {} @Test public void m13(XmlTest xmlTest, ITestContext ctx, Method method) {} @Test public void m14(ITestContext ctx, Method method, XmlTest xmlTest) {} @Test public void m15(ITestContext ctx, XmlTest xmlTest, Method method) {} } InjectAfterMethodWithTestResultSampleTest.java000066400000000000000000000020511475274123300352530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/injectpackage test.inject; import java.lang.reflect.Method; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class InjectAfterMethodWithTestResultSampleTest { static int m_success; @Test public void pass() {} @Test public void fail() { throw new RuntimeException(); } @Test public void skip() { throw new SkipException("Skipped"); } @BeforeClass public void init() { m_success = 3; } @BeforeMethod public void before(Method m, ITestResult r) { System.out.println("Before result: " + r); } @AfterMethod public void after(Method m, ITestResult r) { String name = m.getName(); if (("pass".equals(name) && r.getStatus() == ITestResult.SUCCESS) || ("fail".equals(name) && r.getStatus() == ITestResult.FAILURE) || ("skip".equals(name) && r.getStatus() == ITestResult.SKIP)) { m_success--; } } } InjectAfterMethodWithTestResultTest.java000066400000000000000000000006731475274123300341210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/injectpackage test.inject; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class InjectAfterMethodWithTestResultTest extends SimpleBaseTest { @Test public void verifyTestResultInjection() { TestNG tng = create(InjectAfterMethodWithTestResultSampleTest.class); tng.run(); Assert.assertEquals(0, InjectAfterMethodWithTestResultSampleTest.m_success); } } InjectBeforeAndAfterMethodsWithTestResultSampleTest.java000066400000000000000000000034611475274123300372120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/injectpackage test.inject; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.Map; import org.testng.Assert; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Maps; public class InjectBeforeAndAfterMethodsWithTestResultSampleTest { static int m_success; private ITestResult m_testResult; @Test public void pass() { Assert.assertEquals(Reporter.getCurrentTestResult().getAttribute("before"), 10); Assert.assertEquals(m_testResult.getAttribute("before"), 10); } @Test public void fail() { throw new RuntimeException(); } @Test public void skip() { throw new SkipException("Skipped"); } @BeforeClass public void init() { m_success = 3; } @BeforeMethod public void before(Method m, ITestResult r) { m_testResult = r; r.setAttribute("before", 10); } @AfterMethod public void after(Method m, ITestResult r) { String name = m.getName(); assertThat(m_testResult.getMethod()).isEqualTo(r.getMethod()); assertThat(attributesFrom(m_testResult)).isEqualTo(attributesFrom(r)); if (("pass".equals(name) && r.getStatus() == ITestResult.SUCCESS) || ("fail".equals(name) && r.getStatus() == ITestResult.FAILURE) || ("skip".equals(name) && r.getStatus() == ITestResult.SKIP)) { m_success--; } } private static Map attributesFrom(ITestResult r) { Map attributes = Maps.newHashMap(); for (String key : r.getAttributeNames()) { attributes.put(key, r.getAttribute(key)); } return attributes; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/InjectBeforeMethodTest.java000066400000000000000000000017501475274123300314430ustar00rootroot00000000000000package test.inject; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class InjectBeforeMethodTest { private int m_beforeIndex = 0; private int m_afterIndex = 0; private static final Object[][] DATA = { new Object[] {"a"}, new Object[] {"b"}, }; @BeforeMethod public void before(Object[] parameters) { Assert.assertEquals(DATA[m_beforeIndex], parameters); m_beforeIndex++; } @BeforeMethod public void before2(Object[] parameters, Method m) {} @BeforeMethod public void before3(Method m, Object[] parameters) {} @DataProvider public Object[][] dp() { return DATA; } @AfterMethod public void after(Object[] parameters) { Assert.assertEquals(DATA[m_afterIndex], parameters); m_afterIndex++; } @Test(dataProvider = "dp") public void f(String a) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/InjectDataProviderTest.java000066400000000000000000000024151475274123300314630ustar00rootroot00000000000000package test.inject; import java.util.Arrays; import java.util.Iterator; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test that injection works for data providers. * * @author Cedric Beust, Mar 3, 2010 */ public class InjectDataProviderTest { @DataProvider public Object[][] dp1() { return new Object[][] { new Object[] {1, "a"}, new Object[] {2, "b"}, }; } @Test(dataProvider = "dp1", enabled = true) public void dpObject1(Integer n, ITestContext ctx, String a) {} @Test(dataProvider = "dp1", enabled = true) public void dpObject2(ITestContext ctx, Integer n, String a) {} @Test(dataProvider = "dp1", enabled = true) public void dpObject3(Integer n, String a, ITestContext ctx) {} @DataProvider public Iterator dp2() { return Arrays.asList(new Object[] {1, "a"}, new Object[] {2, "b"}).iterator(); } @Test(dataProvider = "dp2", enabled = false) public void dpIterator1(Integer n, ITestContext ctx, String a) {} @Test(dataProvider = "dp2", enabled = false) public void dpIterator2(ITestContext ctx, Integer n, String a) {} @Test(dataProvider = "dp2", enabled = false) public void dpIterator3(Integer n, String a, ITestContext ctx) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/InjectTestContextTest.java000066400000000000000000000016441475274123300313660ustar00rootroot00000000000000package test.inject; import org.testng.Assert; import org.testng.ITestContext; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class InjectTestContextTest extends SimpleBaseTest { @Test(enabled = false) public void verifyTestContextInjection(ITestContext tc, XmlTest xmlTest) { TestNG tng = create(); tng.setTestClasses(new Class[] {Sample.class}); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.run(); Assert.assertEquals(xmlTest.getName(), "Injection"); Assert.assertEquals(tla.getPassedTests().size(), 1); Assert.assertEquals(tla.getPassedTests().get(0).getMethod().getMethodName(), "f"); } @Parameters("string") @Test public void injectionAndParameters(String s, ITestContext ctx) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/InjectTestResultTest.java000066400000000000000000000007001475274123300312100ustar00rootroot00000000000000package test.inject; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class InjectTestResultTest extends SimpleBaseTest { @Test public void verifyTestResultInjection() { TestNG tng = create(InjectBeforeAndAfterMethodsWithTestResultSampleTest.class); tng.run(); Assert.assertEquals(InjectBeforeAndAfterMethodsWithTestResultSampleTest.m_success, 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/NativeInjectionTest.java000066400000000000000000000051411475274123300310320ustar00rootroot00000000000000package test.inject; import static test.inject.NativeInjectionTestSamples.*; import org.testng.*; import org.testng.annotations.*; import test.SimpleBaseTest; public class NativeInjectionTest extends SimpleBaseTest { @Test(dataProvider = "getTestData") public void testBeforeSuiteInjection(Class clazz, String methodName, String expected) { TestNG tng = create(clazz); InjectionResultHolder holder = new InjectionResultHolder(); tng.addListener(holder); tng.setGroups("test"); tng.run(); Assert.assertTrue(holder.getErrorMessage().contains(expected + methodName)); } @DataProvider public Object[][] getTestData() { String variant1 = "Can inject only one of into a @%s annotated "; String variant2 = "Can inject only one of into a @%s annotated "; return new Object[][] { { BadBeforeSuiteSample.class, "beforeSuite", String.format(variant1, BeforeSuite.class.getSimpleName()) }, { BadBeforeTestSample.class, "beforeTest", String.format(variant1, BeforeTest.class.getSimpleName()) }, { BadBeforeClassSample.class, "beforeClass", String.format(variant1, BeforeClass.class.getSimpleName()) }, { BadBeforeMethodSample.class, "beforeMethod", String.format(variant2, BeforeMethod.class.getSimpleName()) }, { BadAfterMethodSample.class, "afterMethod", String.format(variant2, AfterMethod.class.getSimpleName()) }, { BadAfterClassSample.class, "afterClass", String.format(variant1, AfterClass.class.getSimpleName()) }, { BadAfterTestSample.class, "afterTest", String.format(variant1, AfterTest.class.getSimpleName()) }, { BadAfterSuiteSample.class, "afterSuite", String.format(variant1, AfterSuite.class.getSimpleName()) }, { BadBeforeGroupsSample.class, "beforeGroups", String.format(variant1, BeforeGroups.class.getSimpleName()) }, { BadAfterGroupsSample.class, "afterGroups", String.format(variant1, AfterGroups.class.getSimpleName()) } }; } public static class InjectionResultHolder extends TestListenerAdapter { private String errorMessage; String getErrorMessage() { return errorMessage; } @Override public void onConfigurationFailure(ITestResult itr) { this.errorMessage = itr.getThrowable().getMessage(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/NativeInjectionTestSamples.java000066400000000000000000000030471475274123300323620ustar00rootroot00000000000000package test.inject; import org.testng.annotations.*; class NativeInjectionTestSamples { public static class SimpleBase { @Test(groups = "test") public void testMethod() {} } public static class BadBeforeSuiteSample { @BeforeSuite(groups = "test") public void beforeSuite(int foo) {} } public static class BadBeforeTestSample { @BeforeTest(groups = "test") public void beforeTest(int foo) {} } public static class BadBeforeClassSample extends SimpleBase { @BeforeClass(groups = "test") public void beforeClass(int foo) {} } public static class BadBeforeMethodSample extends SimpleBase { @BeforeMethod(groups = "test") public void beforeMethod(int foo) {} } public static class BadAfterMethodSample extends SimpleBase { @AfterMethod(groups = "test") public void afterMethod(int foo) {} } public static class BadAfterClassSample extends SimpleBase { @AfterClass(groups = "test") public void afterClass(int foo) {} } public static class BadAfterTestSample extends SimpleBase { @AfterTest(groups = "test") public void afterTest(int foo) {} } public static class BadAfterSuiteSample extends SimpleBase { @AfterSuite(groups = "test") public void afterSuite(int foo) {} } public static class BadBeforeGroupsSample extends SimpleBase { @BeforeGroups(groups = "test") public void beforeGroups(int foo) {} } public static class BadAfterGroupsSample extends SimpleBase { @AfterGroups(groups = "test") public void afterGroups(int foo) {} } } NegativeNativeInjectionTestSample.java000066400000000000000000000003441475274123300336000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/injectpackage test.inject; import org.testng.ITestResult; import org.testng.annotations.Test; public class NegativeNativeInjectionTestSample { @Test public void m1(ITestResult result) {} @Test public void m2(int foo) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/NoInjectionTest.java000066400000000000000000000013661475274123300301650ustar00rootroot00000000000000package test.inject; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.NoInjection; import org.testng.annotations.Test; /** * Test the @NoInjection annotation. * * @author cbeust */ public class NoInjectionTest { @DataProvider(name = "provider") public Object[][] provide() throws Exception { return new Object[][] {{CC.class.getMethod("f")}}; } @Test(dataProvider = "provider") public void withoutInjection(@NoInjection Method m) { Assert.assertEquals(m.getName(), "f"); } @Test(dataProvider = "provider") public void withInjection(Method m) { Assert.assertEquals(m.getName(), "withInjection"); } } class CC { public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/inject/Sample.java000066400000000000000000000006641475274123300263270ustar00rootroot00000000000000package test.inject; import org.testng.Assert; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.annotations.Test; public class Sample { @Test public void f(ITestContext tc) { Assert.assertNotNull(tc); ITestNGMethod[] allMethods = tc.getAllTestMethods(); Assert.assertEquals(allMethods.length, 1); Assert.assertEquals(allMethods[0].getConstructorOrMethod().getName(), "f"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/interleavedorder/000077500000000000000000000000001475274123300263175ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/interleavedorder/BaseTestClass.java000066400000000000000000000004211475274123300316570ustar00rootroot00000000000000package test.interleavedorder; import org.testng.annotations.Test; public class BaseTestClass { @Test public void testOne() { InterleavedInvocationTest.LOG.add("test1"); } @Test public void testTwo() { InterleavedInvocationTest.LOG.add("test2"); } } InterleavedInvocationTest.java000066400000000000000000000030511475274123300342360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/interleavedorderpackage test.interleavedorder; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import test.BaseTest; import testhelper.OutputDirectoryPatch; public class InterleavedInvocationTest extends BaseTest { public static List LOG = new ArrayList<>(); @BeforeTest public void beforeTest() { LOG = new ArrayList<>(); } private void verifyInvocation(int number, List log, int index) { Assert.assertEquals(log.get(index), "beforeTestChild" + number + "Class"); Assert.assertTrue( ("test1".equals(log.get(index + 1)) && "test2".equals(LOG.get(index + 2))) || ("test2".equals(LOG.get(index + 1)) && "test1".equals(LOG.get(index + 2))), "test methods were not invoked correctly"); Assert.assertEquals(log.get(index + 3), "afterTestChild" + number + "Class"); } @Test public void invocationOrder() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = new TestNG(); testng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); testng.setTestClasses(new Class[] {TestChild1.class, TestChild2.class}); testng.addListener(tla); testng.run(); Assert.assertEquals(LOG.size(), 8, LOG.toString()); int number1 = "beforeTestChild1Class".equals(LOG.get(0)) ? 1 : 2; int number2 = number1 == 1 ? 2 : 1; verifyInvocation(number1, LOG, 0); verifyInvocation(number2, LOG, 4); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/interleavedorder/TestChild1.java000066400000000000000000000006401475274123300311260ustar00rootroot00000000000000package test.interleavedorder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class TestChild1 extends BaseTestClass { @BeforeClass public void beforeTestChildOneClass() { InterleavedInvocationTest.LOG.add("beforeTestChild1Class"); } @AfterClass public void afterTestChildOneClass() { InterleavedInvocationTest.LOG.add("afterTestChild1Class"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/interleavedorder/TestChild2.java000066400000000000000000000006401475274123300311270ustar00rootroot00000000000000package test.interleavedorder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class TestChild2 extends BaseTestClass { @BeforeClass public void beforeTestChildTwoClass() { InterleavedInvocationTest.LOG.add("beforeTestChild2Class"); } @AfterClass public void afterTestChildTwoClass() { InterleavedInvocationTest.LOG.add("afterTestChild2Class"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/interleavedorder/testng-order.xml000066400000000000000000000005111475274123300314530ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/000077500000000000000000000000001475274123300262035ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/DataProviderBase.java000066400000000000000000000011311475274123300322210ustar00rootroot00000000000000package test.invocationcount; import java.util.Arrays; import java.util.Iterator; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderBase { @Test(dataProvider = "dp") public void f(Integer n) {} @DataProvider public Object[][] dp() { return new Integer[][] {new Integer[] {0}, new Integer[] {1}, new Integer[] {2}}; } @Test(dataProvider = "dp2") public void f2(Integer n) {} @DataProvider public Iterator dp2() { return Arrays.asList(new Object[] {0}, new Object[] {1}, new Object[] {2}).iterator(); } } DataProviderFalseFalseTest.java000066400000000000000000000005101475274123300341350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class DataProviderFalseFalseTest extends DataProviderBase { @BeforeMethod(firstTimeOnly = false) public void beforeMethod() {} @AfterMethod(lastTimeOnly = false) public void afterMethod() {} } DataProviderFalseTrueTest.java000066400000000000000000000005061475274123300340270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class DataProviderFalseTrueTest extends DataProviderBase { @BeforeMethod(firstTimeOnly = false) public void beforeMethod() {} @AfterMethod(lastTimeOnly = true) public void afterMethod() {} } DataProviderTrueFalseTest.java000066400000000000000000000005061475274123300340270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class DataProviderTrueFalseTest extends DataProviderBase { @BeforeMethod(firstTimeOnly = true) public void beforeMethod() {} @AfterMethod(lastTimeOnly = false) public void afterMethod() {} } DataProviderTrueTrueTest.java000066400000000000000000000005041475274123300337120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class DataProviderTrueTrueTest extends DataProviderBase { @BeforeMethod(firstTimeOnly = true) public void beforeMethod() {} @AfterMethod(lastTimeOnly = true) public void afterMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/FailedInvocationCount.java000066400000000000000000000005341475274123300332770ustar00rootroot00000000000000package test.invocationcount; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class FailedInvocationCount { int m_count; @BeforeClass public void setUp() { m_count = 0; } @Test(invocationCount = 10) public void f() { if (m_count++ > 3) { throw new RuntimeException(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/FailedInvocationCount2.java000066400000000000000000000011501475274123300333540ustar00rootroot00000000000000package test.invocationcount; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class FailedInvocationCount2 { int m_count; int m_count2; @BeforeClass public void setUp() { m_count = 0; m_count2 = 0; } @Test(invocationCount = 10, skipFailedInvocations = true) public void shouldSkipFromAnnotation() { if (m_count++ > 3) { throw new RuntimeException(); } } @Test(invocationCount = 10, skipFailedInvocations = false) public void shouldNotSkipFromAnnotation() { if (m_count2++ > 3) { throw new RuntimeException(); } } } FailedInvocationCountTest.java000066400000000000000000000024201475274123300340540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class FailedInvocationCountTest extends SimpleBaseTest { private void runTest(boolean skip, int passed, int failed, int skipped) { TestNG testng = create(FailedInvocationCount.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.setSkipFailedInvocationCounts(skip); testng.addListener(tla); testng.run(); Assert.assertEquals(tla.getPassedTests().size(), passed); Assert.assertEquals(tla.getFailedTests().size(), failed); Assert.assertEquals(tla.getSkippedTests().size(), skipped); } @Test public void verifyGloballyShouldStop() { runTest(true, 4, 1, 5); } @Test public void verifyGloballyShouldNotStop() { runTest(false, 4, 6, 0); } @Test public void verifyAttributeShouldStop() { TestNG testng = create(FailedInvocationCount2.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); Assert.assertEquals(tla.getPassedTests().size(), 8); Assert.assertEquals(tla.getFailedTests().size(), 7); Assert.assertEquals(tla.getSkippedTests().size(), 5); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/FirstAndLastTimeTest.java000066400000000000000000000114251475274123300330660ustar00rootroot00000000000000package test.invocationcount; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.invocationcount.issue426.SampleTestClassWithNoThreadPoolSizeDefined; import test.invocationcount.issue426.SampleTestClassWithThreadPoolSizeDefined; /** * Test various combination of @BeforeMethod(firstTimeOnly = true/false) and * AfterMethod(lastTimeOnly = true/false) with invocation counts and data providers. */ public class FirstAndLastTimeTest extends SimpleBaseTest { @Test public void verifyDataProviderFalseFalse() { List invokedMethodNames = run(DataProviderFalseFalseTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f(0)", "afterMethod", "beforeMethod", "f(1)", "afterMethod", "beforeMethod", "f(2)", "afterMethod", "beforeMethod", "f2(0)", "afterMethod", "beforeMethod", "f2(1)", "afterMethod", "beforeMethod", "f2(2)", "afterMethod"); } @Test public void verifyDataProviderTrueFalse() { List invokedMethodNames = run(DataProviderTrueFalseTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f(0)", "afterMethod", "f(1)", "afterMethod", "f(2)", "afterMethod", "beforeMethod", "f2(0)", "afterMethod", "f2(1)", "afterMethod", "f2(2)", "afterMethod"); } @Test public void verifyDataProviderFalseTrue() { List invokedMethodNames = run(DataProviderFalseTrueTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f(0)", "beforeMethod", "f(1)", "beforeMethod", "f(2)", "afterMethod", "beforeMethod", "f2(0)", "beforeMethod", "f2(1)", "beforeMethod", "f2(2)", "afterMethod"); } @Test public void verifyDataProviderTrueTrue() { List invokedMethodNames = run(DataProviderTrueTrueTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f(0)", "f(1)", "f(2)", "afterMethod", "beforeMethod", "f2(0)", "f2(1)", "f2(2)", "afterMethod"); } @Test public void verifyInvocationCountFalseFalse() { List invokedMethodNames = run(InvocationCountFalseFalseTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f", "afterMethod", "beforeMethod", "f", "afterMethod", "beforeMethod", "f", "afterMethod"); } @Test public void verifyInvocationCountTrueFalse() { List invokedMethodNames = run(InvocationCountTrueFalseTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f", "afterMethod", "f", "afterMethod", "f", "afterMethod"); } @Test public void verifyInvocationCountFalseTrue() { List invokedMethodNames = run(InvocationCountFalseTrueTest.class); assertThat(invokedMethodNames) .containsExactly( "beforeMethod", "f", "beforeMethod", "f", "beforeMethod", "f", "afterMethod"); } @Test public void verifyInvocationCountTrueTrue() { List invokedMethodNames = run(InvocationCountTrueTrueTest.class); assertThat(invokedMethodNames).containsExactly("beforeMethod", "f", "f", "f", "afterMethod"); } @Test(dataProvider = "classNames", description = "GITHUB-426") public void verifyFirstTimeOnly(Class clazz) { List invokedMethodNames = run(clazz); String[] expected = new String[] {"beforeMethod", "testMethod", "testMethod"}; assertThat(invokedMethodNames).containsExactly(expected); } @DataProvider(name = "classNames") public Object[][] getClassNames() { return new Object[][] { {SampleTestClassWithNoThreadPoolSizeDefined.class}, {SampleTestClassWithThreadPoolSizeDefined.class} }; } private static List run(Class cls) { TestNG tng = create(cls); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); return listener.getInvokedMethodNames(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/InvocationBase.java000066400000000000000000000002261475274123300317520ustar00rootroot00000000000000package test.invocationcount; import org.testng.annotations.Test; public class InvocationBase { @Test(invocationCount = 3) public void f() {} } InvocationCountFalseFalseTest.java000066400000000000000000000005111475274123300346740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class InvocationCountFalseFalseTest extends InvocationBase { @BeforeMethod(firstTimeOnly = false) public void beforeMethod() {} @AfterMethod(lastTimeOnly = false) public void afterMethod() {} } InvocationCountFalseTrueTest.java000066400000000000000000000005071475274123300345660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class InvocationCountFalseTrueTest extends InvocationBase { @BeforeMethod(firstTimeOnly = false) public void beforeMethod() {} @AfterMethod(lastTimeOnly = true) public void afterMethod() {} } InvocationCountTrueFalseTest.java000066400000000000000000000005071475274123300345660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class InvocationCountTrueFalseTest extends InvocationBase { @BeforeMethod(firstTimeOnly = true) public void beforeMethod() {} @AfterMethod(lastTimeOnly = false) public void afterMethod() {} } InvocationCountTrueTrueTest.java000066400000000000000000000005051475274123300344510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcountpackage test.invocationcount; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class InvocationCountTrueTrueTest extends InvocationBase { @BeforeMethod(firstTimeOnly = true) public void beforeMethod() {} @AfterMethod(lastTimeOnly = true) public void afterMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue1719/000077500000000000000000000000001475274123300276555ustar00rootroot00000000000000DummyReporter.java000066400000000000000000000033321475274123300332600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue1719package test.invocationcount.issue1719; import java.util.List; import java.util.Set; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ITestResult; import org.testng.collections.Sets; import org.testng.xml.XmlSuite; public class DummyReporter implements IReporter { private Set failures = Sets.newHashSet(); private Set skip = Sets.newHashSet(); private Set success = Sets.newHashSet(); private Set failedWithinSuccessPercentage = Sets.newHashSet(); public void generateReport( List xmlSuites, List suites, String outputDirectory) { suites.forEach( iSuite -> iSuite .getResults() .values() .forEach( suiteResult -> { failures.addAll( suiteResult.getTestContext().getFailedTests().getAllResults()); skip.addAll(suiteResult.getTestContext().getSkippedTests().getAllResults()); success.addAll(suiteResult.getTestContext().getPassedTests().getAllResults()); failedWithinSuccessPercentage.addAll( suiteResult .getTestContext() .getFailedButWithinSuccessPercentageTests() .getAllResults()); })); } public Set getFailures() { return failures; } public Set getSkip() { return skip; } public Set getSuccess() { return success; } public Set getFailedWithinSuccessPercentage() { return failedWithinSuccessPercentage; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue1719/IssueTest.java000066400000000000000000000012431475274123300324500ustar00rootroot00000000000000package test.invocationcount.issue1719; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testSuccessPercentageCalculation() { TestNG testng = create(TestclassSample.class); DummyReporter listener = new DummyReporter(); testng.addListener(listener); testng.run(); assertThat(listener.getFailures()).isEmpty(); assertThat(listener.getSkip()).isEmpty(); assertThat(listener.getSuccess()).isEmpty(); assertThat(listener.getFailedWithinSuccessPercentage()).hasSize(5); } } TestclassSample.java000066400000000000000000000012071475274123300335500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue1719package test.invocationcount.issue1719; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestclassSample { @Test(successPercentage = 0, dataProvider = "dp") public void dataDrivenTestMethod(int i) { Assert.fail("Failing iteration:" + i); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } @Test(successPercentage = 0) public void simpleTestMethod() { Assert.fail(); } @Test(successPercentage = 0, invocationCount = 2) public void testMethodWithMultipleInvocations() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue426/000077500000000000000000000000001475274123300275675ustar00rootroot00000000000000SampleTestClassWithNoThreadPoolSizeDefined.java000066400000000000000000000005131475274123300406460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue426package test.invocationcount.issue426; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SampleTestClassWithNoThreadPoolSizeDefined { @BeforeMethod(firstTimeOnly = true) public void beforeMethod() {} @Test(invocationCount = 2, threadPoolSize = 5) public void testMethod() {} } SampleTestClassWithThreadPoolSizeDefined.java000066400000000000000000000004651475274123300403570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invocationcount/issue426package test.invocationcount.issue426; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SampleTestClassWithThreadPoolSizeDefined { @BeforeMethod(firstTimeOnly = true) public void beforeMethod() {} @Test(invocationCount = 2) public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/000077500000000000000000000000001475274123300273675ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/A.java000066400000000000000000000002551475274123300304140ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.annotations.BeforeSuite; public class A { @BeforeSuite(alwaysRun = false) public static void someMethod1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/B.java000066400000000000000000000003741475274123300304170ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; @Test(enabled = false) public class B extends A { @BeforeSuite public static void someMethod2() {} public void someTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/Base.java000066400000000000000000000021021475274123300310770ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class Base { private boolean m_fail; public Base(boolean fail) { m_fail = fail; } @BeforeMethod public void beforeMethod() {} @AfterMethod public void afterMethod() {} @BeforeTest public void beforeTest() {} @AfterTest public void afterTest() {} @BeforeClass public void beforeClass() {} @AfterClass public void afterClass() {} @BeforeSuite public void beforeSuite() {} @AfterSuite public void afterSuite() { if (m_fail) { throw new RuntimeException("After Suite FAILING"); } } @Test public void a() { if (m_fail) { throw new IllegalArgumentException("Test Method FAILING"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/C.java000066400000000000000000000003531475274123300304150ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; @Test public class C extends A { @BeforeSuite public static void someMethod3() {} public void someTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/Failure.java000066400000000000000000000001651475274123300316230ustar00rootroot00000000000000package test.invokedmethodlistener; public class Failure extends Base { public Failure() { super(true); } } InvokedMethodListener.java000066400000000000000000000012061475274123300344200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistenerpackage test.invokedmethodlistener; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.collections.Lists; public class InvokedMethodListener implements IInvokedMethodListener { private final List m_methods = Lists.newArrayList(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { m_methods.add(method); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) {} public List getInvokedMethods() { return m_methods; } } InvokedMethodListenerTest.java000066400000000000000000000130721475274123300352640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistenerpackage test.invokedmethodlistener; import java.util.List; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestNGListener; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class InvokedMethodListenerTest extends SimpleBaseTest { private static void run(Class[] classes, IInvokedMethodListener l) { TestNG tng = create(); tng.setTestClasses(classes); tng.addListener((ITestNGListener) l); tng.run(); } private static void assertMethodCount(MyListener l) { Assert.assertEquals(l.getBeforeCount(), 9); Assert.assertEquals(l.getAfterCount(), 9); } @Test public void withSuccess() { MyListener l = new MyListener(); run(new Class[] {Success.class}, l); assertMethodCount(l); } @Test public void withFailure() { MyListener l = new MyListener(); run(new Class[] {Failure.class}, l); assertMethodCount(l); Assert.assertEquals(l.getSuiteStatus(), ITestResult.FAILURE); Assert.assertTrue(null != l.getSuiteThrowable()); Assert.assertTrue(l.getSuiteThrowable().getClass() == RuntimeException.class); Assert.assertEquals(l.getMethodStatus(), ITestResult.FAILURE); Assert.assertTrue(null != l.getMethodThrowable()); Assert.assertTrue(l.getMethodThrowable().getClass() == IllegalArgumentException.class); } /** * Fix for: https://github.com/juherr/testng-googlecode/issues/7 * https://github.com/juherr/testng-googlecode/issues/86 * https://github.com/cbeust/testng/issues/93 */ @Test public void sameMethodInvokedMultipleTimesShouldHaveDifferentTimeStamps() { TestNG tng = create(Sample.class); InvokedMethodListener listener = new InvokedMethodListener(); tng.addListener((ITestNGListener) listener); tng.run(); List m = listener.getInvokedMethods(); IInvokedMethod beforeSuite = m.get(0); Assert.assertFalse(beforeSuite.getTestMethod().isAfterMethodConfiguration()); Assert.assertTrue(beforeSuite.isConfigurationMethod()); IInvokedMethod after1 = m.get(2); Assert.assertTrue(after1.getTestMethod().isAfterMethodConfiguration()); Assert.assertTrue(after1.isConfigurationMethod()); IInvokedMethod after2 = m.get(4); Assert.assertTrue(after2.getTestMethod().isAfterMethodConfiguration()); Assert.assertTrue(after2.isConfigurationMethod()); Assert.assertTrue(after1.getDate() != after2.getDate()); } @Test( description = "Test methods with expected exceptions should show up as pass" + " in IInvokedMethodListener's afterInvocation method") public void testMethodsWithExpectedExceptionsShouldShowUpAsPass() { TestNG tng = create(Sample2.class); Sample2.Sample2InvokedMethodListener l = new Sample2().new Sample2InvokedMethodListener(); tng.addListener((ITestNGListener) l); tng.run(); Assert.assertTrue(l.isSuccess); } @Test(description = "Invoked method does not recognize configuration method") public void issue629_InvokedMethodDoesNotRecognizeConfigurationMethod() { InvokedMethodNameListener l = new InvokedMethodNameListener(); run(new Class[] {Success.class}, l); Assert.assertEquals(l.testMethods.size(), 1); Assert.assertTrue(l.testMethods.contains("a")); Assert.assertEquals(l.testMethodsFromTM.size(), 1); Assert.assertTrue(l.testMethodsFromTM.contains("a")); Assert.assertEquals(l.configurationMethods.size(), 8); Assert.assertTrue(l.configurationMethods.contains("beforeMethod")); Assert.assertTrue(l.configurationMethods.contains("afterMethod")); Assert.assertTrue(l.configurationMethods.contains("beforeTest")); Assert.assertTrue(l.configurationMethods.contains("afterTest")); Assert.assertTrue(l.configurationMethods.contains("beforeClass")); Assert.assertTrue(l.configurationMethods.contains("afterClass")); Assert.assertTrue(l.configurationMethods.contains("beforeSuite")); Assert.assertTrue(l.configurationMethods.contains("afterSuite")); Assert.assertEquals(l.configurationMethodsFromTM.size(), 8); Assert.assertTrue(l.configurationMethodsFromTM.contains("beforeMethod")); Assert.assertTrue(l.configurationMethodsFromTM.contains("afterMethod")); Assert.assertTrue(l.configurationMethodsFromTM.contains("beforeTest")); Assert.assertTrue(l.configurationMethodsFromTM.contains("afterTest")); Assert.assertTrue(l.configurationMethodsFromTM.contains("beforeClass")); Assert.assertTrue(l.configurationMethodsFromTM.contains("afterClass")); Assert.assertTrue(l.configurationMethodsFromTM.contains("beforeSuite")); Assert.assertTrue(l.configurationMethodsFromTM.contains("afterSuite")); } @Test public void issue87_method_orderning_with_disable_test_class() { assertIssue87(A.class, B.class, C.class); assertIssue87(A.class, C.class, B.class); assertIssue87(B.class, A.class, C.class); } private void assertIssue87(Class... tests) { TestNG tng = create(tests); tng.setParallel(XmlSuite.ParallelMode.NONE); tng.setPreserveOrder(true); InvokedMethodListener listener = new InvokedMethodListener(); tng.addListener((ITestNGListener) listener); tng.run(); List m = listener.getInvokedMethods(); Assert.assertEquals(m.get(0).getTestMethod().getMethodName(), "someMethod1"); Assert.assertEquals(m.get(1).getTestMethod().getMethodName(), "someMethod3"); Assert.assertEquals(m.get(2).getTestMethod().getMethodName(), "someTest"); Assert.assertEquals(m.size(), 3); } } InvokedMethodNameListener.java000066400000000000000000000030441475274123300352230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistenerpackage test.invokedmethodlistener; import java.util.HashSet; import java.util.Set; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class InvokedMethodNameListener implements IInvokedMethodListener { final Set testMethods = new HashSet<>(); final Set configurationMethods = new HashSet<>(); final Set testMethodsFromTM = new HashSet<>(); final Set configurationMethodsFromTM = new HashSet<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String methodName = method.getTestMethod().getMethodName(); if (method.isTestMethod()) { testMethods.add(methodName); } if (method.isConfigurationMethod()) { configurationMethods.add(methodName); } if (method.getTestMethod().isTest()) { testMethodsFromTM.add(methodName); } if (method.getTestMethod().isBeforeMethodConfiguration() || method.getTestMethod().isAfterMethodConfiguration() || method.getTestMethod().isBeforeTestConfiguration() || method.getTestMethod().isAfterTestConfiguration() || method.getTestMethod().isBeforeClassConfiguration() || method.getTestMethod().isAfterClassConfiguration() || method.getTestMethod().isBeforeSuiteConfiguration() || method.getTestMethod().isAfterSuiteConfiguration()) { configurationMethodsFromTM.add(methodName); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/MyListener.java000066400000000000000000000025021475274123300323240ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class MyListener implements IInvokedMethodListener { private int m_beforeCount = 0; private int m_afterCount = 0; private Throwable suiteThrowable; private int suiteStatus = 0; private Throwable methodThrowable; private int methodStatus = 0; @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { m_afterCount++; if (method.getTestMethod().isAfterSuiteConfiguration()) { suiteStatus = testResult.getStatus(); suiteThrowable = testResult.getThrowable(); } if (method.getTestMethod().isTest()) { methodStatus = testResult.getStatus(); methodThrowable = testResult.getThrowable(); } } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { m_beforeCount++; } public int getBeforeCount() { return m_beforeCount; } public int getAfterCount() { return m_afterCount; } public Throwable getSuiteThrowable() { return suiteThrowable; } public int getSuiteStatus() { return suiteStatus; } public Throwable getMethodThrowable() { return methodThrowable; } public int getMethodStatus() { return methodStatus; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/Sample.java000066400000000000000000000011101475274123300314440ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class Sample { @Test public void t1() { try { Thread.sleep(100); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } @Test public void t2() { try { Thread.sleep(100); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } @AfterMethod public void am() {} @BeforeSuite public void bs() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/Sample2.java000066400000000000000000000015461475274123300315430ustar00rootroot00000000000000package test.invokedmethodlistener; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.Test; public class Sample2 { @Test(expectedExceptions = IllegalArgumentException.class) public void t1() { throw new IllegalArgumentException("Throw this exception on purpose in test"); } public class Sample2InvokedMethodListener implements IInvokedMethodListener { boolean isSuccess = false; /** {@inheritDoc} */ @Override public void afterInvocation(IInvokedMethod m, ITestResult tr) { isSuccess = tr.isSuccess(); } /** {@inheritDoc} */ @Override public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) { // no need to implement this right now } public boolean isSuccess() { return isSuccess; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/invokedmethodlistener/Success.java000066400000000000000000000001661475274123300316450ustar00rootroot00000000000000package test.invokedmethodlistener; public class Success extends Base { public Success() { super(false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue107/000077500000000000000000000000001475274123300243415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue107/Issue107Test.java000066400000000000000000000032101475274123300273600ustar00rootroot00000000000000package test.issue107; import java.util.Collections; import java.util.Map; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class Issue107Test extends SimpleBaseTest { @Test( description = "GITHUB-107, Check that suite parameters set from listener does not affects tests count") public void testSuiteParameterModificationFromListener() { final XmlSuite suite = createXmlSuite("Simple suite"); final Map parameters = suite.getParameters(); parameters.put( TestTestngCounter.PARAMETER_NAME, "some value that must be overriden in listener"); suite.setParameters(parameters); runTest(suite); } @Test( description = "GITHUB-107, Check that suite parameters modification from listener does not affects tests count") public void testSuiteParameterSetFromListener() { final XmlSuite suite = createXmlSuite("Simple suite"); runTest(suite); } private void runTest(XmlSuite suite) { final XmlTest test = createXmlTest(suite, "Simple Test", TestTestngCounter.class.getName()); suite.setTests(Collections.singletonList(test)); final TestListenerAdapter tla = new TestListenerAdapter(); final TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(suite)); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getFailedTests().size(), 0); Assert.assertEquals(tla.getPassedTests().size(), 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue107/MySuiteListener.java000066400000000000000000000010211475274123300303030ustar00rootroot00000000000000package test.issue107; import java.util.Map; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.xml.XmlSuite; public class MySuiteListener implements ISuiteListener { public void onFinish(ISuite suite) {} public void onStart(ISuite suite) { final XmlSuite xmlSuite = suite.getXmlSuite(); final Map parameters = xmlSuite.getParameters(); parameters.put(TestTestngCounter.PARAMETER_NAME, TestTestngCounter.EXPECTED_VALUE); xmlSuite.setParameters(parameters); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue107/TestTestngCounter.java000066400000000000000000000012541475274123300306520ustar00rootroot00000000000000package test.issue107; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @Listeners(MySuiteListener.class) public class TestTestngCounter { public static final String PARAMETER_NAME = "key1"; public static final String EXPECTED_VALUE = "zzz"; @Parameters({PARAMETER_NAME}) @Test public void testParameter(String key) { Assert.assertEquals(key, EXPECTED_VALUE); } @Parameters({PARAMETER_NAME}) @Test public void testParameterAsOptional(@Optional("Unknown") String key) { Assert.assertEquals(key, EXPECTED_VALUE); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue1430/000077500000000000000000000000001475274123300244215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue1430/TestFileToClass.java000066400000000000000000000006601475274123300302760ustar00rootroot00000000000000package test.issue1430; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.internal.ClassHelper; public class TestFileToClass { @Test public void testFileToClass() { Class c1 = this.getClass(); String p = c1.getResource("TestFileToClass.class").getPath(); Class c2 = ClassHelper.fileToClass(p); Assert.assertNotNull(c2); Assert.assertEquals(c1.getName(), c2.getName()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue565/000077500000000000000000000000001475274123300243515ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue565/Issue565Test.java000066400000000000000000000024121475274123300274030ustar00rootroot00000000000000package test.issue565; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import test.issue565.deadlock.ClassInGroupB; import test.issue565.deadlock.GeneratedClassFactory; public class Issue565Test extends SimpleBaseTest { @Test public void ThereShouldNotBeDeadlockWhenGroupByInstanceAndGroupDependencyUsed() throws Exception { XmlSuite suite = createXmlSuite("Deadlock-Suite"); suite.setParallel(ParallelMode.CLASSES); suite.setThreadCount(5); suite.setGroupByInstances(true); XmlTest test = createXmlTestWithPackages(suite, "Deadlock-Test", ClassInGroupB.class); // Prevent real deadlock suite.setTimeOut("1000"); test.setTimeOut(1_000); TestNG tng = create(suite); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getFailedTests().size(), 0); Assert.assertEquals(tla.getSkippedTests().size(), 0); Assert.assertEquals(tla.getPassedTests().size(), 2 + 4 * GeneratedClassFactory.SIZE); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue565/deadlock/000077500000000000000000000000001475274123300261175ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue565/deadlock/ClassInGroupB.java000066400000000000000000000003711475274123300314360ustar00rootroot00000000000000package test.issue565.deadlock; import org.testng.annotations.Test; @Test(groups = "B", dependsOnGroups = "A") public class ClassInGroupB { @Test public void groupB_1() {} @Test(dependsOnMethods = "groupB_1") public void groupB_2() {} } GeneratedClassFactory.java000066400000000000000000000010671475274123300331230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue565/deadlockpackage test.issue565.deadlock; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; public class GeneratedClassFactory { public static final int SIZE = 20; @DataProvider(name = "ids", parallel = true) public Object[][] ids() { Integer[][] params = new Integer[SIZE][1]; for (int id = 0; id < params.length; id++) { params[id] = new Integer[] {id}; } return params; } @Factory(dataProvider = "ids") public Object[] generate(int id) { return new Object[] {new GeneratedClassInGroupA(id)}; } } GeneratedClassInGroupA.java000066400000000000000000000012001475274123300331650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/issue565/deadlockpackage test.issue565.deadlock; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class GeneratedClassInGroupA { private final int id; public GeneratedClassInGroupA(int id) { this.id = id; } @BeforeClass(groups = "A") public void init() {} @Test(groups = "A") public void test1() {} @Test(groups = "A", dependsOnMethods = "test4") public void test2() {} @Test(groups = "A") public void test3() {} @Test(groups = "A", dependsOnMethods = "test3") public void test4() {} @Override public String toString() { return "GeneratedClassInGroupA{" + id + '}'; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jarpackages/000077500000000000000000000000001475274123300252345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jarpackages/JarPackagesTest.java000066400000000000000000000032221475274123300311110ustar00rootroot00000000000000package test.jarpackages; import java.io.File; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class JarPackagesTest extends SimpleBaseTest { private TestListenerAdapter init(String jarFile) { TestNG tng = create(); File currentDir = new File("."); String path = currentDir.getAbsolutePath(); char s = File.separatorChar; path = path + s + "test" + s + "src" + s + "test" + s + "jarpackages" + s; String finalPath = path + jarFile; tng.setTestJar(finalPath); TestListenerAdapter result = new TestListenerAdapter(); tng.addListener((ITestNGListener) result); tng.run(); return result; } @Test public void jarWithTestngXml() { TestListenerAdapter tla = init("withtestngxml.jar"); Assert.assertEquals(tla.getPassedTests().size(), 2); String first = tla.getPassedTests().get(0).getName(); String second = tla.getPassedTests().get(1).getName(); boolean fThenG = "f".equals(first) && "g".equals(second); boolean gThenF = "g".equals(first) && "f".equals(second); Assert.assertTrue(fThenG || gThenF); } @Test public void jarWithoutTestngXml() { TestListenerAdapter tla = init("withouttestngxml.jar"); Assert.assertEquals(tla.getPassedTests().size(), 2); String first = tla.getPassedTests().get(0).getName(); String second = tla.getPassedTests().get(1).getName(); boolean fThenG = "f".equals(first) && "g".equals(second); boolean gThenF = "g".equals(first) && "f".equals(second); Assert.assertTrue(fThenG || gThenF); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jarpackages/testng.xml000066400000000000000000000004261475274123300272640ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jarpackages/tests/000077500000000000000000000000001475274123300263765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jarpackages/tests/A.java000066400000000000000000000001671475274123300274250ustar00rootroot00000000000000package test.jarpackages.tests; import org.testng.annotations.Test; public class A { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jarpackages/tests/B.java000066400000000000000000000001671475274123300274260ustar00rootroot00000000000000package test.jarpackages.tests; import org.testng.annotations.Test; public class B { @Test public void g() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jason/000077500000000000000000000000001475274123300240735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jason/Main.java000066400000000000000000000005321475274123300256220ustar00rootroot00000000000000package test.jason; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class Main extends MainBase { public static boolean m_passed = false; @AfterClass public void afterClass() { m_passed = true; } @Test(description = "This test is run") public void test1() throws InterruptedException {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jason/MainBase.java000066400000000000000000000003021475274123300264100ustar00rootroot00000000000000package test.jason; import org.testng.annotations.Test; public class MainBase { @Test(description = "This test is never run but prevents AfterClass") public void checkReportsExist() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/jason/MainTest.java000066400000000000000000000014211475274123300264600ustar00rootroot00000000000000package test.jason; import java.util.Arrays; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class MainTest extends SimpleBaseTest { @Test public void afterClassShouldRun() { XmlSuite s = createXmlSuite("S"); XmlTest t = createXmlTest(s, "T", Main.class.getName()); XmlClass c = t.getXmlClasses().get(0); c.getIncludedMethods().add(new XmlInclude("test1")); t.setPreserveOrder(true); TestNG tng = create(); tng.setXmlSuites(Arrays.asList(new XmlSuite[] {s})); Main.m_passed = false; tng.run(); Assert.assertTrue(Main.m_passed); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/000077500000000000000000000000001475274123300241125ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/BaseTest.java000066400000000000000000000013761475274123300264760ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; /** * Base JUnit test case to verify TestNG handles TestCase hierarchies properly. * * @author mperham */ public abstract class BaseTest extends TestCase { private static int setUpInvokeCount = 0; private static int tearDownInvokeCount = 0; public BaseTest(String name) { super(name); } @Override protected void setUp() throws Exception { setUpInvokeCount++; } @Override protected void tearDown() throws Exception { tearDownInvokeCount++; } public abstract void testA(); public abstract void testB(); public static int getSetUpInvokeCount() { return setUpInvokeCount; } public static int getTearDownInvokeCount() { return tearDownInvokeCount; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/JUnitConstructorTest.java000066400000000000000000000013471475274123300311210ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; /** * Test that the correct number of constructors is called * *

Created on Aug 9, 2005 * * @author cbeust */ public class JUnitConstructorTest extends TestCase { private static int m_constructorCount = 0; private static int m_createCount = 0; private static int m_queryCount = 0; public JUnitConstructorTest(/*String string */ ) { m_constructorCount++; } public void testCreate() { m_createCount++; } public void testQuery() { m_queryCount++; } @Override public void tearDown() { assertEquals(3, m_constructorCount); assertTrue( (1 == m_createCount && 0 == m_queryCount) || (0 == m_createCount && 1 == m_queryCount)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/JUnitEmptyTest.java000066400000000000000000000005151475274123300276660ustar00rootroot00000000000000package test.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class JUnitEmptyTest extends TestCase { public JUnitEmptyTest(String name) { super(name); } public static Test suite() { TestSuite s = new TestSuite(JUnitEmptyTest.class); return s; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/MainSuite.java000066400000000000000000000005021475274123300266500ustar00rootroot00000000000000package test.junit; import junit.framework.Test; import junit.framework.TestSuite; public class MainSuite { public static Test suite() { TestSuite suite = new TestSuite("MainSuite"); suite.addTest(Suite1.suite()); suite.addTest(Suite2.suite()); suite.addTest(Suite3.suite()); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/SetNameTest.java000066400000000000000000000007001475274123300271460ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; import org.testng.Assert; public class SetNameTest extends TestCase { public static int m_ctorCount = 0; public SetNameTest() { m_ctorCount++; } @Override public void setName(String name) { super.setName(name); } public void testFoo() { Assert.assertEquals("testFoo", getName()); } public void testBar() { Assert.assertEquals("testBar", getName()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/SetUpExceptionSampleTest.java000066400000000000000000000004511475274123300316760ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class SetUpExceptionSampleTest extends TestCase { @Override protected void setUp() throws Exception { throw new RuntimeException(); } public void testM1() {} @Override protected void tearDown() throws Exception {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/SetUpExceptionTest.java000066400000000000000000000010351475274123300305330ustar00rootroot00000000000000package test.junit; import org.testng.annotations.Test; public class SetUpExceptionTest extends test.BaseTest { @Test public void setUpFailingShouldCauseMethodsToBeSkipped() { addClass("test.junit.SetUpExceptionSampleTest"); setJUnit(true); run(); String[] passed = {}; String[] failed = {"setUp"}; String[] skipped = {"testM1", "tearDown"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Skipped", skipped, getSkippedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/Suite1.java000066400000000000000000000005201475274123300261240ustar00rootroot00000000000000package test.junit; import junit.framework.Test; import junit.framework.TestSuite; public class Suite1 { public Suite1(String s) { // dummy } public static Test suite() { TestSuite suite = new TestSuite("JUnitSuite1"); suite.addTestSuite(TestAa.class); suite.addTestSuite(TestAb.class); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/Suite2.java000066400000000000000000000005001475274123300261230ustar00rootroot00000000000000package test.junit; import junit.framework.Test; import junit.framework.TestSuite; public class Suite2 { public static Test suite() { TestSuite suite = new TestSuite("Suite2"); suite.addTestSuite(TestAc.class); suite.addTestSuite(TestAd.class); suite.addTest(Suite3.suite()); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/Suite3.java000066400000000000000000000003641475274123300261340ustar00rootroot00000000000000package test.junit; import junit.framework.Test; import junit.framework.TestSuite; public class Suite3 { public static Test suite() { TestSuite suite = new TestSuite("Suite3"); suite.addTest(Suite4.suite()); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/Suite4.java000066400000000000000000000004351475274123300261340ustar00rootroot00000000000000package test.junit; import junit.framework.Test; import junit.framework.TestSuite; public class Suite4 { public static Test suite() { TestSuite suite = new TestSuite("Suite4"); suite.addTestSuite(TestAe.class); suite.addTestSuite(TestAf.class); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/TestAa.java000066400000000000000000000001741475274123300261400ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class TestAa extends TestCase { public void testAa1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/TestAb.java000066400000000000000000000001741475274123300261410ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class TestAb extends TestCase { public void testAb1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/TestAc.java000066400000000000000000000001741475274123300261420ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class TestAc extends TestCase { public void testAc1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/TestAd.java000066400000000000000000000001741475274123300261430ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class TestAd extends TestCase { public void testAd1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/TestAe.java000066400000000000000000000001741475274123300261440ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class TestAe extends TestCase { public void testAe1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/TestAf.java000066400000000000000000000001741475274123300261450ustar00rootroot00000000000000package test.junit; import junit.framework.TestCase; public class TestAf extends TestCase { public void testAf1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetup/000077500000000000000000000000001475274123300261525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetup/ATest.java000066400000000000000000000003701475274123300300350ustar00rootroot00000000000000package test.junit.testsetup; import junit.framework.TestCase; public class ATest extends TestCase { public void testIt() { System.out.println("A.testIt()"); Data d = TestSuiteContainerWrapper.getData(); assertEquals(3, d.i); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetup/Data.java000066400000000000000000000001111475274123300276570ustar00rootroot00000000000000package test.junit.testsetup; public class Data { public int i = 3; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetup/LayerATestSuite.java000066400000000000000000000005631475274123300320500ustar00rootroot00000000000000package test.junit.testsetup; import junit.framework.Test; import junit.framework.TestSuite; public class LayerATestSuite { public static Test suite() { TestSuite suite = new TestSuite("Layer A Test Suite"); suite.addTestSuite(ATest.class); TestSuiteContainerWrapper wrapper = new TestSuiteContainerWrapper(suite, Data.class); return wrapper; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetup/LoggingTestSuite.java000066400000000000000000000006571475274123300322650ustar00rootroot00000000000000package test.junit.testsetup; import junit.framework.Test; import junit.framework.TestResult; import junit.framework.TestSuite; public class LoggingTestSuite extends TestSuite { public LoggingTestSuite(String string) { super(string); } @Override public void run(TestResult result) { super.run(result); } @Override public void runTest(Test test, TestResult result) { super.runTest(test, result); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetup/SmokeSuite.java000066400000000000000000000010051475274123300311010ustar00rootroot00000000000000package test.junit.testsetup; import junit.framework.Test; import junit.framework.TestSuite; public class SmokeSuite extends LoggingTestSuite { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite("Smoke Test Suite"); suite.addTest(LayerATestSuite.suite()); return suite; } // public SmokeSuite() // { // this("SmokeSuite"); // } public SmokeSuite(String name) { super(name); } } TestSuiteContainerWrapper.java000066400000000000000000000020121475274123300340660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit/testsetuppackage test.junit.testsetup; import junit.extensions.TestSetup; import junit.framework.TestSuite; import org.testng.internal.objects.InstanceCreator; public class TestSuiteContainerWrapper extends TestSetup { private static Data INSTANCE = null; private static TestSuite _test = null; private static Class dataImpl = null; public TestSuiteContainerWrapper(TestSuite testSuite, Class dataImpl) { super(testSuite); _test = testSuite; TestSuiteContainerWrapper.dataImpl = dataImpl; } public static Data getData() { return INSTANCE; } @Override protected void setUp() throws Exception { System.out.println("setup"); INSTANCE = InstanceCreator.newInstance(dataImpl); } @Override protected void tearDown() throws Exception { System.out.println("teardown"); INSTANCE = null; System.out.println( _test.countTestCases() + " test cases defined by \"" + _test.getName() + "\" were executed."); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/000077500000000000000000000000001475274123300241765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/BeforeClassJUnit4Sample.java000066400000000000000000000006621475274123300314350ustar00rootroot00000000000000package test.junit4; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class BeforeClassJUnit4Sample { @BeforeClass public static void before() { throw new IllegalArgumentException("before failed"); } @AfterClass public static void after() { // throw new IllegalArgumentException("after failed"); } @Test public void myTest() { System.out.println("yay!"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/ClassRuleJUnit4Sample.java000066400000000000000000000010761475274123300311420ustar00rootroot00000000000000package test.junit4; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.ExternalResource; public class ClassRuleJUnit4Sample { @ClassRule public static ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { throw new IllegalArgumentException("before"); } @Override protected void after() { throw new IllegalArgumentException("after"); } }; @Test public void myTest() { System.out.println("yay!"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/InheritedTest.java000066400000000000000000000001371475274123300276150ustar00rootroot00000000000000package test.junit4; /** @author lukas */ public class InheritedTest extends JUnit4Sample1 {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/JUnit4Child.java000066400000000000000000000003401475274123300271170ustar00rootroot00000000000000package test.junit4; import org.junit.runners.Suite; /** @author lukas */ @Suite.SuiteClasses({JUnit4Sample1.class}) public class JUnit4Child extends JUnit4SampleSuite { public static final String[] EXPECTED = {"t1"}; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/JUnit4ParameterizedTest.java000066400000000000000000000021051475274123300315310ustar00rootroot00000000000000package test.junit4; import java.util.Arrays; import java.util.Collection; import org.junit.Assert; import org.junit.Assume; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class JUnit4ParameterizedTest { public static final String[] EXPECTED = {"t2[0]", "t2[1]", "t4[0]"}; public static final String[] SKIPPED = {"t3[0]", "t3[1]", "ta[0]", "ta[1]"}; public static final String[] FAILED = {"t4[1]", "tf[0]", "tf[1]"}; private int param; @Parameters public static Collection data() { return Arrays.asList(new Object[][] {{1}, {5}}); } public JUnit4ParameterizedTest(int param) { this.param = param; } @Test public void t2() {} @Test @Ignore public void t3() {} @Test public void t4() { if (param == 5) { Assert.fail("a test"); } } @Test public void tf() { Assert.fail("a test"); } @Test public void ta() { Assume.assumeTrue(false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/JUnit4Sample1.java000066400000000000000000000002011475274123300273720ustar00rootroot00000000000000package test.junit4; import org.junit.Test; /** @author lukas */ public class JUnit4Sample1 { @Test public void t1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/JUnit4Sample2.java000066400000000000000000000010611475274123300274000ustar00rootroot00000000000000package test.junit4; import org.junit.Assert; import org.junit.Assume; import org.junit.Ignore; import org.junit.Test; /** @author lukas */ public class JUnit4Sample2 { public static final String[] EXPECTED = {"t2", "t4"}; public static final String[] SKIPPED = {"t3", "ta"}; public static final String[] FAILED = {"tf"}; @Test public void t2() {} @Test @Ignore public void t3() {} @Test public void t4() {} @Test public void tf() { Assert.fail("a test"); } @Test public void ta() { Assume.assumeTrue(false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/JUnit4SampleSuite.java000066400000000000000000000006141475274123300303330ustar00rootroot00000000000000package test.junit4; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** @author lukas */ @RunWith(Suite.class) @Suite.SuiteClasses({JUnit4Sample1.class, JUnit4Sample2.class}) public class JUnit4SampleSuite { public static final String[] EXPECTED = {"t1", "t2", "t4"}; public static final String[] SKIPPED = {"t3", "ta"}; public static final String[] FAILED = {"tf"}; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/listeners/000077500000000000000000000000001475274123300262065ustar00rootroot00000000000000Issue323JUnitInvocationListener.java000066400000000000000000000011311475274123300350200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/listenerspackage test.junit4.listeners; import java.util.ArrayList; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class Issue323JUnitInvocationListener implements IInvokedMethodListener { public static List messages = new ArrayList<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { messages.add("beforeInvocation"); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { messages.add("afterInvocation"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/listeners/Issue323TestRunner.java000066400000000000000000000012441475274123300324240ustar00rootroot00000000000000package test.junit4.listeners; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class Issue323TestRunner extends SimpleBaseTest { @Test public void testMethod() { TestNG testng = create(Issue323TestSample.class); Issue323JUnitInvocationListener listener = new Issue323JUnitInvocationListener(); testng.addListener((ITestNGListener) listener); testng.setJUnit(true); testng.run(); assertThat(Issue323JUnitInvocationListener.messages) .containsExactly("beforeInvocation", "afterInvocation"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junit4/listeners/Issue323TestSample.java000066400000000000000000000002021475274123300323650ustar00rootroot00000000000000package test.junit4.listeners; import org.junit.Test; public class Issue323TestSample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/000077500000000000000000000000001475274123300255315ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/Issue1262TestSample.java000066400000000000000000000005261475274123300320040ustar00rootroot00000000000000package test.junitreports; import org.testng.annotations.Test; public class Issue1262TestSample { @Test(priority = 3) public void testRoles003_Post() {} @Test(priority = 4) public void testRoles004_Post() {} @Test(priority = 1) public void testRoles001_Post() {} @Test(priority = 2) public void testRoles002_Post() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/JUnitReportsTest.java000066400000000000000000000212361475274123300316500ustar00rootroot00000000000000package test.junitreports; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.*; import static test.junitreports.TestClassContainerForGithubIssue1265.*; import com.beust.jcommander.internal.Lists; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import test.SimpleBaseTest; import test.TestHelper; import test.junitreports.issue2124.TestClassSample; import test.junitreports.issue993.SampleTestClass; public class JUnitReportsTest extends SimpleBaseTest { private static final String TESTS = "tests"; private static final String ERRORS = "errors"; private static final String FAILURES = "failures"; private static final String IGNORED = "ignored"; private static final String SKIPPED = "skipped"; private static final String JUNIT_XSD = "jenkins-junit.xsd"; private static String clazz = SimpleTestSample.class.getName(); private static List testcaseList = Arrays.asList( Testcase.newInstance("childTest", clazz, SKIPPED), Testcase.newInstance("masterTest", clazz, "error"), Testcase.newInstance("masterTest", clazz, "failure"), Testcase.newInstance("iShouldNeverBeExecuted", clazz, SKIPPED), Testcase.newInstance("iShouldNeverBeExecuted", clazz, IGNORED)); @Test public void testJUnitXMLReporter() throws IOException { runTest(2, 0, 1, 1, 0, new LocalJUnitXMLReporter(), false); } @Test public void testJUnitReportReporter() throws IOException { runTest(3, 1, 0, 0, 2, new LocalJUnitReportReporter(), true); } @Test public void testJUnitReportReporterWithMultipleClasses() throws IOException { Path outputDir = TestHelper.createRandomDirectory(); Class[] classes = new Class[] {FirstTest.class, SecondTest.class, ThirdTest.class}; Map, Map> mapping = Maps.newHashMap(); mapping.put(FirstTest.class, createMapFor(2, 1)); mapping.put(SecondTest.class, createMapFor(1, 0)); mapping.put(ThirdTest.class, createMapFor(1, 0)); TestNG tng = createTests(outputDir, "suite", classes); LocalJUnitReportReporter reportReporter = new LocalJUnitReportReporter(); tng.addListener(reportReporter); tng.run(); for (Class clazz : classes) { Testsuite suite = reportReporter.getTestsuite(clazz.getName()); Map attributes = mapping.get(clazz); assertEquals(suite.getName(), clazz.getName(), "Suite Name validation."); assertEquals(suite.getTests(), attributes.get(TESTS).intValue(), " count validation."); assertEquals( suite.getErrors(), attributes.get(ERRORS).intValue(), "errored count validation."); assertEquals( suite.getIgnored(), attributes.get(IGNORED).intValue(), "ignored count validation."); assertEquals( suite.getFailures(), attributes.get(FAILURES).intValue(), "failure count validation."); assertEquals( suite.getSkipped(), attributes.get(SKIPPED).intValue(), "skipped count validation."); } } @Test public void testTestCaseOrderingInJUnitReportReporterWhenPrioritiesDefined() throws IOException { Path outputDir = TestHelper.createRandomDirectory(); TestNG tng = createTests(outputDir, "suite", Issue1262TestSample.class); LocalJUnitReportReporter reportReporter = new LocalJUnitReportReporter(); tng.addListener(reportReporter); tng.run(); Testsuite suite = reportReporter.getTestsuite(Issue1262TestSample.class.getName()); List expected = new LinkedList() { { add("testRoles001_Post"); add("testRoles002_Post"); add("testRoles003_Post"); add("testRoles004_Post"); } }; List actual = Lists.newLinkedList(); for (Testcase testcase : suite.getTestcase()) { actual.add(testcase.getName().trim()); } assertEquals(actual, expected); } @Test public void testEnsureTestnameDoesnotAcceptNullValues() throws IOException { Path outputDir = TestHelper.createRandomDirectory(); TestNG tng = createTests(outputDir, "suite", SampleTestClass.class); LocalJUnitReportReporter reportReporter = new LocalJUnitReportReporter(); tng.addListener(reportReporter); tng.run(); Testsuite suite = reportReporter.getTestsuite(SampleTestClass.class.getName()); Testcase testcase = suite.getTestcase().get(0); String actual = testcase.getName(); assertEquals(actual, "Test_001"); } @Test public void ensureTestReportContainsValidSysOutContent() throws Exception { Path outputDir = TestHelper.createRandomDirectory(); TestNG tng = createTests(outputDir, "suite", TestClassSample.class); tng.setUseDefaultListeners(true); tng.run(); DocumentBuilder builder = getJUnitDocumentBuilder(); String name = "TEST-" + TestClassSample.class.getName(); File file = new File( outputDir.toFile().getAbsolutePath() + File.separator + "junitreports" + File.separator + name + ".xml"); Document doc = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "//testsuite/system-out"; String data = (String) xPath.compile(expression).evaluate(doc, XPathConstants.STRING); assertThat(data.trim()).isEqualTo(TestClassSample.MESSAGE_1 + "\n" + TestClassSample.MESSAGE_2); } private DocumentBuilder getJUnitDocumentBuilder() throws SAXException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); SchemaFactory xsdFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = xsdFactory.newSchema(new File(getPathToResource(JUNIT_XSD))); factory.setSchema(schema); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler( new DefaultHandler() { @Override public void error(SAXParseException e) { fail("Test Report Parse Error", e); } }); return builder; } private static Map createMapFor(int testCount, int skipped) { Map map = Maps.newHashMap(); map.put(TESTS, testCount); map.put(ERRORS, 0); map.put(IGNORED, 0); map.put(FAILURES, 0); map.put(SKIPPED, skipped); return map; } private void runTest( int tests, int errors, int ignored, int failures, int skipped, ITestNGListener reporter, boolean useClazzAsSuiteName) throws IOException { Path outputDir = TestHelper.createRandomDirectory(); XmlSuite xmlSuite = createXmlSuite("suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "test"); createXmlClass(xmlTest, SimpleTestSample.class); TestNG tng = create(outputDir, xmlSuite); TestsuiteRetriever reportReporter = (TestsuiteRetriever) reporter; tng.addListener(reporter); tng.run(); String suitename = SimpleTestSample.class.getName(); if (!useClazzAsSuiteName) { suitename = xmlTest.getName(); } Testsuite suite = reportReporter.getTestsuite(suitename); assertEquals(suite.getName(), suitename, "Suite Name validation."); assertEquals(suite.getTests(), tests, " count validation."); assertEquals(suite.getErrors(), errors, "errored count validation."); assertEquals(suite.getIgnored(), ignored, "ignored count validation."); assertEquals(suite.getFailures(), failures, "failure count validation."); assertEquals(suite.getSkipped(), skipped, "skipped count validation."); assertEquals(suite.getTestcase().size(), 3, "test case count validation."); List actualTestcases = suite.getTestcase(); for (Testcase actualTestcase : actualTestcases) { assertTrue( testcaseList.contains(actualTestcase), "Validation of " + actualTestcase.getName() + " " + "presence."); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/LocalJUnitReportReporter.java000066400000000000000000000017611475274123300333240ustar00rootroot00000000000000package test.junitreports; import java.io.File; import java.util.ArrayList; import java.util.List; import org.testng.ISuite; import org.testng.reporters.JUnitReportReporter; import org.testng.xml.XmlSuite; public class LocalJUnitReportReporter extends JUnitReportReporter implements TestsuiteRetriever { private List testsuites = new ArrayList<>(); @Override public void generateReport( List xmlSuites, List suites, String defaultOutputDirectory) { super.generateReport(xmlSuites, suites, defaultOutputDirectory); String dir = defaultOutputDirectory + File.separator + "junitreports"; File directory = new File(dir); File[] files = directory.listFiles((dir1, name) -> name.endsWith(".xml")); testsuites.addAll(LocalJUnitXMLReporter.getSuites(files)); } public Testsuite getTestsuite(String name) { for (Testsuite suite : testsuites) { if (suite.getName().equals(name)) { return suite; } } return null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/LocalJUnitXMLReporter.java000066400000000000000000000024611475274123300325070ustar00rootroot00000000000000package test.junitreports; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.testng.ITestContext; import org.testng.reporters.JUnitXMLReporter; public class LocalJUnitXMLReporter extends JUnitXMLReporter implements TestsuiteRetriever { private List testsuites = new ArrayList<>(); protected void generateReport(ITestContext context) { super.generateReport(context); String dir = context.getOutputDirectory(); File directory = new File(dir); File[] files = directory.listFiles((dir1, name) -> name.endsWith(".xml")); testsuites.addAll(getSuites(files)); } public Testsuite getTestsuite(String name) { for (Testsuite suite : testsuites) { if (suite.getName().equals(name)) { return suite; } } return null; } static List getSuites(File[] files) { List testsuites = new ArrayList<>(); if (files != null) { for (File file : files) { TestsuiteXmlParser parser = new TestsuiteXmlParser(); try { testsuites.add(parser.parse("", new FileInputStream(file), false)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } return testsuites; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/SimpleTestSample.java000066400000000000000000000005331475274123300316300ustar00rootroot00000000000000package test.junitreports; import org.testng.annotations.Test; public class SimpleTestSample { @Test(enabled = false) public void iShouldNeverBeExecuted() {} @Test public void masterTest() { throw new IllegalStateException("Simulating a llegal state."); } @Test(dependsOnMethods = "masterTest") public void childTest() {} } TestClassContainerForGithubIssue1265.java000066400000000000000000000017661475274123300352400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreportspackage test.junitreports; import static org.testng.Assert.assertEquals; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class TestClassContainerForGithubIssue1265 { public abstract static class ParentTest { @BeforeSuite public synchronized void startEverything() throws Exception {} @AfterSuite public synchronized void shutdownContainer() throws Exception {} } public static class FirstTest extends ParentTest { @Test public void should_pass() { assertEquals("abc", "abc"); } @Test(enabled = false) public void should_be_ignored() { assertEquals("abcd", "abc"); } } public static class SecondTest extends ParentTest { @Test public void should_pass_second() { assertEquals("abc", "abc"); } } public static class ThirdTest extends ParentTest { @Test public void should_pass_third() { assertEquals("abc", "abc"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/TestSuiteHandler.java000066400000000000000000000027621475274123300316320ustar00rootroot00000000000000package test.junitreports; import java.util.Arrays; import java.util.List; import java.util.Stack; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class TestSuiteHandler extends DefaultHandler { private static List tags = Arrays.asList("error", "skipped", "ignored", "failure"); private Testsuite testsuite = new Testsuite(); private Stack elementStack = new Stack(); private Stack testcaseStack = new Stack<>(); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.elementStack.push(qName); if ("testsuite".equals(qName)) { if (attributes != null) { testsuite.init(attributes); } } if ("testcase".equals(qName)) { Testcase testcase = new Testcase(); if (attributes != null) { testcase.init(attributes); } testcaseStack.push(testcase); } if (tags.contains(qName)) { Testcase testcase = testcaseStack.pop(); String innerTag = qName; testcase.setInnerTagType(innerTag); testcaseStack.push(testcase); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { elementStack.pop(); if ("testcase".equals(qName)) { Testcase testcase = testcaseStack.pop(); testsuite.addTestcase(testcase); } } public Testsuite getTestsuite() { return testsuite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/Testcase.java000066400000000000000000000034461475274123300301560ustar00rootroot00000000000000package test.junitreports; import org.xml.sax.Attributes; public class Testcase { private String name; private String classname; private String innerTagType; public String getName() { return name; } public String getClassname() { return classname; } public String getInnerTagType() { return innerTagType; } public void setInnerTagType(String innerTagType) { this.innerTagType = innerTagType; } public void init(Attributes attributes) { String value = attributes.getValue("name"); if (value != null) { this.name = value; } value = attributes.getValue("classname"); if (value != null) { this.classname = value; } } @Override public String toString() { return "Testcase{" + "name='" + name + '\'' + ", classname='" + classname + '\'' + ", innerTagType='" + innerTagType + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Testcase testcase = (Testcase) o; if (!name.equals(testcase.name)) { return false; } if (!classname.equals(testcase.classname)) { return false; } return innerTagType.equals(testcase.innerTagType); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + classname.hashCode(); result = 31 * result + innerTagType.hashCode(); return result; } public static Testcase newInstance(String name, String classname, String innerTagType) { Testcase testcase = new Testcase(); testcase.name = name; testcase.classname = classname; testcase.innerTagType = innerTagType; return testcase; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/Testsuite.java000066400000000000000000000036061475274123300303720ustar00rootroot00000000000000package test.junitreports; import java.util.LinkedList; import java.util.List; import org.xml.sax.Attributes; public class Testsuite { public String getName() { return name; } public int getTests() { return tests; } public int getIgnored() { return ignored; } public int getFailures() { return failures; } public int getSkipped() { return skipped; } public int getErrors() { return errors; } public List getTestcase() { return testcase; } public void addTestcase(Testcase testcase) { this.testcase.add(testcase); } public void init(Attributes attributes) { String value = attributes.getValue("name"); if (value != null) { this.name = value; } value = attributes.getValue("tests"); if (value != null) { this.tests = Integer.parseInt(value); } value = attributes.getValue("ignored"); if (value != null) { this.ignored = Integer.parseInt(value); } value = attributes.getValue("failures"); if (value != null) { this.failures = Integer.parseInt(value); } value = attributes.getValue("skipped"); if (value != null) { this.skipped = Integer.parseInt(value); } value = attributes.getValue("errors"); if (value != null) { this.errors = Integer.parseInt(value); } } @Override public String toString() { return "Testsuite{" + "name='" + name + '\'' + ", tests=" + tests + ", ignored=" + ignored + ", failures=" + failures + ", skipped=" + skipped + ", errors=" + errors + ", testcase=" + testcase + '}'; } private String name; private int tests; private int ignored; private int failures; private int skipped; private int errors; private List testcase = new LinkedList<>(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/TestsuiteRetriever.java000066400000000000000000000001531475274123300322540ustar00rootroot00000000000000package test.junitreports; public interface TestsuiteRetriever { Testsuite getTestsuite(String name); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/TestsuiteXmlParser.java000066400000000000000000000011271475274123300322240ustar00rootroot00000000000000package test.junitreports; import java.io.IOException; import java.io.InputStream; import org.testng.TestNGException; import org.testng.xml.XMLParser; import org.xml.sax.SAXException; public class TestsuiteXmlParser extends XMLParser { @Override public Testsuite parse(String filePath, InputStream is, boolean loadClasses) throws TestNGException { TestSuiteHandler handler = new TestSuiteHandler(); try { super.parse(is, handler); return handler.getTestsuite(); } catch (SAXException | IOException e) { throw new TestNGException(e); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/issue2124/000077500000000000000000000000001475274123300271725ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/issue2124/TestClassSample.java000066400000000000000000000006501475274123300331050ustar00rootroot00000000000000package test.junitreports.issue2124; import org.testng.Reporter; import org.testng.annotations.Test; public class TestClassSample { public static final String MESSAGE_1 = "Teenage Mutant Ninja Turtles"; public static final String MESSAGE_2 = "Teenage Mutant Ninja Turtles: Out of the Shadows"; @Test public void testReporter() { Reporter.log(MESSAGE_1, true); Reporter.log(MESSAGE_2, true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/issue993/000077500000000000000000000000001475274123300271265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/junitreports/issue993/SampleTestClass.java000066400000000000000000000012241475274123300330370ustar00rootroot00000000000000package test.junitreports.issue993; import java.lang.reflect.Method; import org.testng.ITest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTestClass implements ITest { private String testName; @BeforeMethod public void setTestName(Method method, Object[] testData) { testName = (String) testData[0]; } @Test(dataProvider = "DP") public void Test_001(String param) {} @DataProvider(name = "DP") public Object[][] getData() { return new Object[][] {{null}}; } @Override public String getTestName() { return testName; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/justin/000077500000000000000000000000001475274123300242755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/justin/BaseTestCase.java000066400000000000000000000016561475274123300274560ustar00rootroot00000000000000package test.justin; import org.testng.annotations.Test; /** @author Justin Lee Date: Aug 15, 2004 */ @Test public abstract class BaseTestCase { protected static final String TEST_PASSWORD = "testPassword"; public BaseTestCase() { init(); } public BaseTestCase(String name) { this(); } private void init() { setSessionUser(null); } protected void commit() {} protected void tearDown() throws Exception { commit(); } protected Object createCustomer() throws Exception { return null; } protected Object createProject() throws Exception { return null; } protected Object createTimeEntry() throws Exception { return null; } protected Object createUser(String name) throws Exception { return null; } protected Object createUserGroup() throws Exception { return null; } protected void setSessionUser(Object user) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/justin/MonthTest.java000066400000000000000000000007151475274123300270700ustar00rootroot00000000000000package test.justin; import java.text.ParseException; import org.testng.annotations.Test; /** * Created Jul 10, 2005 * * @author Justin Lee */ public class MonthTest extends BaseTestCase { public MonthTest() {} public MonthTest(String name) { super(name); } @Test(groups = {"bean-tests"}) public void july2005() throws ParseException {} @Test public void weekendDay() throws ParseException {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/000077500000000000000000000000001475274123300247715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/AggregateSampleTest.java000066400000000000000000000004531475274123300315260ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(L2.class) public class AggregateSampleTest extends BaseAggregate { static int m_count = 0; public static void incrementCount() { m_count++; } @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/AlterSuiteListenerTest.java000066400000000000000000000106251475274123300322670ustar00rootroot00000000000000package test.listeners; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.testng.*; import org.testng.annotations.Test; import org.testng.internal.collections.Pair; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class AlterSuiteListenerTest extends SimpleBaseTest { public static final String ALTER_SUITE_LISTENER = "AlterSuiteListener"; @Test public void executionListenerWithXml() { XmlSuite suite = runTest(AlterSuiteListener1SampleTest.class, AlterSuiteNameListener.class.getName()) .second(); Assert.assertEquals(suite.getName(), AlterSuiteNameListener.class.getSimpleName()); } @Test public void executionListenerWithoutListener() { XmlSuite suite = runTest(AlterSuiteListener1SampleTest.class).second(); Assert.assertEquals(suite.getName(), ALTER_SUITE_LISTENER); } @Test public void executionListenerWithXml2() { XmlSuite suite = runTest(AlterSuiteListener1SampleTest.class, AlterXmlTestsInSuiteListener.class.getName()) .second(); Assert.assertEquals(suite.getTests().size(), 2); } @Test(description = "GITHUB-2469") public void executionListenerWithXml3() { Pair retObjects = runTest( AlterSuiteListener1SampleTest.class, AlterXmlTestWithParameterInSuiteListener.class.getName(), AlteredXmlSuiteReadListener.class.getName()); TestNG tng = retObjects.first(); XmlSuite suite = retObjects.second(); Assert.assertEquals(suite.getTests().size(), 2); List listeners = Optional.ofNullable(tng.getSuiteListeners()).orElse(new ArrayList<>()); Assert.assertFalse(listeners.isEmpty()); for (ISuiteListener iSuiteListener : listeners) { if (iSuiteListener instanceof AlteredXmlSuiteReadListener) { AlteredXmlSuiteReadListener alteredXmlSuiteReadListener = (AlteredXmlSuiteReadListener) iSuiteListener; XmlSuite xmlSuite = alteredXmlSuiteReadListener.currentSuiteOnStart.getXmlSuite(); List tests = xmlSuite.getTests(); int i = 1; for (XmlTest xmlTest : tests) { Assert.assertEquals(xmlTest.getParameter("param"), String.valueOf(i)); i++; } } } } private Pair runTest(Class listenerClass, String... listenerNames) { XmlSuite s = createXmlSuite(ALTER_SUITE_LISTENER); createXmlTest(s, "Test", listenerClass.getName()); for (String listenerName : listenerNames) { s.addListener(listenerName); } TestNG tng = create(); tng.setXmlSuites(Arrays.asList(s)); tng.run(); Pair returnObj = new Pair<>(tng, s); return returnObj; } public static class AlterSuiteListener1SampleTest { @Test public void foo() {} } public static class AlterSuiteNameListener implements IAlterSuiteListener { @Override public void alter(List suites) { XmlSuite suite = suites.get(0); suite.setName(getClass().getSimpleName()); } } public static class AlterXmlTestsInSuiteListener implements IAlterSuiteListener { @Override public void alter(List suites) { XmlSuite suite = suites.get(0); List tests = suite.getTests(); XmlTest test = tests.get(0); XmlTest anotherTest = new XmlTest(suite); anotherTest.setName("foo"); anotherTest.setClasses(test.getClasses()); } } public static class AlterXmlTestWithParameterInSuiteListener implements IAlterSuiteListener { @Override public void alter(List suites) { XmlSuite suite = suites.get(0); List tests = suite.getTests(); XmlTest test = tests.get(0); List newXmlTests = new ArrayList<>(); XmlTest newXmlTest = (XmlTest) test.clone(); newXmlTest.setName("name_1"); newXmlTest.addParameter("param", "1"); newXmlTests.add(newXmlTest); newXmlTest = (XmlTest) test.clone(); newXmlTest.setName("name_2"); newXmlTest.addParameter("param", "2"); newXmlTests.add(newXmlTest); suite.setTests(newXmlTests); } } public static class AlteredXmlSuiteReadListener implements ISuiteListener { public ISuite currentSuiteOnStart; @Override public void onStart(ISuite suite) { currentSuiteOnStart = suite; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/BaseAggregate.java000066400000000000000000000001661475274123300303200ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; @Listeners(L1.class) public class BaseAggregate {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/BaseListener.java000066400000000000000000000012561475274123300302200ustar00rootroot00000000000000package test.listeners; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class BaseListener implements ITestListener { @Override public void onTestStart(ITestResult result) { AggregateSampleTest.incrementCount(); } @Override public void onTestSuccess(ITestResult result) {} @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/BaseWithListener.java000066400000000000000000000004071475274123300310510ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; @Listeners(value = {L3.class, SuiteListener.class, MyInvokedMethodListener.class}) class BaseWithListener { static int m_count = 0; public static void incrementCount() { m_count++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ClassListenerSample.java000066400000000000000000000003611475274123300315510ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(MyClassListener.class) public class ClassListenerSample { @Test public void test() {} @Test public void test2() {} } ConfigurationListenerFailSampleTest.java000066400000000000000000000004231475274123300346670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ConfigurationListenerFailSampleTest { @BeforeMethod public void bmShouldFail() { throw new RuntimeException(); } @Test public void f() {} } ConfigurationListenerSkipSampleTest.java000066400000000000000000000005351475274123300347260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ConfigurationListenerSkipSampleTest { @BeforeMethod public void bmShouldFail() { throw new RuntimeException(); } @BeforeMethod(dependsOnMethods = "bmShouldFail") public void bm() {} @Test public void f() {} } ConfigurationListenerSucceedSampleTest.java000066400000000000000000000003641475274123300353730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ConfigurationListenerSucceedSampleTest { @BeforeMethod public void bmShouldSucceed() {} @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ConfigurationListenerTest.java000066400000000000000000000025061475274123300330140ustar00rootroot00000000000000package test.listeners; import org.testng.Assert; import org.testng.IConfigurationListener; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ConfigurationListenerTest extends SimpleBaseTest { public static class CL implements IConfigurationListener { private static int m_status = 0; @Override public void beforeConfiguration(ITestResult tr) { m_status += 1; } @Override public void onConfigurationSuccess(ITestResult itr) { m_status += 3; } @Override public void onConfigurationFailure(ITestResult itr) { m_status += 5; } @Override public void onConfigurationSkip(ITestResult itr) { m_status += 7; } } private void runTest(Class cls, int expected) { TestNG tng = create(cls); CL listener = new CL(); CL.m_status = 0; tng.addListener(listener); tng.run(); Assert.assertEquals(CL.m_status, expected); } @Test public void shouldSucceed() { runTest(ConfigurationListenerSucceedSampleTest.class, 1 + 3); } @Test public void shouldFail() { runTest(ConfigurationListenerFailSampleTest.class, 1 + 5); } @Test public void shouldSkip() { runTest(ConfigurationListenerSkipSampleTest.class, 1 + 5 + 7); // fail + skip } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/Derived1.java000066400000000000000000000002071475274123300272760ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; class Derived1 extends BaseWithListener { @Test public void t() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/Derived2.java000066400000000000000000000002071475274123300272770ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; class Derived2 extends BaseWithListener { @Test public void s() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/Derived3.java000066400000000000000000000002461475274123300273030ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; class Derived3 extends BaseWithListener { @Test public void r() {} @Test public void r1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/EndMillisShouldNotBeZeroTest.java000066400000000000000000000022531475274123300333250ustar00rootroot00000000000000package test.listeners; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.EndMillisShouldNotBeZeroTest.MyInvokedMethodListener; @Listeners(MyInvokedMethodListener.class) public class EndMillisShouldNotBeZeroTest { private static long m_end; public static class MyInvokedMethodListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { m_end = testResult.getEndMillis(); } } @BeforeClass public void bm() { m_end = 0; } @Test public void f1() { try { Thread.sleep(1); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } @Test( description = "Make sure that ITestResult#getEndMillis is properly set", dependsOnMethods = "f1") public void f2() { Assert.assertTrue(m_end > 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ExecutionListener1SampleTest.java000066400000000000000000000002111475274123300333620ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; public class ExecutionListener1SampleTest { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ExecutionListener2SampleTest.java000066400000000000000000000003541475274123300333730ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ExecutionListenerTest.ExecutionListener.class) public class ExecutionListener2SampleTest { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ExecutionListener3SampleTest.java000066400000000000000000000002111475274123300333640ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; public class ExecutionListener3SampleTest { @Test public void f() {} } ExecutionListenerAndSuiteListener.java000066400000000000000000000012171475274123300343720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import java.util.Locale; import org.testng.IExecutionListener; import org.testng.ISuite; import org.testng.ISuiteListener; public class ExecutionListenerAndSuiteListener implements ISuiteListener, IExecutionListener { private String testString; private static String tmp; @Override public void onExecutionStart() { testString = "initialized"; } @Override public void onExecutionFinish() {} @Override public void onStart(ISuite suite) { tmp = testString.toUpperCase(Locale.ROOT); } @Override public void onFinish(ISuite suite) {} public static String getTmpString() { return tmp; } } ExecutionListenerAndSuiteListenerTest.java000066400000000000000000000012371475274123300352340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import static org.testng.Assert.assertEquals; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class ExecutionListenerAndSuiteListenerTest extends SimpleBaseTest { @Test public void executionListenerAndSuiteListenerTest() { String suiteFile = getPathToResource("executionlistenersingletoncheck/parent.xml"); List suites = getSuites(suiteFile); TestNG testng = new TestNG(); testng.setXmlSuites(suites); testng.run(); assertEquals(ExecutionListenerAndSuiteListener.getTmpString(), "INITIALIZED"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ExecutionListenerTest.java000066400000000000000000000033461475274123300321530ustar00rootroot00000000000000package test.listeners; import java.util.Arrays; import org.testng.Assert; import org.testng.IExecutionListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class ExecutionListenerTest extends SimpleBaseTest { public static class ExecutionListener implements IExecutionListener { public static boolean m_start = false; public static boolean m_finish = false; @Override public void onExecutionStart() { m_start = true; } @Override public void onExecutionFinish() { m_finish = true; } } @Test public void executionListenerWithXml() { runTest(ExecutionListener1SampleTest.class, true /* add listener */, true /* should run */); } @Test public void executionListenerWithoutListener() { runTest( ExecutionListener1SampleTest.class, false /* don't add listener */, false /* should not run */); } @Test public void executionListenerAnnotation() { runTest( ExecutionListener2SampleTest.class, false /* don't add listener */, true /* should run */); } private void runTest(Class listenerClass, boolean addListener, boolean expected) { XmlSuite s = createXmlSuite("ExecutionListener"); XmlTest t = createXmlTest(s, "Test", listenerClass.getName()); if (addListener) { s.addListener(ExecutionListener.class.getName()); } TestNG tng = create(); tng.setXmlSuites(Arrays.asList(s)); ExecutionListener.m_start = false; ExecutionListener.m_finish = false; tng.run(); Assert.assertEquals(ExecutionListener.m_start, expected); Assert.assertEquals(ExecutionListener.m_finish, expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/FailingSampleTest.java000066400000000000000000000006061475274123300312110ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.AfterMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(SimpleListener.class) public class FailingSampleTest { @AfterMethod public void am() { SimpleListener.m_list.add(6); } @Test public void a1() { SimpleListener.m_list.add(4); throw new RuntimeException(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/GitHub911Listener.java000066400000000000000000000017661475274123300307710ustar00rootroot00000000000000package test.listeners; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class GitHub911Listener implements ITestListener { int onTestStart = 0; int onTestSuccess = 0; int onTestFailure = 0; int onTestSkipped = 0; int onTestFailedButWithinSuccessPercentage = 0; int onStart = 0; int onFinish = 0; @Override public void onTestStart(ITestResult result) { onTestStart++; } @Override public void onTestSuccess(ITestResult result) { onTestSuccess++; } @Override public void onTestFailure(ITestResult result) { onTestFailure++; } @Override public void onTestSkipped(ITestResult result) { onTestSkipped++; } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { onTestFailedButWithinSuccessPercentage++; } @Override public void onStart(ITestContext context) { onStart++; } @Override public void onFinish(ITestContext context) { onFinish++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/GitHub911Sample.java000066400000000000000000000005371475274123300304200ustar00rootroot00000000000000package test.listeners; import org.testng.Assert; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class GitHub911Sample { @BeforeSuite(alwaysRun = true) public void setUp() { Assert.fail(); } // TODO check before invocation @Test public void myTest1() {} @Test public void myTest2() {} } InterceptorInvokeTwiceSimulateListener.java000066400000000000000000000013001475274123300354270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.ITestListener; /** * This listener is used to trigger the bug 1863: IMethodInterceptor will be invoked twice when * listener implements both ITestListener and IMethodInterceptor via eclipse execution way */ public class InterceptorInvokeTwiceSimulateListener implements ITestListener, IMethodInterceptor { private int count = 0; @Override public List intercept(List methods, ITestContext context) { count++; return methods; } public int getCount() { return count; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/L1.java000066400000000000000000000001011475274123300261000ustar00rootroot00000000000000package test.listeners; public class L1 extends BaseListener {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/L2.java000066400000000000000000000001011475274123300261010ustar00rootroot00000000000000package test.listeners; public class L2 extends BaseListener {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/L3.java000066400000000000000000000003671475274123300261200ustar00rootroot00000000000000package test.listeners; import org.testng.ITestResult; import org.testng.TestListenerAdapter; public class L3 extends TestListenerAdapter { @Override public void onTestStart(ITestResult result) { BaseWithListener.incrementCount(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/LListener.java000066400000000000000000000006751475274123300275450ustar00rootroot00000000000000package test.listeners; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class LListener implements IInvokedMethodListener { public static boolean invoked = false; @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { invoked = true; } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/LSampleTest.java000066400000000000000000000001751475274123300300340ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; public class LSampleTest { @Test public void dummy() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ListenerAssert.java000066400000000000000000000007061475274123300306060ustar00rootroot00000000000000package test.listeners; import java.util.List; import org.testng.Assert; import org.testng.ITestNGListener; public final class ListenerAssert { private ListenerAssert() {} public static void assertListenerType( List listeners, Class clazz) { for (ITestNGListener listener : listeners) { if (clazz.isInstance(listener)) { return; } } Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ListenerInXmlTest.java000066400000000000000000000010541475274123300312310ustar00rootroot00000000000000package test.listeners; import java.util.Arrays; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ListenerInXmlTest extends SimpleBaseTest { @Test(description = "Make sure that listeners defined in testng.xml are invoked") public void listenerInXmlShouldBeInvoked() { TestNG tng = create(); tng.setTestSuites(Arrays.asList(getPathToResource("listener-in-xml.xml"))); LListener.invoked = false; tng.run(); Assert.assertTrue(LListener.invoked); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ListenerTest.java000066400000000000000000000444671475274123300303000ustar00rootroot00000000000000package test.listeners; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.*; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; import test.listeners.github1029.Issue1029InvokedMethodListener; import test.listeners.github1029.Issue1029SampleTestClassWithDataDrivenMethod; import test.listeners.github1029.Issue1029SampleTestClassWithFiveInstances; import test.listeners.github1029.Issue1029SampleTestClassWithFiveMethods; import test.listeners.github1029.Issue1029SampleTestClassWithOneMethod; import test.listeners.github1393.Listener1393; import test.listeners.github2558.CallHolder; import test.listeners.github2558.ClassMethodListenersHolder; import test.listeners.github2558.ExecutionListenersHolder; import test.listeners.github2558.ReportersHolder; import test.listeners.github2558.SuiteAlterListenersHolder; import test.listeners.github2558.SuiteListenersHolder; import test.listeners.github2558.TestClassSamples; import test.listeners.github2558.TestListenersHolder; import test.listeners.github956.ListenerFor956; import test.listeners.github956.TestClassContainer; import test.listeners.issue1952.TestclassSample; import test.listeners.issue2043.SampleTestClass; import test.listeners.issue2043.listeners.FailFastListener; import test.listeners.issue2055.DynamicTestListener; import test.listeners.issue2055.TestClassSample; public class ListenerTest extends SimpleBaseTest { @BeforeMethod public void bm() { SimpleListener.m_list = Lists.newArrayList(); CallHolder.clear(); } @Test( description = "Ensure that if a listener is present, we get test(), onSuccess()," + " afterMethod()") public void listenerShouldBeCalledBeforeConfiguration() { TestNG tng = create(OrderedListenerSampleTest.class); tng.run(); Assert.assertEquals(SimpleListener.m_list, Arrays.asList(1, 2, 3, 4)); } @Test(description = "TESTNG-400: onTestFailure should be called before @AfterMethod") public void failureBeforeAfterMethod() { TestNG tng = create(FailingSampleTest.class); tng.run(); Assert.assertEquals(SimpleListener.m_list, Arrays.asList(4, 5, 6)); } @Test(description = "Inherited @Listeners annotations should aggregate") public void aggregateListeners() { TestNG tng = create(AggregateSampleTest.class); AggregateSampleTest.m_count = 0; tng.run(); Assert.assertEquals(AggregateSampleTest.m_count, 2); } @Test(description = "Should attach only one instance of the same @Listener class per test") public void shouldAttachOnlyOneInstanceOfTheSameListenerClassPerTest() { TestNG tng = create(Derived1.class, Derived2.class); BaseWithListener.m_count = 0; tng.run(); Assert.assertEquals(BaseWithListener.m_count, 2); } @Test(description = "@Listeners with an ISuiteListener") public void suiteListenersShouldWork() { TestNG tng = create(SuiteListenerSample.class); SuiteListener.start = 0; SuiteListener.finish = 0; tng.run(); Assert.assertEquals(SuiteListener.start, 1); Assert.assertEquals(SuiteListener.finish, 1); } @Test(description = "GITHUB-767: ISuiteListener called twice when @Listeners") public void suiteListenerInListernersAnnotationShouldBeRunOnce() { TestNG tng = createTests("Suite", SuiteListenerSample2.class); SuiteListener2.start = 0; SuiteListener2.finish = 0; tng.run(); Assert.assertEquals(SuiteListener2.start, 1); Assert.assertEquals(SuiteListener2.finish, 1); } @Test(description = "GITHUB-171") public void suiteListenersShouldBeOnlyRunOnceWithManyTests() { TestNG tng = createTests("suite", Derived1.class, Derived2.class); SuiteListener.start = 0; SuiteListener.finish = 0; tng.run(); Assert.assertEquals(SuiteListener.start, 1); Assert.assertEquals(SuiteListener.finish, 1); } @Test(description = "GITHUB-795") public void suiteListenersShouldBeOnlyRunOnceWithManyIdenticalTests() { TestNG tng = createTests("suite", Derived1.class, Derived1.class); SuiteListener.start = 0; SuiteListener.finish = 0; tng.run(); Assert.assertEquals(SuiteListener.start, 1); Assert.assertEquals(SuiteListener.finish, 1); } @Test(description = "GITHUB-169") public void invokedMethodListenersShouldBeOnlyRunOnceWithManyTests() { TestNG tng = createTests("suite", Derived1.class, Derived2.class); MyInvokedMethodListener.beforeInvocation.clear(); MyInvokedMethodListener.afterInvocation.clear(); tng.run(); assertThat(MyInvokedMethodListener.beforeInvocation).containsOnly(entry("t", 1), entry("s", 1)); assertThat(MyInvokedMethodListener.afterInvocation).containsOnly(entry("t", 1), entry("s", 1)); } @Test(description = "GITHUB-154: MethodInterceptor will be called twice") public void methodInterceptorShouldBeRunOnce() { TestNG tng = create(SuiteListenerSample.class); MyMethodInterceptor interceptor = new MyMethodInterceptor(); tng.addListener(interceptor); tng.run(); Assert.assertEquals(interceptor.getCount(), 1); } @Test( description = "GITHUB-1863:IMethodInterceptor will be invoked twice when listener implements both ITestListener and IMethodInterceptor via eclipse execution way") public void methodInterceptorShouldBeRunOnceWhenCustomisedListenerImplementsITestListenerAndIMethodInterceptor() { TestNG tng = create(LSampleTest.class); InterceptorInvokeTwiceSimulateListener interceptor = new InterceptorInvokeTwiceSimulateListener(); tng.addListener(interceptor); tng.run(); Assert.assertEquals(interceptor.getCount(), 1); } @Test(description = "GITHUB-356: Add listeners for @BeforeClass/@AfterClass") public void classListenerShouldWork() { MyClassListener.names.clear(); TestNG tng = create(Derived1.class, Derived2.class); MyClassListener listener = new MyClassListener(); tng.addListener(listener); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); assertThat(adapter.getFailedTests()).isEmpty(); assertThat(adapter.getSkippedTests()).isEmpty(); assertThat(MyClassListener.names) .containsExactly( "BeforeClass=Derived1", "BeforeMethod=Derived1.t", "AfterMethod=Derived1.t", "AfterClass=Derived1", "BeforeClass=Derived2", "BeforeMethod=Derived2.s", "AfterMethod=Derived2.s", "AfterClass=Derived2"); } @Test public void classListenerShouldWorkWithManyTestMethods() { MyClassListener.names.clear(); TestNG tng = create(Derived3.class); MyClassListener listener = new MyClassListener(); tng.addListener(listener); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); assertThat(adapter.getFailedTests()).isEmpty(); assertThat(adapter.getSkippedTests()).isEmpty(); assertThat(MyClassListener.names) .containsExactly( "BeforeClass=Derived3", "BeforeMethod=Derived3.r", "AfterMethod=Derived3.r", "BeforeMethod=Derived3.r1", "AfterMethod=Derived3.r1", "AfterClass=Derived3"); } @Test(description = "GITHUB-356: Add listeners for @BeforeClass/@AfterClass") public void classListenerShouldWorkFromAnnotation() { MyClassListener.names.clear(); TestNG tng = create(ClassListenerSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); assertThat(adapter.getFailedTests()).isEmpty(); assertThat(adapter.getSkippedTests()).isEmpty(); assertThat(MyClassListener.names) .containsExactly( "BeforeClass=ClassListenerSample", "BeforeMethod=ClassListenerSample.test", "AfterMethod=ClassListenerSample.test", "BeforeMethod=ClassListenerSample.test2", "AfterMethod=ClassListenerSample.test2", "AfterClass=ClassListenerSample"); } @Test public void classListenerShouldBeOnlyRunOnce() { MyClassListener.names.clear(); TestNG tng = create(Derived3.class); MyClassListener listener = new MyClassListener(); tng.addListener(listener); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); TestAndClassListener tacl = new TestAndClassListener(); tng.addListener(tacl); tng.run(); assertThat(adapter.getFailedTests()).isEmpty(); assertThat(adapter.getSkippedTests()).isEmpty(); assertThat(tacl.getBeforeClassCount()).isEqualTo(1); assertThat(tacl.getAfterClassCount()).isEqualTo(1); } @Test(description = "GITHUB-911: Should not call method listeners for skipped methods") public void methodListenersShouldNotBeCalledForSkippedMethods() { GitHub911Listener listener = new GitHub911Listener(); TestNG tng = create(GitHub911Sample.class); tng.addListener(listener); tng.run(); Assert.assertEquals(listener.onStart, 1); Assert.assertEquals(listener.onFinish, 1); Assert.assertEquals(listener.onTestStart, 2); Assert.assertEquals(listener.onTestSuccess, 0); Assert.assertEquals(listener.onTestFailure, 0); Assert.assertEquals(listener.onTestFailedButWithinSuccessPercentage, 0); Assert.assertEquals(listener.onTestSkipped, 2); } @Test(description = "GITHUB-895: Changing status of test by setStatus of ITestResult") public void setStatusShouldWorkInListener() { SetStatusListener listener = new SetStatusListener(); TestNG tng = create(SetStatusSample.class); tng.addListener(listener); tng.run(); Assert.assertEquals(listener.getContext().getFailedTests().size(), 0); Assert.assertEquals(listener.getContext().getFailedButWithinSuccessPercentageTests().size(), 0); Assert.assertEquals(listener.getContext().getSkippedTests().size(), 0); Assert.assertEquals(listener.getContext().getPassedTests().size(), 1); } @Test( description = "GITHUB-1084: Using deprecated addListener methods should not register many times") public void listenerRegistration() { MultiListener listener = new MultiListener(); TestNG tng = create(SimpleSample.class); // Keep using deprecated addListener methods. It is what the test is testing tng.addListener((ITestNGListener) listener); tng.addListener((ITestNGListener) listener); tng.addListener((ITestNGListener) listener); tng.run(); Assert.assertEquals(listener.getOnSuiteStartCount(), 1); Assert.assertEquals(listener.getOnSuiteFinishCount(), 1); Assert.assertEquals(listener.getOnTestStartCount(), 1); Assert.assertEquals(listener.getOnTestFinishCount(), 1); Assert.assertEquals(listener.getBeforeInvocationCount(), 1); Assert.assertEquals(listener.getAfterInvocationCount(), 1); Assert.assertEquals(listener.getOnMethodTestStartCount(), 1); Assert.assertEquals(listener.getOnMethodTestSuccessCount(), 1); } @Test public void testListenerCallInvocation() { XmlSuite suite = createXmlSuite( "suite956", "test956", TestClassContainer.FirstTestClass.class, TestClassContainer.SecondTestClass.class); TestNG tng = create(suite); ListenerFor956 listener = new ListenerFor956(); tng.addListener(listener); tng.run(); List messages = ListenerFor956.getMessages(); Assert.assertEquals(messages.size(), 1); Assert.assertEquals(messages.get(0), "Executing test956"); } @Test(description = "GITHUB-1393: fail a test from onTestStart method") public void testFailATestFromOnTestStart() { TestNG tng = create(SimpleSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.addListener(new Listener1393()); tng.run(); Assert.assertEquals(adapter.getPassedTests().size(), 0); Assert.assertEquals(adapter.getFailedTests().size(), 1); } @Test(dataProvider = "dp", description = "GITHUB-1029") public void ensureXmlTestIsNotNull(Class clazz, XmlSuite.ParallelMode mode) { XmlSuite xmlSuite = createXmlSuite("Suite"); createXmlTest(xmlSuite, "GITHUB-1029-Test", clazz); xmlSuite.setParallel(mode); Issue1029InvokedMethodListener listener = new Issue1029InvokedMethodListener(); TestNG testng = create(xmlSuite); testng.addListener(listener); testng.setThreadCount(10); testng.setDataProviderThreadCount(10); testng.run(); List expected = Collections.nCopies(5, "GITHUB-1029-Test"); assertThat(listener.getBeforeInvocation()).containsExactlyElementsOf(expected); assertThat(listener.getAfterInvocation()).containsExactlyElementsOf(expected); } @Test(description = "GITHUB-1952") public void ensureTimeoutListenerIsInvokedForTimingoutTests() { TestNG tng = create(TestclassSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); assertThat(adapter.getTimedoutTests()).hasSize(1); } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] { {Issue1029SampleTestClassWithFiveMethods.class, XmlSuite.ParallelMode.METHODS}, {Issue1029SampleTestClassWithOneMethod.class, XmlSuite.ParallelMode.METHODS}, {Issue1029SampleTestClassWithDataDrivenMethod.class, XmlSuite.ParallelMode.METHODS}, {Issue1029SampleTestClassWithFiveInstances.class, XmlSuite.ParallelMode.INSTANCES} }; } @Test(description = "GITHUB-2043") public void runTest() { TestNG testng = create(SampleTestClass.class); testng.run(); assertThat(FailFastListener.msgs) .containsExactly( "FailFastListener:afterInvocation", "FailFastListener:beforeDataProviderExecution", "FailFastListener:beforeConfiguration"); } @Test(description = "GITHUB-2055") public void ensureDynamicTestListenerInjection() { TestNG testng = create(TestClassSample.class); testng.run(); assertThat(DynamicTestListener.MSGS).containsExactly("Starting testMethod"); } @Test(description = "GITHUB-2061") public void ensureDynamicListenerAdditionsDontTriggerConcurrentModificationExceptions() { TestNG testng = create(test.listeners.issue2061.TestClassSample.class); testng.run(); assertThat(testng.getStatus()).isEqualTo(0); } @Test(description = "GITHUB-2558") public void ensureInsertionOrderIsHonouredByListeners() { String prefix = "test.listeners.github2558."; String[] expectedOrder = new String[] { prefix + "ExecutionListenersHolder$ExecutionListenerB.onExecutionStart()", prefix + "ExecutionListenersHolder$ExecutionListenerA.onExecutionStart()", prefix + "SuiteAlterListenersHolder$SuiteAlterB.alter()", prefix + "SuiteAlterListenersHolder$SuiteAlterA.alter()", prefix + "SuiteListenersHolder$SuiteListenerB.onStart()", prefix + "SuiteListenersHolder$SuiteListenerA.onStart()", prefix + "TestListenersHolder$TestListenerB.onStart(ctx)", prefix + "TestListenersHolder$TestListenerA.onStart(ctx)", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.beforeInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.beforeInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.afterInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.afterInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.beforeInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.beforeInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.afterInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.afterInvocation()", prefix + "ClassMethodListenersHolder$ClassMethodListenerB.onBeforeClass()", prefix + "ClassMethodListenersHolder$ClassMethodListenerA.onBeforeClass()", prefix + "TestListenersHolder$TestListenerA.onFinish(ctx)", prefix + "TestListenersHolder$TestListenerB.onFinish(ctx)", prefix + "SuiteListenersHolder$SuiteListenerA.onFinish()", prefix + "SuiteListenersHolder$SuiteListenerB.onFinish()", prefix + "ReportersHolder$ReporterB.generateReport()", prefix + "ReportersHolder$ReporterA.generateReport()", prefix + "ExecutionListenersHolder$ExecutionListenerA.onExecutionFinish()", prefix + "ExecutionListenersHolder$ExecutionListenerB.onExecutionFinish()" }; List> listeners = Arrays.asList( ExecutionListenersHolder.ExecutionListenerB.class, SuiteAlterListenersHolder.SuiteAlterB.class, SuiteListenersHolder.SuiteListenerB.class, TestListenersHolder.TestListenerB.class, ClassMethodListenersHolder.ClassMethodListenerB.class, ReportersHolder.ReporterB.class, ExecutionListenersHolder.ExecutionListenerA.class, SuiteAlterListenersHolder.SuiteAlterA.class, SuiteListenersHolder.SuiteListenerA.class, TestListenersHolder.TestListenerA.class, ClassMethodListenersHolder.ClassMethodListenerA.class, ReportersHolder.ReporterA.class); XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("Random_Suite"); listeners.forEach(each -> xmlSuite.addListener(each.getName())); createXmlTest( xmlSuite, "random_test", TestClassSamples.TestClassSampleA.class, TestClassSamples.TestClassSampleB.class); TestNG testng = create(xmlSuite); testng.setUseDefaultListeners(false); testng.run(); List actual = CallHolder.getCalls(); assertThat(actual).containsExactly(expectedOrder); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ListenersTest.java000066400000000000000000000140701475274123300304460ustar00rootroot00000000000000package test.listeners; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; import test.listeners.issue2638.DummyInvokedMethodListener; import test.listeners.issue2638.TestClassASample; import test.listeners.issue2638.TestClassBSample; public class ListenersTest extends SimpleBaseTest { private static final String[] github2638ExpectedList = new String[] { "test.listeners.issue2638.TestClassASample.testMethod", "test.listeners.issue2638.TestClassBSample.testMethod" }; @Test(description = "GITHUB-2638", dataProvider = "suiteProvider") public void ensureDuplicateListenersAreNotWiredInAcrossSuites( XmlSuite xmlSuite, Map expected) { TestNG testng = create(xmlSuite); testng.run(); assertThat(DummyInvokedMethodListener.getMethods("Container_Suite")) .containsExactly(expected.get("Container_Suite")); assertThat(DummyInvokedMethodListener.getMethods("Inner_Suite1")) .containsExactly(expected.get("Inner_Suite1")); assertThat(DummyInvokedMethodListener.getMethods("Inner_Suite2")) .containsExactly(expected.get("Inner_Suite2")); DummyInvokedMethodListener.reset(); } @DataProvider(name = "suiteProvider") public Object[][] getSuites() throws IOException { return new Object[][] { new Object[] {getNestedSuitesViaXmlFiles(), getExpectations()}, new Object[] {getNestedSuitesViaApis(), getExpectations()}, new Object[] {getNestedSuitesViaXmlFilesWithListenerInChildSuite(), getExpectations()}, new Object[] {getNestedSuitesViaApisWithListenerInChildSuite(), getExpectations()} }; } private static Map getExpectations() { Map expected = new HashMap<>(); expected.put("Container_Suite", new String[] {}); expected.put("Inner_Suite1", github2638ExpectedList); expected.put("Inner_Suite2", github2638ExpectedList); return expected; } private static XmlSuite getNestedSuitesViaXmlFiles() throws IOException { XmlSuite containerSuite = createXmlSuite("Container_Suite"); containerSuite.setListeners( Collections.singletonList(DummyInvokedMethodListener.class.getName())); XmlSuite innerSuite1 = createXmlSuite("Inner_Suite1"); createXmlTest(innerSuite1, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite1, "Inner_Test_2", TestClassBSample.class); Path s1 = Files.createTempFile("testng", ".xml"); Files.write(s1, Collections.singletonList(innerSuite1.toXml())); XmlSuite innerSuite2 = createXmlSuite("Inner_Suite2"); createXmlTest(innerSuite2, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite2, "Inner_Test_2", TestClassBSample.class); Path s2 = Files.createTempFile("testng", ".xml"); Files.write(s2, Collections.singletonList(innerSuite2.toXml())); containerSuite.setSuiteFiles( Arrays.asList(s1.toFile().getAbsolutePath(), s2.toFile().getAbsolutePath())); return containerSuite; } private static XmlSuite getNestedSuitesViaXmlFilesWithListenerInChildSuite() throws IOException { XmlSuite containerSuite = createXmlSuite("Container_Suite"); XmlSuite innerSuite1 = createXmlSuite("Inner_Suite1"); innerSuite1.setListeners(Collections.singletonList(DummyInvokedMethodListener.class.getName())); createXmlTest(innerSuite1, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite1, "Inner_Test_2", TestClassBSample.class); Path s1 = Files.createTempFile("testng", ".xml"); Files.write(s1, Collections.singletonList(innerSuite1.toXml())); XmlSuite innerSuite2 = createXmlSuite("Inner_Suite2"); createXmlTest(innerSuite2, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite2, "Inner_Test_2", TestClassBSample.class); Path s2 = Files.createTempFile("testng", ".xml"); Files.write(s2, Collections.singletonList(innerSuite2.toXml())); containerSuite.setSuiteFiles( Arrays.asList(s1.toFile().getAbsolutePath(), s2.toFile().getAbsolutePath())); return containerSuite; } private static XmlSuite getNestedSuitesViaApisWithListenerInChildSuite() { XmlSuite containerSuite = createXmlSuite("Container_Suite"); XmlSuite innerSuite1 = createXmlSuite("Inner_Suite1"); innerSuite1.setListeners(Collections.singletonList(DummyInvokedMethodListener.class.getName())); createXmlTest(innerSuite1, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite1, "Inner_Test_2", TestClassBSample.class); containerSuite.getChildSuites().add(innerSuite1); innerSuite1.setParentSuite(containerSuite); XmlSuite innerSuite2 = createXmlSuite("Inner_Suite2"); createXmlTest(innerSuite2, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite2, "Inner_Test_2", TestClassBSample.class); containerSuite.getChildSuites().add(innerSuite2); innerSuite2.setParentSuite(containerSuite); return containerSuite; } private static XmlSuite getNestedSuitesViaApis() { XmlSuite containerSuite = createXmlSuite("Container_Suite"); containerSuite.setListeners( Collections.singletonList(DummyInvokedMethodListener.class.getName())); XmlSuite innerSuite1 = createXmlSuite("Inner_Suite1"); createXmlTest(innerSuite1, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite1, "Inner_Test_2", TestClassBSample.class); XmlSuite innerSuite2 = createXmlSuite("Inner_Suite2"); createXmlTest(innerSuite2, "Inner_Test_1", TestClassASample.class); createXmlTest(innerSuite2, "Inner_Test_2", TestClassBSample.class); containerSuite.getChildSuites().add(innerSuite1); containerSuite.getChildSuites().add(innerSuite2); innerSuite1.setParentSuite(containerSuite); innerSuite2.setParentSuite(containerSuite); return containerSuite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/MultiListener.java000066400000000000000000000070571475274123300304450ustar00rootroot00000000000000package test.listeners; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.internal.IResultListener; public class MultiListener implements ISuiteListener, IResultListener, IInvokedMethodListener { private int onConfigurationSuccessCount = 0; private int onConfigurationFailureCount = 0; private int onConfigurationSkipCount = 0; private int beforeInvocationCount = 0; private int afterInvocationCount = 0; private int onSuiteStartCount = 0; private int onSuiteFinishCount = 0; private int onMethodTestStartCount = 0; private int onMethodTestSuccessCount = 0; private int onMethodTestFailureCount = 0; private int onMethodTestSkippedCount = 0; private int onMethodTestFailedButWithinSuccessPercentageCount = 0; private int onTestStartCount = 0; private int onTestFinishCount = 0; @Override public void onConfigurationSuccess(ITestResult itr) { onConfigurationSuccessCount++; } @Override public void onConfigurationFailure(ITestResult itr) { onConfigurationFailureCount++; } @Override public void onConfigurationSkip(ITestResult itr) { onConfigurationSkipCount++; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { beforeInvocationCount++; } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { afterInvocationCount++; } @Override public void onStart(ISuite suite) { onSuiteStartCount++; } @Override public void onFinish(ISuite suite) { onSuiteFinishCount++; } @Override public void onTestStart(ITestResult result) { onMethodTestStartCount++; } @Override public void onTestSuccess(ITestResult result) { onMethodTestSuccessCount++; } @Override public void onTestFailure(ITestResult result) { onMethodTestFailureCount++; } @Override public void onTestSkipped(ITestResult result) { onMethodTestSkippedCount++; } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { onMethodTestFailedButWithinSuccessPercentageCount++; } @Override public void onStart(ITestContext context) { onTestStartCount++; } @Override public void onFinish(ITestContext context) { onTestFinishCount++; } public int getOnConfigurationSuccessCount() { return onConfigurationSuccessCount; } public int getOnConfigurationFailureCount() { return onConfigurationFailureCount; } public int getOnConfigurationSkipCount() { return onConfigurationSkipCount; } public int getBeforeInvocationCount() { return beforeInvocationCount; } public int getAfterInvocationCount() { return afterInvocationCount; } public int getOnSuiteStartCount() { return onSuiteStartCount; } public int getOnSuiteFinishCount() { return onSuiteFinishCount; } public int getOnMethodTestStartCount() { return onMethodTestStartCount; } public int getOnMethodTestSuccessCount() { return onMethodTestSuccessCount; } public int getOnMethodTestFailureCount() { return onMethodTestFailureCount; } public int getOnMethodTestSkippedCount() { return onMethodTestSkippedCount; } public int getOnMethodTestFailedButWithinSuccessPercentageCount() { return onMethodTestFailedButWithinSuccessPercentageCount; } public int getOnTestStartCount() { return onTestStartCount; } public int getOnTestFinishCount() { return onTestFinishCount; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/MyClassListener.java000066400000000000000000000021711475274123300307160ustar00rootroot00000000000000package test.listeners; import java.util.ArrayList; import java.util.List; import org.testng.IClassListener; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestClass; import org.testng.ITestResult; import org.testng.internal.BaseTestMethod; public class MyClassListener implements IClassListener, IInvokedMethodListener { public static final List names = new ArrayList<>(); @Override public void onBeforeClass(ITestClass testClass) { names.add("BeforeClass=" + testClass.getRealClass().getSimpleName()); } @Override public void onAfterClass(ITestClass testClass) { names.add("AfterClass=" + testClass.getRealClass().getSimpleName()); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { BaseTestMethod m = (BaseTestMethod) method.getTestMethod(); names.add("BeforeMethod=" + m.getSimpleName()); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { BaseTestMethod m = (BaseTestMethod) method.getTestMethod(); names.add("AfterMethod=" + m.getSimpleName()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/MyInvokedMethodListener.java000066400000000000000000000016771475274123300324230ustar00rootroot00000000000000package test.listeners; import java.util.HashMap; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class MyInvokedMethodListener implements IInvokedMethodListener { public static Map beforeInvocation = new HashMap<>(); public static Map afterInvocation = new HashMap<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { increments(beforeInvocation, method); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { increments(afterInvocation, method); } private static void increments(Map map, IInvokedMethod method) { String stringValue = method.getTestMethod().getMethodName(); Integer count = map.get(stringValue); if (count == null) { count = 0; } map.put(stringValue, count + 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/MyMethodInterceptor.java000066400000000000000000000006721475274123300316060ustar00rootroot00000000000000package test.listeners; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; public class MyMethodInterceptor implements IMethodInterceptor { private int count = 0; @Override public List intercept(List methods, ITestContext context) { count++; return methods; } public int getCount() { return count; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/OrderedListenerSampleTest.java000066400000000000000000000010271475274123300327300ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.SimpleBaseTest; @Listeners(SimpleListener.class) public class OrderedListenerSampleTest extends SimpleBaseTest { @BeforeMethod public void bm() { SimpleListener.m_list.add(1); } @Test public void f() { SimpleListener.m_list.add(2); } @AfterMethod public void am() { SimpleListener.m_list.add(4); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ResultContextListener.java000066400000000000000000000013361475274123300321700ustar00rootroot00000000000000package test.listeners; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class ResultContextListener implements ITestListener { public static boolean contextProvided = false; public void onTestStart(ITestResult result) { ITestContext context = result.getTestContext(); if (context != null) { contextProvided = true; } } public void onTestSuccess(ITestResult result) {} public void onTestFailure(ITestResult result) {} public void onTestSkipped(ITestResult result) {} public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} public void onStart(ITestContext context) {} public void onFinish(ITestContext context) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ResultContextListenerSample.java000066400000000000000000000003321475274123300333250ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ResultContextListener.class) public class ResultContextListenerSample { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ResultContextTest.java000066400000000000000000000006741475274123300313260ustar00rootroot00000000000000package test.listeners; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ResultContextTest extends SimpleBaseTest { @Test public void testResultContext() { TestNG tng = create(ResultContextListenerSample.class); tng.run(); Assert.assertTrue( ResultContextListener.contextProvided, "Test context was not provided to the listener"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ResultEndMillisTest.java000066400000000000000000000010121475274123300315450ustar00rootroot00000000000000package test.listeners; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; import test.sample.Sample1; public class ResultEndMillisTest extends SimpleBaseTest { @Test public void endMillisShouldBeNonNull() { TestNG tng = create(Sample1.class); tng.addListener((ITestNGListener) new ResultListener()); tng.run(); assertThat(ResultListener.m_end > 0).isTrue(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ResultListener.java000066400000000000000000000025551475274123300306270ustar00rootroot00000000000000package test.listeners; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.internal.IResultListener2; public class ResultListener implements IResultListener2 { public static long m_end = 0; @Override public void onTestStart(ITestResult result) { // TODO Auto-generated method stub } @Override public void beforeConfiguration(ITestResult tr) {} @Override public void onTestSuccess(ITestResult result) { m_end = result.getEndMillis(); } @Override public void onTestFailure(ITestResult result) { // TODO Auto-generated method stub } @Override public void onTestSkipped(ITestResult result) { // TODO Auto-generated method stub } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { // TODO Auto-generated method stub } @Override public void onStart(ITestContext context) { // TODO Auto-generated method stub } @Override public void onFinish(ITestContext context) { // TODO Auto-generated method stub } @Override public void onConfigurationSuccess(ITestResult itr) { // TODO Auto-generated method stub } @Override public void onConfigurationFailure(ITestResult itr) { // TODO Auto-generated method stub } @Override public void onConfigurationSkip(ITestResult itr) { // TODO Auto-generated method stub } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SetStatusListener.java000066400000000000000000000015551475274123300313070ustar00rootroot00000000000000package test.listeners; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; /** From https://github.com/rajsrivastav1919/TestNGTest */ public class SetStatusListener implements ITestListener { private ITestContext context; @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) {} @Override public void onTestFailure(ITestResult result) { result.setStatus(ITestResult.SUCCESS); } @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) { this.context = context; } public ITestContext getContext() { return context; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SetStatusSample.java000066400000000000000000000003161475274123300307350ustar00rootroot00000000000000package test.listeners; import org.testng.Assert; import org.testng.annotations.Test; public class SetStatusSample { @Test public void aFailingTest() { Assert.fail("Failing deliberately"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SimpleListener.java000066400000000000000000000006671475274123300306040ustar00rootroot00000000000000package test.listeners; import java.util.List; import org.testng.ITestResult; import org.testng.TestListenerAdapter; public class SimpleListener extends TestListenerAdapter { public static List m_list; @Override public void onTestSuccess(ITestResult tr) { m_list.add(3); super.onTestSuccess(tr); } @Override public void onTestFailure(ITestResult tr) { m_list.add(5); super.onTestSuccess(tr); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SimpleSample.java000066400000000000000000000001751475274123300302320ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Test; public class SimpleSample { @Test public void test() {} } SuiteAndConfigurationListenerTest.java000066400000000000000000000025241475274123300343720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.IConfigurationListener; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestResult; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.SuiteAndConfigurationListenerTest.MyListener; /** * Check that if a listener implements IConfigurationListener additionally to ISuiteListener, * ISuiteListener gets invoked exactly once. * * @author Mihails Volkovs */ @Listeners(MyListener.class) public class SuiteAndConfigurationListenerTest { public static class MyListener implements ISuiteListener, IConfigurationListener { private static volatile AtomicInteger started = new AtomicInteger(0); public MyListener() {} @Override public void onStart(ISuite suite) { started.incrementAndGet(); } @Override public void onFinish(ISuite suite) {} @Override public void onConfigurationSuccess(ITestResult itr) {} @Override public void onConfigurationFailure(ITestResult itr) {} @Override public void onConfigurationSkip(ITestResult itr) {} } @Test public void bothListenersShouldRun() { Assert.assertEquals( MyListener.started.get(), 1, "ISuiteListener was not invoked exactly once:"); } } SuiteAndInvokedMethodListenerTest.java000066400000000000000000000025671475274123300343320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listenerspackage test.listeners; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestResult; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.SuiteAndInvokedMethodListenerTest.MyListener; /** * Make sure that if a listener implements both IInvokedMethodListener and ISuiteListener, both * listeners get invoked. * * @author Cedric Beust */ @Listeners(MyListener.class) public class SuiteAndInvokedMethodListenerTest { public static class MyListener implements IInvokedMethodListener, ISuiteListener { private static boolean m_before = false; private static boolean m_start = false; public MyListener() {} @Override public void beforeInvocation(IInvokedMethod method, ITestResult result) { m_before = true; } @Override public void afterInvocation(IInvokedMethod method, ITestResult result) {} @Override public void onStart(ISuite suite) { m_start = true; } @Override public void onFinish(ISuite suite) {} } @Test public void bothListenersShouldRun() { Assert.assertTrue(MyListener.m_before, "IInvokedMethodListener was not invoked"); Assert.assertTrue(MyListener.m_start, "ISuiteListener was not invoked"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SuiteListener.java000066400000000000000000000005301475274123300304310ustar00rootroot00000000000000package test.listeners; import org.testng.ISuite; import org.testng.ISuiteListener; public class SuiteListener implements ISuiteListener { public static int start = 0; public static int finish = 0; @Override public void onFinish(ISuite suite) { finish++; } @Override public void onStart(ISuite suite) { start++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SuiteListener2.java000066400000000000000000000031431475274123300305160ustar00rootroot00000000000000package test.listeners; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.List; import org.testng.*; import org.testng.annotations.ITestAnnotation; public class SuiteListener2 implements IAnnotationTransformer, IInvokedMethodListener, ITestListener, ISuiteListener, IExecutionListener, IMethodInterceptor { public static int start = 0; public static int finish = 0; @Override public void onFinish(ISuite suite) { finish++; } @Override public void onStart(ISuite suite) { start++; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} @Override public void onExecutionStart() {} @Override public void onExecutionFinish() {} @Override public List intercept(List methods, ITestContext context) { return methods; } @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) {} @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SuiteListenerSample.java000066400000000000000000000003141475274123300315730ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(SuiteListener.class) public class SuiteListenerSample { @Test public void foo() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/SuiteListenerSample2.java000066400000000000000000000003161475274123300316570ustar00rootroot00000000000000package test.listeners; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(SuiteListener2.class) public class SuiteListenerSample2 { @Test public void foo() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/TestAndClassListener.java000066400000000000000000000021451475274123300316740ustar00rootroot00000000000000package test.listeners; import org.testng.IClassListener; import org.testng.ITestClass; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class TestAndClassListener implements ITestListener, IClassListener { private int beforeClassCount = 0; private int afterClassCount = 0; @Override public void onBeforeClass(ITestClass testClass) { beforeClassCount++; } @Override public void onAfterClass(ITestClass testClass) { afterClassCount++; } @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) {} @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} public int getBeforeClassCount() { return beforeClassCount; } public int getAfterClassCount() { return afterClassCount; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1029/000077500000000000000000000000001475274123300265675ustar00rootroot00000000000000Issue1029InvokedMethodListener.java000066400000000000000000000021011475274123300351400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1029package test.listeners.github1029; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.xml.XmlTest; public class Issue1029InvokedMethodListener implements IInvokedMethodListener { private List beforeInvocation = Collections.synchronizedList(new ArrayList()); private List afterInvocation = Collections.synchronizedList(new ArrayList()); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { XmlTest xmlTest = method.getTestMethod().getXmlTest(); beforeInvocation.add(xmlTest.getName()); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { XmlTest xmlTest = method.getTestMethod().getXmlTest(); afterInvocation.add(xmlTest.getName()); } public List getAfterInvocation() { return afterInvocation; } public List getBeforeInvocation() { return beforeInvocation; } } Issue1029SampleTestClassWithDataDrivenMethod.java000066400000000000000000000006551475274123300377140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1029package test.listeners.github1029; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Issue1029SampleTestClassWithDataDrivenMethod { @Test(dataProvider = "dp") public void a(int i) { Assert.assertTrue(i > 0); } @DataProvider(name = "dp", parallel = true) public Object[][] getData() { return new Object[][] {{1}, {2}, {3}, {4}, {5}}; } } Issue1029SampleTestClassWithFiveInstances.java000066400000000000000000000010611475274123300372630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1029package test.listeners.github1029; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class Issue1029SampleTestClassWithFiveInstances { private int i; @Factory(dataProvider = "dp") public Issue1029SampleTestClassWithFiveInstances(int i) { this.i = i; } @Test public void a() { Assert.assertTrue(i > 0); } @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] {{1}, {2}, {3}, {4}, {5}}; } } Issue1029SampleTestClassWithFiveMethods.java000066400000000000000000000007211475274123300367410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1029package test.listeners.github1029; import org.testng.Assert; import org.testng.annotations.Test; public class Issue1029SampleTestClassWithFiveMethods { @Test public void a() { Assert.assertTrue(true); } @Test public void b() { Assert.assertTrue(true); } @Test public void c() { Assert.assertTrue(true); } @Test public void d() { Assert.assertTrue(true); } @Test public void e() { Assert.assertTrue(true); } } Issue1029SampleTestClassWithOneMethod.java000066400000000000000000000004011475274123300364010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1029package test.listeners.github1029; import org.testng.Assert; import org.testng.annotations.Test; public class Issue1029SampleTestClassWithOneMethod { @Test(invocationCount = 5, threadPoolSize = 10) public void a() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1130/000077500000000000000000000000001475274123300265605ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1130/ASample.java000066400000000000000000000002301475274123300307400ustar00rootroot00000000000000package test.listeners.github1130; import org.testng.annotations.Test; public class ASample extends BaseSample { @Test public void testA1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1130/BSample.java000066400000000000000000000002301475274123300307410ustar00rootroot00000000000000package test.listeners.github1130; import org.testng.annotations.Test; public class BSample extends BaseSample { @Test public void testB1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1130/BaseSample.java000066400000000000000000000002061475274123300314350ustar00rootroot00000000000000package test.listeners.github1130; import org.testng.annotations.Listeners; @Listeners(MyListener.class) public class BaseSample {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1130/GitHub1130Test.java000066400000000000000000000027011475274123300317520ustar00rootroot00000000000000package test.listeners.github1130; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class GitHub1130Test extends SimpleBaseTest { @Test(description = "GITHUB-1130: IClassListener should only be instantiated once") public void classListenerShouldBeOnlyInstantiatedOnceInMultiTestContext() { checkGithub1130(createTests("GITHUB-1130", ASample.class, BSample.class)); } @Test public void classListenerShouldBeOnlyInstantiatedOnce() { checkGithub1130(create(ASample.class, BSample.class)); } private void checkGithub1130(TestNG tng) { MyListener.count = 0; MyListener.beforeSuiteCount = new ArrayList<>(); MyListener.beforeClassCount = new ArrayList<>(); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener((ITestNGListener) adapter); tng.run(); assertThat(adapter.getFailedTests()).isEmpty(); assertThat(adapter.getSkippedTests()).isEmpty(); assertThat(MyListener.beforeSuiteCount.size()).isEqualTo(1); assertThat(MyListener.beforeClassCount.size()).isEqualTo(2); assertThat(MyListener.beforeSuiteCount.get(0)) .isEqualTo(MyListener.beforeClassCount.get(0)) .isEqualTo(MyListener.beforeClassCount.get(1)); assertThat(MyListener.count).isEqualTo(1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1130/MyListener.java000066400000000000000000000022751475274123300315240ustar00rootroot00000000000000package test.listeners.github1130; import java.util.ArrayList; import java.util.List; import org.testng.IClassListener; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestClass; import org.testng.ITestContext; import org.testng.ITestResult; public class MyListener implements ISuiteListener, IClassListener { public static int count = 0; public static List beforeSuiteCount = new ArrayList<>(); public static List beforeClassCount = new ArrayList<>(); public MyListener() { count++; } public void onStart(ISuite suite) { beforeSuiteCount.add(this.toString()); } public void onBeforeClass(ITestClass testClass) { beforeClassCount.add(this.toString()); } public void onTestStart(ITestResult result) {} public void onTestSuccess(ITestResult result) {} public void onTestFailure(ITestResult result) {} public void onTestSkipped(ITestResult result) {} public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} public void onStart(ITestContext context) {} public void onFinish(ITestContext context) {} public void onFinish(ISuite suite) {} public void onAfterClass(ITestClass testClass) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1284/000077500000000000000000000000001475274123300265725ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1284/Listener1284.java000066400000000000000000000014661475274123300315500ustar00rootroot00000000000000package test.listeners.github1284; import java.util.LinkedList; import java.util.List; import org.testng.IClassListener; import org.testng.ITestClass; public class Listener1284 implements IClassListener { private static Listener1284 instance; static List testList = new LinkedList<>(); public Listener1284() { setInstance(this); } private static void setInstance(Listener1284 newInstance) { instance = newInstance; } public static Listener1284 getInstance() { return instance; } public void onBeforeClass(ITestClass iTestClass) { Listener1284.testList.add(iTestClass.getRealClass().getName() + " - Before Invocation"); } public void onAfterClass(ITestClass iTestClass) { Listener1284.testList.add(iTestClass.getRealClass().getName() + " - After Invocation"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1284/Sample1284.java000066400000000000000000000021501475274123300311730ustar00rootroot00000000000000package test.listeners.github1284; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.collections.Lists; public class Sample1284 { @Test public void testWithNoListener() { Assert.assertNull(Listener1284.getInstance()); Assert.assertEquals(Listener1284.testList.size(), 0); } @Test public void testWithListener() { Assert.assertNotNull(Listener1284.getInstance()); Assert.assertEquals(Listener1284.testList.size(), 1); Assert.assertEquals( Listener1284.testList.get(0), Sample1284.class.getName() + " - Before Invocation"); } @Test public void testWithChildListener() { Assert.assertNotNull(Listener1284.getInstance()); Assert.assertEquals(Listener1284.testList.size(), 3); String beforeInvocation = Sample1284.class.getName() + " - Before Invocation"; String afterInvocation = Sample1284.class.getName() + " - After Invocation"; List expectedList = Lists.newArrayList(beforeInvocation, afterInvocation, beforeInvocation); Assert.assertEquals(Listener1284.testList, expectedList); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1284/Sample1284B.java000066400000000000000000000012761475274123300313050ustar00rootroot00000000000000package test.listeners.github1284; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.collections.Lists; public class Sample1284B { @Test public void testTheOrderOfInvokedMethods() { Assert.assertNotNull(Listener1284.getInstance()); Assert.assertEquals(Listener1284.testList.size(), 5); String b1 = Sample1284.class.getName() + " - Before Invocation"; String a1 = Sample1284.class.getName() + " - After Invocation"; String b2 = Sample1284B.class.getName() + " - Before Invocation"; List expectedList = Lists.newArrayList(b1, a1, b1, a1, b2); Assert.assertEquals(Listener1284.testList, expectedList); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1284/TestListeners.java000066400000000000000000000021731475274123300322500ustar00rootroot00000000000000package test.listeners.github1284; import java.util.Collections; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class TestListeners extends SimpleBaseTest { @Test(priority = 1) public void verifyWithoutListener() { TestNG testNG = create(); testNG.setTestSuites( Collections.singletonList( getPathToResource("test/listeners/github1284/github1284_nolistener.xml"))); testNG.run(); Assert.assertEquals(testNG.getStatus(), 0); } @Test(priority = 2) public void verifyWithListener() { TestNG testNG = create(); testNG.setTestSuites( Collections.singletonList( getPathToResource("test/listeners/github1284/github1284_withlistener.xml"))); testNG.run(); Assert.assertEquals(testNG.getStatus(), 0); } @Test(priority = 3) public void verifyWithChildSuite() { TestNG testNG = create(); testNG.setTestSuites( Collections.singletonList(getPathToResource("test/listeners/github1284/github1284.xml"))); testNG.run(); Assert.assertEquals(testNG.getStatus(), 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1296/000077500000000000000000000000001475274123300265755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1296/GitHub1296Test.java000066400000000000000000000016771475274123300320170ustar00rootroot00000000000000package test.listeners.github1296; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class GitHub1296Test extends SimpleBaseTest { @Test(description = "https://github.com/cbeust/testng/issues/1296") public void test_number_of_call_of_configuration_listener() { MyConfigurationListener.CALLS.clear(); XmlSuite suite = createXmlSuite("Tests"); createXmlTest(suite, "Test version", MyTest.class); createXmlTest(suite, "Test version 2", MyTest.class); createXmlTest(suite, "Test version 3", MyTest.class); TestNG tng = create(suite); tng.run(); assertThat(MyConfigurationListener.CALLS) .hasSize(3) .containsOnly( entry("Test version", 2), entry("Test version 2", 2), entry("Test version 3", 2)); } } MyConfigurationListener.java000066400000000000000000000013411475274123300342030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1296package test.listeners.github1296; import java.util.HashMap; import java.util.Map; import org.testng.IConfigurationListener; import org.testng.ITestResult; public class MyConfigurationListener implements IConfigurationListener { public static final Map CALLS = new HashMap<>(); @Override public void onConfigurationSuccess(ITestResult itr) { String xmlTestName = itr.getTestContext().getCurrentXmlTest().getName(); Integer count = CALLS.get(xmlTestName); if (count == null) { count = 0; } count++; CALLS.put(xmlTestName, count); } @Override public void onConfigurationFailure(ITestResult iTestResult) {} @Override public void onConfigurationSkip(ITestResult itr) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1296/MyTest.java000066400000000000000000000007001475274123300306620ustar00rootroot00000000000000package test.listeners.github1296; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(MyConfigurationListener.class) public class MyTest { @BeforeTest public void setUp() {} @Test public void test() { assertTrue(true); } @AfterTest public void tearDown() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1319/000077500000000000000000000000001475274123300265715ustar00rootroot00000000000000TestResultInstanceCheckTest.java000066400000000000000000000011561475274123300347610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1319package test.listeners.github1319; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class TestResultInstanceCheckTest extends SimpleBaseTest { @Test public void testInstances() { TestNG tng = create(TestSample.class); tng.run(); int hashCode = TestSample.hashcode; Assert.assertEquals(TestSample.Listener.maps.size(), 6, "Validating the number of instances"); for (Object object : TestSample.Listener.maps.values()) { Assert.assertNotNull(object); Assert.assertEquals(object.hashCode(), hashCode); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1319/TestSample.java000066400000000000000000000037501475274123300315220ustar00rootroot00000000000000package test.listeners.github1319; import com.google.common.collect.Maps; import java.util.Map; import org.testng.*; import org.testng.annotations.*; @Listeners(TestSample.Listener.class) public class TestSample { public static int hashcode; public TestSample() { hashcode = hashCode(); } @Test public void test1() { Assert.assertTrue(true); } @Test public void test2() { Assert.assertTrue(false); } @Test public void test3() { throw new SkipException("simulating a skip"); } @AfterClass public void afterClass() {} @AfterTest public void afterTest() { throw new RuntimeException("Simulating a failure"); } @AfterSuite public void afterSuite() { throw new SkipException("simulating a skip"); } public static class Listener implements IConfigurationListener, ITestListener { public static Map maps = Maps.newConcurrentMap(); public void onConfigurationSuccess(ITestResult itr) { maps.put(itr.getMethod().getMethodName(), itr.getInstance()); } public void onConfigurationFailure(ITestResult itr) { maps.put(itr.getMethod().getMethodName(), itr.getInstance()); } public void onConfigurationSkip(ITestResult itr) { maps.put(itr.getMethod().getMethodName(), itr.getInstance()); } @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult itr) { maps.put(itr.getMethod().getMethodName(), itr.getInstance()); } @Override public void onTestFailure(ITestResult itr) { maps.put(itr.getMethod().getMethodName(), itr.getInstance()); } @Override public void onTestSkipped(ITestResult itr) { maps.put(itr.getMethod().getMethodName(), itr.getInstance()); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1393/000077500000000000000000000000001475274123300265735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1393/Listener1393.java000066400000000000000000000006261475274123300315470ustar00rootroot00000000000000package test.listeners.github1393; import org.testng.ITestResult; import org.testng.TestListenerAdapter; public class Listener1393 extends TestListenerAdapter { public void onTestStart(ITestResult testContext) { super.onTestStart(testContext); System.out.println("In onTestStart"); testContext.setStatus(ITestResult.FAILURE); throw new RuntimeException("Trying to fail a test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1465/000077500000000000000000000000001475274123300265735ustar00rootroot00000000000000ExampleClassListener.java000066400000000000000000000035361475274123300334550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1465package test.listeners.github1465; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; public class ExampleClassListener implements IInvokedMethodListener { final List messages = new LinkedList<>(); final List configMsgs = new LinkedList<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { log("beforeInvocation:", method, testResult); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { log("afterInvocation:", method, testResult); } private void log(String prefix, IInvokedMethod method, ITestResult testResult) { String msg = prefix + "_" + typeOfMethod(method); msg += method.getTestMethod().getMethodName() + parameters(testResult); if (method.isConfigurationMethod()) { configMsgs.add(msg); } else { messages.add(msg); } } private static String typeOfMethod(IInvokedMethod method) { ITestNGMethod tm = method.getTestMethod(); if (tm.isBeforeMethodConfiguration()) { return "before_method: "; } if (tm.isAfterMethodConfiguration()) { return "after_method: "; } return "test_method: "; } private static String parameters(ITestResult testResult) { Object[] parameters = testResult.getParameters(); if (parameters == null) { return ""; } String returnValue = ""; StringBuilder builder = new StringBuilder(); for (Object parameter : parameters) { if (parameter instanceof Method) { builder.append(((Method) parameter).getName()); } } if (builder.length() != 0) { returnValue = "[" + builder.toString() + "]"; } return returnValue; } } ExampleClassSample.java000066400000000000000000000012141475274123300331000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1465package test.listeners.github1465; import static org.testng.Assert.assertTrue; import java.lang.reflect.Method; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ExampleClassSample { @BeforeMethod public void beforeMethod(Method method) { if ("test1".equals(method.getName())) { throw new SkipException("Skip from [before]"); } } @Test public void test1() { assertTrue(true); } @Test public void test2() { assertTrue(true); } @AfterMethod public void afterMethod(Method method) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1465/IssueTest.java000066400000000000000000000045211475274123300313700ustar00rootroot00000000000000package test.listeners.github1465; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(dataProvider = "dp") public void reproduceIssue(XmlSuite.FailurePolicy policy, String[] expectedMsgs) { TestNG testNG = create(ExampleClassSample.class); testNG.setConfigFailurePolicy(policy); ExampleClassListener listener = new ExampleClassListener(); testNG.addListener(listener); testNG.run(); String[] expected = new String[] { "beforeInvocation:_test_method: test1", "afterInvocation:_test_method: test1", "beforeInvocation:_test_method: test2", "afterInvocation:_test_method: test2" }; assertThat(listener.messages).containsExactly(expected); assertThat(listener.configMsgs).containsExactly(expectedMsgs); } @DataProvider(name = "dp") public Object[][] getdata() { String[] continueFailurePolicyExpected = new String[] { "beforeInvocation:_before_method: beforeMethod[test1]", "afterInvocation:_before_method: beforeMethod[test1]", "beforeInvocation:_after_method: afterMethod[test1]", "afterInvocation:_after_method: afterMethod[test1]", "beforeInvocation:_before_method: beforeMethod[test2]", "afterInvocation:_before_method: beforeMethod[test2]", "beforeInvocation:_after_method: afterMethod[test2]", "afterInvocation:_after_method: afterMethod[test2]" }; String[] skipFailurePolicyExpected = new String[] { "beforeInvocation:_before_method: beforeMethod[test1]", "afterInvocation:_before_method: beforeMethod[test1]", "beforeInvocation:_after_method: afterMethod", "afterInvocation:_after_method: afterMethod", "beforeInvocation:_before_method: beforeMethod", "afterInvocation:_before_method: beforeMethod", "beforeInvocation:_after_method: afterMethod", "afterInvocation:_after_method: afterMethod" }; return new Object[][] { {XmlSuite.FailurePolicy.CONTINUE, continueFailurePolicyExpected}, {XmlSuite.FailurePolicy.SKIP, skipFailurePolicyExpected} }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1490/000077500000000000000000000000001475274123300265715ustar00rootroot00000000000000DataProviderInfoProvider.java000066400000000000000000000013221475274123300342660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1490package test.listeners.github1490; import org.testng.IDataProviderListener; import org.testng.IDataProviderMethod; import org.testng.ITestContext; import org.testng.ITestNGMethod; public class DataProviderInfoProvider implements IDataProviderListener { public static IDataProviderMethod before; public static IDataProviderMethod after; @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { before = dataProviderMethod; } @Override public void afterDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { after = dataProviderMethod; } } InstanceAwareLocalDataProviderListener.java000066400000000000000000000025071475274123300370730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1490package test.listeners.github1490; import java.util.Set; import org.testng.IDataProviderMethod; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.collections.Sets; public class InstanceAwareLocalDataProviderListener extends LocalDataProviderListener { public static Set instanceCollectionBeforeExecution = Sets.newHashSet(); public static Set instanceCollectionAfterExecution = Sets.newHashSet(); public InstanceAwareLocalDataProviderListener() { instanceCollectionBeforeExecution.clear(); instanceCollectionAfterExecution.clear(); } @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { super.beforeDataProviderExecution(dataProviderMethod, method, iTestContext); if (dataProviderMethod.getInstance() != null) { instanceCollectionBeforeExecution.add(dataProviderMethod.getInstance()); } } @Override public void afterDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { super.afterDataProviderExecution(dataProviderMethod, method, iTestContext); if (dataProviderMethod.getInstance() != null) { instanceCollectionAfterExecution.add(dataProviderMethod.getInstance()); } } } LocalDataProviderListener.java000066400000000000000000000020321475274123300344170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1490package test.listeners.github1490; import java.util.List; import org.testng.IDataProviderListener; import org.testng.IDataProviderMethod; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.collections.Lists; public class LocalDataProviderListener implements IDataProviderListener { public static final List messages = Lists.newArrayList(); @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { log(method, "before:"); } @Override public void afterDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { log(method, "after:"); } private static void log(ITestNGMethod method, String prefix) { if (method.getInstance() != null) { messages.add( prefix + method.getInstance().getClass().getName() + "." + method.getMethodName()); } else { messages.add(prefix + method.getMethodName()); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1602/000077500000000000000000000000001475274123300265645ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1602/IssueTest.java000066400000000000000000000041511475274123300313600ustar00rootroot00000000000000package test.listeners.github1602; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(dataProvider = "dp") public void testListenerInvocation( Class clazz, XmlSuite.FailurePolicy policy, List expected) { TestNG tng = create(clazz); ListenerForIssue1602 listener = new ListenerForIssue1602(); tng.setConfigFailurePolicy(policy); tng.addListener(listener); tng.run(); assertThat(listener.getLogs()).containsExactlyElementsOf(expected); } @DataProvider(name = "dp") public Object[][] getData() { List passList = Arrays.asList( "BeforeInvocation_beforeMethod_STARTED", "AfterInvocation_beforeMethod_SUCCESS", "BeforeInvocation_testMethod_STARTED", "AfterInvocation_testMethod_SUCCESS", "BeforeInvocation_afterMethod_STARTED", "AfterInvocation_afterMethod_SUCCESS"); List baseList = Arrays.asList( "BeforeInvocation_beforeMethod_STARTED", "AfterInvocation_beforeMethod_FAILURE", "BeforeInvocation_testMethod_SKIP", "AfterInvocation_testMethod_SKIP", "BeforeInvocation_afterMethod_STARTED"); List skipList = Lists.newArrayList(baseList); skipList.add("AfterInvocation_afterMethod_SKIP"); List failList = Lists.newArrayList(baseList); failList.add("AfterInvocation_afterMethod_FAILURE"); return new Object[][] { {TestClassWithPassingConfigsSample.class, XmlSuite.FailurePolicy.SKIP, passList}, {TestClassWithFailingConfigsSample.class, XmlSuite.FailurePolicy.SKIP, skipList}, {TestClassWithPassingConfigsSample.class, XmlSuite.FailurePolicy.CONTINUE, passList}, {TestClassWithFailingConfigsSample.class, XmlSuite.FailurePolicy.CONTINUE, failList} }; } } ListenerForIssue1602.java000066400000000000000000000027301475274123300331300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1602package test.listeners.github1602; import java.util.Collections; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.collections.Lists; public class ListenerForIssue1602 implements IInvokedMethodListener { private List logs = Collections.synchronizedList(Lists.newArrayList()); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { logs.add( "BeforeInvocation_" + method.getTestMethod().getMethodName() + "_" + intToStatus(testResult)); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { logs.add( "AfterInvocation_" + method.getTestMethod().getMethodName() + "_" + intToStatus(testResult)); } public List getLogs() { return logs; } private String intToStatus(ITestResult testResult) { int status = testResult.getStatus(); switch (status) { case ITestResult.CREATED: return "CREATED"; case ITestResult.SUCCESS: return "SUCCESS"; case ITestResult.SKIP: return "SKIP"; case ITestResult.FAILURE: return "FAILURE"; case ITestResult.STARTED: return "STARTED"; case ITestResult.SUCCESS_PERCENTAGE_FAILURE: return "SUCCESS_PERCENTAGE_FAILURE"; } return " ??? " + String.valueOf(status); } } TestClassWithFailingConfigsSample.java000066400000000000000000000006431475274123300360610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1602package test.listeners.github1602; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestClassWithFailingConfigsSample { @BeforeMethod public void beforeMethod() { throw new RuntimeException(); } @Test public void testMethod() {} @AfterMethod public void afterMethod() { throw new RuntimeException(); } } TestClassWithPassingConfigsSample.java000066400000000000000000000005311475274123300361100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1602package test.listeners.github1602; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestClassWithPassingConfigsSample { @BeforeMethod public void beforeMethod() {} @Test public void testMethod() {} @AfterMethod public void afterMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1735/000077500000000000000000000000001475274123300265735ustar00rootroot00000000000000ExecutionListenerTest.java000066400000000000000000000015761475274123300337010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1735package test.listeners.github1735; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class ExecutionListenerTest extends SimpleBaseTest { @Test public void ensureExecutionListenerIsInvokedOnlyOnce() { XmlSuite suite = createXmlSuite("suite"); createXmlTest(suite, "test1", TestClassSample.class, TestClassTwoSample.class); createXmlTest(suite, "test2", TestClassSample.class, TestClassTwoSample.class); TestNG testng = create(suite); testng.run(); assertThat(LocalExecutionListener.getFinish()) .containsExactlyElementsOf(Collections.singletonList("finish")); assertThat(LocalExecutionListener.getStart()) .containsExactlyElementsOf(Collections.singletonList("start")); } } LocalExecutionListener.java000066400000000000000000000011611475274123300340020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1735package test.listeners.github1735; import java.util.List; import org.testng.IExecutionListener; import org.testng.collections.Lists; public class LocalExecutionListener implements IExecutionListener { private static final List start = Lists.newArrayList(); private static final List finish = Lists.newArrayList(); @Override public void onExecutionStart() { start.add("start"); } @Override public void onExecutionFinish() { finish.add("finish"); } public static List getFinish() { return finish; } public static List getStart() { return start; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1735/TestClassSample.java000066400000000000000000000003421475274123300325040ustar00rootroot00000000000000package test.listeners.github1735; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(LocalExecutionListener.class) public class TestClassSample { @Test public void testMethod() {} } TestClassTwoSample.java000066400000000000000000000003451475274123300331220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github1735package test.listeners.github1735; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(LocalExecutionListener.class) public class TestClassTwoSample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/000077500000000000000000000000001475274123300265755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/BaseTestCLass.java000066400000000000000000000002131475274123300320740ustar00rootroot00000000000000package test.listeners.github2385; import org.testng.annotations.Listeners; @Listeners(TestListener.class) public class BaseTestCLass {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/FatherTestClass.java000066400000000000000000000003731475274123300325020ustar00rootroot00000000000000package test.listeners.github2385; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(TestClassListener.class) public class FatherTestClass extends BaseTestCLass { @Test public void testClassListeners() {} } ITestClassInterface.java000066400000000000000000000002321475274123300332150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Listeners; @Listeners(TestClassListener.class) public interface ITestClassInterface {} ITestInheritedInterface.java000066400000000000000000000002651475274123300340710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Listeners; @Listeners(TestClassListener.class) public interface ITestInheritedInterface extends ITestInterface {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/ITestInterface.java000066400000000000000000000002201475274123300323030ustar00rootroot00000000000000package test.listeners.github2385; import org.testng.annotations.Listeners; @Listeners(TestListener.class) public interface ITestInterface {} ITestInterfaceSame.java000066400000000000000000000002241475274123300330360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Listeners; @Listeners(TestListener.class) public interface ITestInterfaceSame {} ITestInterfaceSameInherit.java000066400000000000000000000002621475274123300343630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Listeners; @Listeners(TestListener.class) public interface ITestInterfaceSameInherit extends ITestInterface {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/IssueTest.java000066400000000000000000000062721475274123300313770ustar00rootroot00000000000000package test.listeners.github2385; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import org.testng.xml.XmlPackage; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testExtendClass() { TestNG testNG = create(SonTestClassSample.class); testNG.run(); assertTrue(TestListener.listenerExecuted); assertTrue(TestListener.listenerMethodInvoked); } @Test public void testClassAndInterface() { TestNG testNG = create(TestClassAndInterfaceInheritSample.class); testNG.run(); assertTrue(TestListener.listenerExecuted); assertTrue(TestListener.listenerMethodInvoked); assertTrue(TestClassListener.listenerMethodInvoked); } @Test public void testClassListeners() { TestNG testNG = create(TestClassListenersInheritSample.class); testNG.run(); assertTrue(TestListener.listenerExecuted); assertTrue(TestListener.listenerMethodInvoked); } @Test public void testInterface() { TestNG testNG = create(TestInterfaceListenersInheritSample.class); testNG.run(); assertTrue(TestListener.listenerExecuted); assertTrue(TestListener.listenerMethodInvoked); } @Test public void testMultiInherit() { TestNG testNG = create(TestMultiInheritSample.class); testNG.run(); assertTrue(TestListener.listenerMethodInvoked); assertTrue(TestClassListener.listenerMethodInvoked); } @Test public void testMultiInheritSameAnnotation() { TestNG testNG = create(TestMultiInheritSameAnnotationSample.class); testNG.run(); assertTrue(TestListener.listenerMethodInvoked); } @Test public void testMultiLevel() { TestNG testNG = create(TestMultiLevelInheritSample.class); testNG.run(); assertTrue(TestListener.listenerExecuted); assertTrue(TestListener.listenerMethodInvoked); assertTrue(TestClassListener.listenerMethodInvoked); } @Test public void testMultiLevelSameAnnotation() { TestNG testNG = create(TestMultiLevelInheritSameAnnotationSample.class); testNG.run(); assertTrue(TestListener.listenerExecuted); assertTrue(TestListener.listenerMethodInvoked); } @Test public void testPackages() { List packages = new ArrayList<>(); XmlPackage xmlPackage = new XmlPackage("test.listeners.github2385.packages"); packages.add(xmlPackage); XmlTest test = new XmlTest(); test.setName("MyTest"); test.setXmlPackages(packages); XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("MySuite"); xmlSuite.setTests(Collections.singletonList(test)); test.setXmlSuite(xmlSuite); TestNG tng = new TestNG(); tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); assertFalse(TestListener.listenerMethodInvoked); } @AfterMethod public void reset() { TestListener.listenerExecuted = false; TestListener.listenerMethodInvoked = false; TestClassListener.listenerMethodInvoked = false; } } SonTestClassSample.java000066400000000000000000000002551475274123300331120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class SonTestClassSample extends FatherTestClass { @Test public void testSonClass() {} } TestClassAndInterfaceInheritSample.java000066400000000000000000000004251475274123300362200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(TestClassListener.class) public class TestClassAndInterfaceInheritSample implements ITestInterface { @Test public void testClassAndInterface() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/TestClassListener.java000066400000000000000000000010021475274123300330440ustar00rootroot00000000000000package test.listeners.github2385; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class TestClassListener implements IInvokedMethodListener { public static boolean listenerExecuted = false; public static boolean listenerMethodInvoked = false; public TestClassListener() { listenerExecuted = true; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { listenerMethodInvoked = true; } } TestClassListenersInheritSample.java000066400000000000000000000002761475274123300356510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class TestClassListenersInheritSample extends BaseTestCLass { @Test public void testClassListeners() {} } TestInterfaceListenersInheritSample.java000066400000000000000000000003021475274123300364720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class TestInterfaceListenersInheritSample implements ITestInterface { @Test public void testInterface() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/TestListener.java000066400000000000000000000007761475274123300320770ustar00rootroot00000000000000package test.listeners.github2385; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public final class TestListener implements IInvokedMethodListener { public static boolean listenerExecuted = false; public static boolean listenerMethodInvoked = false; public TestListener() { listenerExecuted = true; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { listenerMethodInvoked = true; } } TestMultiInheritSameAnnotationSample.java000066400000000000000000000003501475274123300366370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class TestMultiInheritSameAnnotationSample implements ITestInterface, ITestInterfaceSame { @Test public void testMultiInheritSameAnnotation() {} } TestMultiInheritSample.java000066400000000000000000000003151475274123300337770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class TestMultiInheritSample implements ITestClassInterface, ITestInterface { @Test public void testMultiInherit() {} } TestMultiLevelInheritSameAnnotationSample.java000066400000000000000000000003241475274123300376300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class TestMultiLevelInheritSameAnnotationSample implements ITestInterfaceSameInherit { @Test public void testMultiLevel() {} } TestMultiLevelInheritSample.java000066400000000000000000000003041475274123300347650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385package test.listeners.github2385; import org.testng.annotations.Test; public class TestMultiLevelInheritSample implements ITestInheritedInterface { @Test public void testMultiLevel() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/packages/000077500000000000000000000000001475274123300303535ustar00rootroot00000000000000ITestInterfaceWithoutImpl.java000066400000000000000000000002531475274123300362160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/packagespackage test.listeners.github2385.packages; import org.testng.annotations.Listeners; @Listeners(TestPackageListener.class) public interface ITestInterfaceWithoutImpl {} TestPackageListener.java000066400000000000000000000010171475274123300350370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/packagespackage test.listeners.github2385.packages; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class TestPackageListener implements IInvokedMethodListener { public static boolean listenerExecuted = false; public static boolean listenerMethodInvoked = false; public TestPackageListener() { listenerExecuted = true; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { listenerMethodInvoked = true; } } TestWithoutImplSample.java000066400000000000000000000002441475274123300354260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2385/packagespackage test.listeners.github2385.packages; import org.testng.annotations.Test; public class TestWithoutImplSample { @Test public void testWithoutImpl() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/000077500000000000000000000000001475274123300265665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/FirstTestSample.java000066400000000000000000000006731475274123300325300ustar00rootroot00000000000000package test.listeners.github2522; import org.testng.Assert; import org.testng.annotations.Test; public class FirstTestSample { @Test(description = "First test step") public void firstMethod() {} @Test(description = "Second test step", dependsOnMethods = "firstMethod") public void secondMethod() { Assert.fail(); } @Test(description = "Third test step", dependsOnMethods = "secondMethod") public void thirdMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/IssueTest.java000066400000000000000000000055171475274123300313710ustar00rootroot00000000000000package test.listeners.github2522; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void issueTest() { TestNG testNG = create(FirstTestSample.class, SecondTestSample.class); testNG.addListener(new TestListener()); testNG.run(); Assert.assertEquals( ITestResult.STARTED, TestListener.beforeInvocation .get("test.listeners.github2522.FirstTestSamplefirstMethod") .intValue()); Assert.assertEquals( ITestResult.STARTED, TestListener.beforeInvocation .get("test.listeners.github2522.FirstTestSamplesecondMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.beforeInvocation .get("test.listeners.github2522.FirstTestSamplethirdMethod") .intValue()); Assert.assertEquals( ITestResult.STARTED, TestListener.beforeInvocation .get("test.listeners.github2522.SecondTestSamplefirstMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.beforeInvocation .get("test.listeners.github2522.SecondTestSamplesecondMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.beforeInvocation .get("test.listeners.github2522.SecondTestSamplethirdMethod") .intValue()); Assert.assertEquals( ITestResult.SUCCESS, TestListener.afterInvocation .get("test.listeners.github2522.FirstTestSamplefirstMethod") .intValue()); Assert.assertEquals( ITestResult.FAILURE, TestListener.afterInvocation .get("test.listeners.github2522.FirstTestSamplesecondMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.afterInvocation .get("test.listeners.github2522.FirstTestSamplethirdMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.afterInvocation .get("test.listeners.github2522.SecondTestSamplefirstMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.afterInvocation .get("test.listeners.github2522.SecondTestSamplesecondMethod") .intValue()); Assert.assertEquals( ITestResult.SKIP, TestListener.afterInvocation .get("test.listeners.github2522.SecondTestSamplethirdMethod") .intValue()); } @Test public void testSkip() { TestNG testNG = create(SkipTestSample.class); testNG.addListener(new SkipTestListener()); testNG.run(); Assert.assertTrue(SkipTestSample.getFlag()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/SecondTestSample.java000066400000000000000000000006141475274123300326470ustar00rootroot00000000000000package test.listeners.github2522; import org.testng.annotations.Test; public class SecondTestSample { @Test(description = "First test step") public void firstMethod() {} @Test(description = "Second test step", dependsOnMethods = "firstMethod") public void secondMethod() {} @Test(description = "Third test step", dependsOnMethods = "secondMethod") public void thirdMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/SkipTestListener.java000066400000000000000000000006641475274123300327130ustar00rootroot00000000000000package test.listeners.github2522; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class SkipTestListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult result) { if (invokedMethod.getTestMethod().getMethodName().contains("oneTest")) { result.setStatus(ITestResult.SKIP); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/SkipTestSample.java000066400000000000000000000004521475274123300323420ustar00rootroot00000000000000package test.listeners.github2522; import org.testng.annotations.Test; public class SkipTestSample { private static boolean flag = true; @Test() public void oneTest() { flag = false; } @Test() public void twoTest() {} public static boolean getFlag() { return flag; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2522/TestListener.java000066400000000000000000000020241475274123300320540ustar00rootroot00000000000000package test.listeners.github2522; import java.util.HashMap; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class TestListener implements IInvokedMethodListener { private boolean hasFailures = false; public static Map beforeInvocation = new HashMap<>(); public static Map afterInvocation = new HashMap<>(); @Override public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult result) { beforeInvocation.put(result.getTestClass().getName() + result.getName(), result.getStatus()); if (hasFailures) { result.setStatus(ITestResult.SKIP); } } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { afterInvocation.put( testResult.getTestClass().getName() + testResult.getName(), testResult.getStatus()); if (!method.isTestMethod()) { return; } if (!testResult.isSuccess()) { hasFailures = true; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558/000077500000000000000000000000001475274123300265775ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558/CallHolder.java000066400000000000000000000006111475274123300314510ustar00rootroot00000000000000package test.listeners.github2558; import java.util.List; import org.assertj.core.util.Lists; public class CallHolder { private static final List calls = Lists.newArrayList(); public static void addCall(String identifier) { calls.add(identifier); } public static void clear() { calls.clear(); } public static List getCalls() { return calls; } } ClassMethodListenersHolder.java000066400000000000000000000037121475274123300346230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558package test.listeners.github2558; import org.testng.IClassListener; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestClass; import org.testng.ITestResult; public class ClassMethodListenersHolder { public static class ClassMethodListenerA implements IClassListener, IInvokedMethodListener { @Override public void onBeforeClass(ITestClass testClass) { CallHolder.addCall(getClass().getName() + ".onBeforeClass()"); } @Override public void onAfterClass(ITestClass testClass) { CallHolder.addCall(getClass().getName() + ".onBeforeClass()"); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isConfigurationMethod()) { return; } CallHolder.addCall(getClass().getName() + ".beforeInvocation()"); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isConfigurationMethod()) { return; } CallHolder.addCall(getClass().getName() + ".afterInvocation()"); } } public static class ClassMethodListenerB implements IClassListener, IInvokedMethodListener { @Override public void onBeforeClass(ITestClass testClass) { CallHolder.addCall(getClass().getName() + ".onBeforeClass()"); } @Override public void onAfterClass(ITestClass testClass) { CallHolder.addCall(getClass().getName() + ".onBeforeClass()"); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isConfigurationMethod()) { return; } CallHolder.addCall(getClass().getName() + ".beforeInvocation()"); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { if (method.isConfigurationMethod()) { return; } CallHolder.addCall(getClass().getName() + ".afterInvocation()"); } } } DataProviderListenersHolder.java000066400000000000000000000025471475274123300350060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558package test.listeners.github2558; import org.testng.IDataProviderListener; import org.testng.IDataProviderMethod; import org.testng.ITestContext; import org.testng.ITestNGMethod; public class DataProviderListenersHolder { public static class DataProviderListenerA implements IDataProviderListener { @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { CallHolder.addCall(getClass().getName() + ".beforeDataProviderExecution()"); } @Override public void afterDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { CallHolder.addCall(getClass().getName() + ".afterDataProviderExecution()"); } } public static class DataProviderListenerB implements IDataProviderListener { @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { CallHolder.addCall(getClass().getName() + ".beforeDataProviderExecution()"); } @Override public void afterDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { CallHolder.addCall(getClass().getName() + ".afterDataProviderExecution()"); } } } ExecutionListenersHolder.java000066400000000000000000000014351475274123300343600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558package test.listeners.github2558; import org.testng.IExecutionListener; public class ExecutionListenersHolder { public static class ExecutionListenerA implements IExecutionListener { @Override public void onExecutionStart() { CallHolder.addCall(getClass().getName() + ".onExecutionStart()"); } @Override public void onExecutionFinish() { CallHolder.addCall(getClass().getName() + ".onExecutionFinish()"); } } public static class ExecutionListenerB implements IExecutionListener { @Override public void onExecutionStart() { CallHolder.addCall(getClass().getName() + ".onExecutionStart()"); } @Override public void onExecutionFinish() { CallHolder.addCall(getClass().getName() + ".onExecutionFinish()"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558/ReportersHolder.java000066400000000000000000000013041475274123300325630ustar00rootroot00000000000000package test.listeners.github2558; import java.util.List; import org.testng.IReporter; import org.testng.ISuite; import org.testng.xml.XmlSuite; public class ReportersHolder { public static class ReporterA implements IReporter { @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { CallHolder.addCall(getClass().getName() + ".generateReport()"); } } public static class ReporterB implements IReporter { @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { CallHolder.addCall(getClass().getName() + ".generateReport()"); } } } SuiteAlterListenersHolder.java000066400000000000000000000011001475274123300344630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558package test.listeners.github2558; import java.util.List; import org.testng.IAlterSuiteListener; import org.testng.xml.XmlSuite; public class SuiteAlterListenersHolder { public static class SuiteAlterA implements IAlterSuiteListener { @Override public void alter(List suites) { CallHolder.addCall(getClass().getName() + ".alter()"); } } public static class SuiteAlterB implements IAlterSuiteListener { @Override public void alter(List suites) { CallHolder.addCall(getClass().getName() + ".alter()"); } } } SuiteListenersHolder.java000066400000000000000000000014071475274123300335050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558package test.listeners.github2558; import org.testng.ISuite; import org.testng.ISuiteListener; public class SuiteListenersHolder { public static class SuiteListenerA implements ISuiteListener { @Override public void onStart(ISuite suite) { CallHolder.addCall(getClass().getName() + ".onStart()"); } @Override public void onFinish(ISuite suite) { CallHolder.addCall(getClass().getName() + ".onFinish()"); } } public static class SuiteListenerB implements ISuiteListener { @Override public void onStart(ISuite suite) { CallHolder.addCall(getClass().getName() + ".onStart()"); } @Override public void onFinish(ISuite suite) { CallHolder.addCall(getClass().getName() + ".onFinish()"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558/TestClassSamples.java000066400000000000000000000010721475274123300326740ustar00rootroot00000000000000package test.listeners.github2558; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestClassSamples { public static class TestClassSampleA { @BeforeClass public void beforeClass() {} @Test public void testMethod() {} @AfterClass public void afterClass() {} } public static class TestClassSampleB { @BeforeClass public void beforeClass() {} @Test public void testMethod() {} @AfterClass public void afterClass() {} } } TestListenersHolder.java000066400000000000000000000014631475274123300333350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github2558package test.listeners.github2558; import org.testng.ITestContext; import org.testng.ITestListener; public class TestListenersHolder { public static class TestListenerA implements ITestListener { @Override public void onStart(ITestContext context) { CallHolder.addCall(getClass().getName() + ".onStart(ctx)"); } @Override public void onFinish(ITestContext context) { CallHolder.addCall(getClass().getName() + ".onFinish(ctx)"); } } public static class TestListenerB implements ITestListener { @Override public void onStart(ITestContext context) { CallHolder.addCall(getClass().getName() + ".onStart(ctx)"); } @Override public void onFinish(ITestContext context) { CallHolder.addCall(getClass().getName() + ".onFinish(ctx)"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github551/000077500000000000000000000000001475274123300265065ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github551/ConfigListener.java000066400000000000000000000007511475274123300322670ustar00rootroot00000000000000package test.listeners.github551; import org.testng.IConfigurationListener; import org.testng.ITestResult; public class ConfigListener implements IConfigurationListener { public static long executionTime = 0; @Override public void onConfigurationSuccess(ITestResult itr) {} @Override public void onConfigurationFailure(ITestResult itr) { executionTime = itr.getEndMillis() - itr.getStartMillis(); } @Override public void onConfigurationSkip(ITestResult itr) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github551/Test551.java000066400000000000000000000010521475274123300305210ustar00rootroot00000000000000package test.listeners.github551; import java.io.IOException; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class Test551 extends SimpleBaseTest { @Test public void testExecutionTimeOfFailedConfig() throws IOException { ConfigListener listener = new ConfigListener(); TestNG testNG = create(TestWithFailingConfig.class); testNG.addListener(listener); testNG.run(); Assert.assertTrue(listener.executionTime >= TestWithFailingConfig.EXEC_TIME); } } TestWithFailingConfig.java000066400000000000000000000006061475274123300334670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github551package test.listeners.github551; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestWithFailingConfig { public static final int EXEC_TIME = 300; @BeforeClass public void setUpClassWaitThenFail() throws InterruptedException { Thread.sleep(EXEC_TIME); throw new RuntimeException(); } @Test public void testNothing() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github956/000077500000000000000000000000001475274123300265175ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github956/ListenerFor956.java000066400000000000000000000016401475274123300320630ustar00rootroot00000000000000package test.listeners.github956; import java.util.List; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.collections.Lists; public class ListenerFor956 implements ITestListener { private static final List messages = Lists.newArrayList(); public static List getMessages() { return messages; } @Override public void onStart(ITestContext context) { messages.add("Executing " + context.getCurrentXmlTest().getName()); } @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) {} @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onFinish(ITestContext context) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/github956/TestClassContainer.java000066400000000000000000000007711475274123300331370ustar00rootroot00000000000000package test.listeners.github956; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; public class TestClassContainer { @Listeners(ListenerFor956.class) public static class FirstTestClass { @Test public void testMethod() { Assert.assertEquals(true, true); } } @Listeners(ListenerFor956.class) public static class SecondTestClass { @Test public void testMethod() { Assert.assertEquals(true, true); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue1777/000077500000000000000000000000001475274123300264475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue1777/IssueTest.java000066400000000000000000000047361475274123300312540ustar00rootroot00000000000000package test.listeners.issue1777; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { public static final String GITHUB_1777 = "GITHUB-1777"; @Test(description = GITHUB_1777) public void testOnStartInvokedForSkippedTests() { TestNG testNG = create(TestClassSample.class); testNG.alwaysRunListeners(true); testNG.setConfigFailurePolicy(XmlSuite.FailurePolicy.CONTINUE); MyListener listener = new MyListener(); testNG.addListener(listener); testNG.run(); List expectedTestMessages = Arrays.asList( "testStart_test_method: test1", "before_test_method: test1", "before_test_method: test1", "after_test_method: test1", "after_test_method: test1", "testSkipped_test_method: test1", "testStart_test_method: test2", "before_test_method: test2", "before_test_method: test2", "after_test_method: test2", "after_test_method: test2", "testSuccess_test_method: test2"); assertThat(listener.tstMsgs).containsExactlyElementsOf(expectedTestMessages); List expectedConfigMessages = Arrays.asList( "before_configuration_method: beforeMethod[test1]", "before_configuration_method: beforeMethod[test1]", "after_configuration_method: beforeMethod[test1]", "after_configuration_method: beforeMethod[test1]", "before_configuration_method: afterMethod[test1]", "before_configuration_method: afterMethod[test1]", "after_configuration_method: afterMethod[test1]", "after_configuration_method: afterMethod[test1]", "before_configuration_method: beforeMethod[test2]", "before_configuration_method: beforeMethod[test2]", "after_configuration_method: beforeMethod[test2]", "after_configuration_method: beforeMethod[test2]", "before_configuration_method: afterMethod[test2]", "before_configuration_method: afterMethod[test2]", "after_configuration_method: afterMethod[test2]", "after_configuration_method: afterMethod[test2]"); assertThat(listener.cfgMsgs).containsExactlyElementsOf(expectedConfigMessages); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue1777/MyListener.java000066400000000000000000000056261475274123300314160ustar00rootroot00000000000000package test.listeners.issue1777; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; public class MyListener implements IInvokedMethodListener, ITestListener { List allMsgs = new LinkedList<>(); List tstMsgs = new LinkedList<>(); List cfgMsgs = new LinkedList<>(); @Override public void onFinish(ITestContext testContext) {} @Override public void onStart(ITestContext testContext) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult testResult) { log("testFailedBut", testResult); } @Override public void onTestFailure(ITestResult testResult) { log("testFailed", testResult); } @Override public void onTestSkipped(ITestResult testResult) { log("testSkipped", testResult); } @Override public void onTestStart(ITestResult testResult) { log("testStart", testResult); } @Override public void onTestSuccess(ITestResult testResult) { log("testSuccess", testResult); } @Override public void afterInvocation( IInvokedMethod method, ITestResult testResult, ITestContext testContext) { log("after", method, testResult); } @Override public void beforeInvocation( IInvokedMethod method, ITestResult testResult, ITestContext testContext) { log("before", method, testResult); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { log("before", method, testResult); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { log("after", method, testResult); } private void log(String prefix, ITestResult testResult) { log(prefix, testResult.getMethod(), testResult); } private void log(String prefix, IInvokedMethod method, ITestResult testResult) { log(prefix, method.getTestMethod(), testResult); } private void log(String prefix, ITestNGMethod method, ITestResult testResult) { String msg = prefix + "_"; if (method.isTest()) { msg += "test_method: "; } else { msg += "configuration_method: "; } msg += method.getMethodName() + parameters(testResult); allMsgs.add(msg); if (method.isTest()) { tstMsgs.add(msg); } else { cfgMsgs.add(msg); } } private String parameters(ITestResult testResult) { Object[] parameters = testResult.getParameters(); if (parameters != null) { StringBuilder builder = new StringBuilder(); for (Object parameter : parameters) { if (parameter instanceof Method) { builder.append(((Method) parameter).getName()); } } if (builder.length() != 0) { return "[" + builder.toString() + "]"; } } return ""; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue1777/TestClassSample.java000066400000000000000000000011631475274123300323620ustar00rootroot00000000000000package test.listeners.issue1777; import static org.testng.Assert.assertTrue; import java.lang.reflect.Method; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestClassSample { @BeforeMethod public void beforeMethod(Method method) { if ("test1".equals(method.getName())) { throw new AssertionError("Assertion error from [before]"); } } @Test public void test1() { assertTrue(true); } @Test public void test2() { assertTrue(true); } @AfterMethod public void afterMethod(Method method) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue1952/000077500000000000000000000000001475274123300264425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue1952/TestclassSample.java000066400000000000000000000004041475274123300324120ustar00rootroot00000000000000package test.listeners.issue1952; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; public class TestclassSample { @Test(timeOut = 500) public void testMethod() throws InterruptedException { TimeUnit.SECONDS.sleep(10); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2043/000077500000000000000000000000001475274123300264325ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2043/SampleDataProvider.java000066400000000000000000000005641475274123300330300ustar00rootroot00000000000000package test.listeners.issue2043; import org.testng.annotations.DataProvider; public class SampleDataProvider { @DataProvider public Object[][] dp1master() { return new Object[][] {new Object[] {Object.class}, {Object.class}}; } @DataProvider public Object[][] dp2master() { return new Object[][] {new Object[] {Object.class}, {Object.class}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2043/SampleTestClass.java000066400000000000000000000015221475274123300323440ustar00rootroot00000000000000package test.listeners.issue2043; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestListener; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test.listeners.issue2043.listeners.FailFastListener; @Listeners({SampleTestClass.class}) public class SampleTestClass implements ITestListener, ISuiteListener { @Override public void onStart(ISuite suite) { suite.addListener(new FailFastListener()); } @BeforeClass public void beforeClass() {} @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "dp1master") public void test1(Class clazz) {} @Test(dataProviderClass = SampleDataProvider.class, dataProvider = "dp1master") public void test2(Class clazz) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2043/listeners/000077500000000000000000000000001475274123300304425ustar00rootroot00000000000000FailFastListener.java000066400000000000000000000021451475274123300344270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2043/listenerspackage test.listeners.issue2043.listeners; import java.util.Set; import org.testng.IConfigurationListener; import org.testng.IDataProviderListener; import org.testng.IDataProviderMethod; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.collections.Sets; public class FailFastListener implements IInvokedMethodListener, IConfigurationListener, IDataProviderListener { public static final Set msgs = Sets.newHashSet(); @Override public synchronized void afterInvocation(IInvokedMethod method, ITestResult testResult) { msgs.add(getClass().getSimpleName() + ":afterInvocation"); } @Override public void beforeConfiguration(ITestResult testResult) { msgs.add(getClass().getSimpleName() + ":beforeConfiguration"); } @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { msgs.add(getClass().getSimpleName() + ":beforeDataProviderExecution"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2055/000077500000000000000000000000001475274123300264355ustar00rootroot00000000000000DynamicTestListener.java000066400000000000000000000006401475274123300331530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2055package test.listeners.issue2055; import java.util.List; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.collections.Lists; public class DynamicTestListener implements ITestListener { public static final List MSGS = Lists.newArrayList(); @Override public void onTestStart(ITestResult result) { MSGS.add("Starting " + result.getMethod().getMethodName()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2055/TestClassSample.java000066400000000000000000000007121475274123300323470ustar00rootroot00000000000000package test.listeners.issue2055; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestListener; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(TestClassSample.class) public class TestClassSample implements ITestListener, ISuiteListener { @Override public void onStart(ISuite suite) { suite.addListener(new DynamicTestListener()); } @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2061/000077500000000000000000000000001475274123300264325ustar00rootroot00000000000000DynamicSuiteListener.java000066400000000000000000000004111475274123300333160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2061package test.listeners.issue2061; import org.testng.ISuite; import org.testng.ISuiteListener; public class DynamicSuiteListener implements ISuiteListener { @Override public void onStart(ISuite suite) { suite.addListener(new DynamicTestListener()); } } DynamicTestListener.java000066400000000000000000000002021475274123300331420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2061package test.listeners.issue2061; import org.testng.ITestListener; public class DynamicTestListener implements ITestListener {} ListenerEnabledBaseClass.java000066400000000000000000000006221475274123300340370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2061package test.listeners.issue2061; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestListener; import org.testng.annotations.Listeners; @Listeners(ListenerEnabledBaseClass.class) public class ListenerEnabledBaseClass implements ITestListener, ISuiteListener { @Override public void onStart(ISuite suite) { suite.addListener(new DynamicSuiteListener()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2061/TestClassSample.java000066400000000000000000000002611475274123300323430ustar00rootroot00000000000000package test.listeners.issue2061; import org.testng.annotations.Test; public class TestClassSample extends ListenerEnabledBaseClass { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2220/000077500000000000000000000000001475274123300264275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2220/IssueTest.java000066400000000000000000000025151475274123300312250ustar00rootroot00000000000000package test.listeners.issue2220; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void ensureAnnotatedListenersAreWiredInOnlyOnce() { XmlSuite xmlsuite = createXmlSuite("my_suite"); createXmlTest(xmlsuite, "test_1", TestClass01.class); createXmlTest(xmlsuite, "test_2", TestClass02.class); TestNG testng = create(xmlsuite); testng.run(); List expected = Arrays.asList( "started__test_1", "started_test_method_test.listeners.issue2220.TestClass01.test01", "started_test_method_test.listeners.issue2220.TestClass01.test02", "started_test_method_test.listeners.issue2220.TestClass01.test03", "finished__test_1", "started__test_2", "started_test_method_test.listeners.issue2220.TestClass02.test01", "started_test_method_test.listeners.issue2220.TestClass02.test02", "started_test_method_test.listeners.issue2220.TestClass02.test03", "finished__test_2"); assertThat(Listener1.logs).containsExactlyElementsOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2220/Listener1.java000066400000000000000000000014421475274123300311410ustar00rootroot00000000000000package test.listeners.issue2220; import java.util.LinkedList; import java.util.List; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class Listener1 implements ITestListener { static final List logs = new LinkedList<>(); @Override public void onTestStart(ITestResult result) { logs.add("started_test_method_" + getMethodName(result)); } @Override public void onStart(ITestContext context) { logs.add("started__" + context.getName()); } @Override public void onFinish(ITestContext context) { logs.add("finished__" + context.getName()); } private static String getMethodName(ITestResult result) { return result.getTestClass().getRealClass().getName() + "." + result.getName(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2220/TestClass01.java000066400000000000000000000006211475274123300313370ustar00rootroot00000000000000package test.listeners.issue2220; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(Listener1.class) public class TestClass01 { @BeforeClass public void setup() {} @Test(priority = 1) public void test01() {} @Test(priority = 2) public void test02() {} @Test(priority = 3) public void test03() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2220/TestClass02.java000066400000000000000000000006211475274123300313400ustar00rootroot00000000000000package test.listeners.issue2220; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(Listener1.class) public class TestClass02 { @BeforeClass public void setup() {} @Test(priority = 1) public void test01() {} @Test(priority = 2) public void test02() {} @Test(priority = 3) public void test03() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2328/000077500000000000000000000000001475274123300264405ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2328/ConfigListener.java000066400000000000000000000015441475274123300322220ustar00rootroot00000000000000package test.listeners.issue2328; import java.util.HashMap; import java.util.Map; import org.testng.IConfigurationListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; public class ConfigListener implements IConfigurationListener { private final Map data = new HashMap<>(); public ITestNGMethod getDataFor(String key) { return data.get(key); } @Override public void beforeConfiguration(ITestResult tr, ITestNGMethod tm) { data.put("before", tm); } @Override public void onConfigurationFailure(ITestResult tr, ITestNGMethod tm) { data.put("failed", tm); } @Override public void onConfigurationSkip(ITestResult tr, ITestNGMethod tm) { data.put("skip", tm); } @Override public void onConfigurationSuccess(ITestResult tr, ITestNGMethod tm) { data.put("success", tm); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2328/IssueTest.java000066400000000000000000000017131475274123300312350ustar00rootroot00000000000000package test.listeners.issue2328; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { private static final String TEST_METHOD = "test.listeners.issue2328.SampleWithConfiguration.testMethod"; @Test(description = "GITHUB-2328") public void testIfTestMethodInfoPassedToConfigListeners() { TestNG testng = create(SampleWithConfiguration.class); ConfigListener listener = new ConfigListener(); testng.addListener(listener); testng.run(); assertThat(listener.getDataFor("before").getQualifiedName()).isEqualTo(TEST_METHOD); assertThat(listener.getDataFor("failed").getQualifiedName()).isEqualTo(TEST_METHOD); assertThat(listener.getDataFor("skip").getQualifiedName()).isEqualTo(TEST_METHOD); assertThat(listener.getDataFor("success").getQualifiedName()).isEqualTo(TEST_METHOD); } } SampleWithConfiguration.java000066400000000000000000000007321475274123300340330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2328package test.listeners.issue2328; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SampleWithConfiguration { @BeforeMethod public void passingConfig() {} @BeforeMethod(dependsOnMethods = "passingConfig") public void failingConfig() { throw new RuntimeException("Simulate failure"); } @BeforeMethod(dependsOnMethods = "failingConfig") public void skippingConfig() {} @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2456/000077500000000000000000000000001475274123300264425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2456/IssueTest.java000066400000000000000000000015511475274123300312370ustar00rootroot00000000000000package test.listeners.issue2456; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.internal.ExitCode; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2456") public void testEavesdroppingIntoDataProviderExceptions() { TestNG testng = create(TestClassSample.class); SimpleErrorSniffingListener listener = new SimpleErrorSniffingListener(); testng.addListener(listener); testng.run(); assertThat(listener.getTestMethod().getName()).isEqualTo("sampleTest"); assertThat(listener.getDataProvider().getName()).isEqualTo("getData"); assertThat(listener.getException()).isInstanceOf(TestClassSample.TestCaseFailedException.class); assertThat(testng.getStatus()).isEqualTo(ExitCode.SKIPPED); } } SimpleErrorSniffingListener.java000066400000000000000000000014651475274123300346710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2456package test.listeners.issue2456; import java.lang.reflect.Method; import org.testng.IDataProviderListener; import org.testng.ITestContext; import org.testng.ITestNGMethod; public class SimpleErrorSniffingListener implements IDataProviderListener { private Method testMethod; private Method dataProvider; private Throwable exception; @Override public void onDataProviderFailure(ITestNGMethod method, ITestContext ctx, RuntimeException t) { this.testMethod = method.getConstructorOrMethod().getMethod(); this.dataProvider = method.getDataProviderMethod().getMethod(); this.exception = t.getCause(); } public Method getDataProvider() { return dataProvider; } public Method getTestMethod() { return testMethod; } public Throwable getException() { return exception; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2456/TestClassSample.java000066400000000000000000000007661475274123300323650ustar00rootroot00000000000000package test.listeners.issue2456; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestClassSample { @Test(dataProvider = "dp") public void sampleTest(int i) {} @DataProvider(name = "dp") public Object[][] getData() { throw new TestCaseFailedException("dataprovider failed"); } public static class TestCaseFailedException extends RuntimeException { public TestCaseFailedException(String message) { super(message); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2638/000077500000000000000000000000001475274123300264445ustar00rootroot00000000000000DummyInvokedMethodListener.java000066400000000000000000000016541475274123300345200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2638package test.listeners.issue2638; import java.util.Collections; import java.util.List; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.collections.Maps; public class DummyInvokedMethodListener implements IInvokedMethodListener { private static final Map> methods = Maps.newHashMap(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { String suiteName = testResult.getTestContext().getSuite().getName(); methods .computeIfAbsent(suiteName, k -> Lists.newArrayList()) .add(method.getTestMethod().getQualifiedName()); } public static List getMethods(String suiteName) { return methods.getOrDefault(suiteName, Collections.emptyList()); } public static void reset() { methods.clear(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2638/TestClassASample.java000066400000000000000000000002211475274123300324520ustar00rootroot00000000000000package test.listeners.issue2638; import org.testng.annotations.Test; public class TestClassASample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/issue2638/TestClassBSample.java000066400000000000000000000002211475274123300324530ustar00rootroot00000000000000package test.listeners.issue2638; import org.testng.annotations.Test; public class TestClassBSample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ordering/000077500000000000000000000000001475274123300266025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ordering/Constants.java000066400000000000000000000104631475274123300314250ustar00rootroot00000000000000package test.listeners.ordering; public interface Constants { String IALTERSUITELISTENER_ALTER = "org.testng.IAlterSuiteListener.alter(List suites)"; String IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS = "org.testng.IAnnotationTransformer.transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod)"; String IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS = "org.testng.IAnnotationTransformer.transform(IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod)"; String IANNOTATIONTRANSFORMER_DATAPROVIDER = "org.testng.IAnnotationTransformer.transform(IDataProviderAnnotation annotation, Method method)"; String IANNOTATIONTRANSFORMER_FACTORY = "org.testng.IAnnotationTransformer.transform(IFactoryAnnotation annotation, Method method)"; String METHODINTERCEPTOR_INTERCEPT = "org.testng.IMethodInterceptor.intercept(List methods, ITestContext context)"; String IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION = "org.testng.IExecutionVisualiser.consumeDotDefinition(String dotDefinition)"; String IREPORTER_GENERATE_REPORT = "org.testng.IReporter.generateReport(List xmlSuites, List suites, String outputDirectory)"; String ISUITELISTENER_ON_START = "org.testng.ISuiteListener.onStart()"; String ISUITELISTENER_ON_FINISH = "org.testng.ISuiteListener.onFinish()"; String ITESTLISTENER_ON_START_TEST_METHOD = "org.testng.ITestListener.onTestStart(ITestResult result)"; String ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD = "org.testng.ITestListener.onTestFailure(ITestResult result)"; String ITESTLISTENER_ON_TEST_TIMEOUT_TEST_METHOD = "org.testng.ITestListener.onTestFailedWithTimeout(ITestResult result)"; String ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD = "org.testng.ITestListener.onTestSuccess(ITestResult result)"; String ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD = "org.testng.ITestListener.onTestSkipped(ITestResult result)"; String ITESTLISTENER_ON_START_TEST_TAG = "org.testng.ITestListener.onStart(ITestContext context)"; String ITESTLISTENER_ON_FINISH_TEST_TAG = "org.testng.ITestListener.onFinish(ITestContext context)"; String ICLASSLISTENER_ON_BEFORE_CLASS = "org.testng.IClassListener.onBeforeClass(ITestClass testClass)"; String ICLASSLISTENER_ON_AFTER_CLASS = "org.testng.IClassListener.onAfterClass(ITestClass testClass)"; String IINVOKEDMETHODLISTENER_BEFORE_INVOCATION = "org.testng.IInvokedMethodListener.beforeInvocation(IInvokedMethod method, ITestResult testResult)"; String IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT = "org.testng.IInvokedMethodListener.beforeInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context)"; String IINVOKEDMETHODLISTENER_AFTER_INVOCATION = "org.testng.IInvokedMethodListener.afterInvocation(IInvokedMethod method, ITestResult testResult)"; String IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT = "org.testng.IInvokedMethodListener.afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context)"; String IEXECUTIONLISTENER_ON_EXECUTION_START = "org.testng.IExecutionListener.onExecutionStart()"; String IEXECUTIONLISTENER_ON_EXECUTION_FINISH = "org.testng.IExecutionListener.onExecutionFinish()"; String IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION = "org.testng.IDataProviderListener.beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext)"; String IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION = "org.testng.IDataProviderListener.afterDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext)"; String ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION = "org.testng.IConfigurationListener.beforeConfiguration(ITestResult tr)"; String ICONFIGURATIONLISTENER_ON_CONFIGURATION_SUCCESS = "org.testng.IConfigurationListener.onConfigurationSuccess(ITestResult itr)"; String ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE = "org.testng.IConfigurationListener.onConfigurationFailure(ITestResult itr)"; String ICONFIGURATIONLISTENER_ON_CONFIGURATION_SKIP = "org.testng.IConfigurationListener.onConfigurationSkip(ITestResult itr)"; } ListenerInvocationDefaultBehaviorTest.java000066400000000000000000000535701475274123300370440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import static test.listeners.ordering.Constants.*; import java.util.Arrays; import java.util.List; import org.assertj.core.api.Assertions; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; import test.listeners.issue1952.TestclassSample; public class ListenerInvocationDefaultBehaviorTest extends SimpleBaseTest { // Test methods along with configurations @Test(description = "Test class has only 1 passed config and test method") public void testOrderHasOnlyPassedConfigAndTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_SUCCESS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithPassConfigAndMethod.class); } @Test(description = "Test class has only 1 failed config and skipped test method") public void testOrderHasOnlyFailedConfigAndSkippedTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedConfigAndSkippedTestMethod.class); } @Test(description = "Test class has only 1 failed test method due to a timeout") public void testOrderHasTimedoutTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_TIMEOUT_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, TestclassSample.class); } @Test( description = "Test class has only 1 failed config, 1 skipped config and skipped test method") public void testOrderHasOnlyFailedAndSkippedConfigAndSkippedTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_SKIP, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedAndSkippedConfigAndSkippedTestMethod.class); } // All Data driven scenarios @Test(description = "Test class has only 1 passed test method powered by a data provider") public void testOrderHasOnlyDataDrivenPassedMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_DATAPROVIDER, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION, IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithDataDrivenPassMethod.class); } @Test( description = "Test class has only 1 data provider driven test method with 1 passed and 1 failed iteration.") public void testOrderHasOnlyDataDrivenMethodWithPassedAndFailedIteration() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_DATAPROVIDER, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION, IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithDataDrivenMethodPassAndFailedIterations.class); } // Regular test methods without any configuration methods. @Test(description = "Test class has only 1 passed test method") public void testOrderHasOnlyPassedMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithPassMethod.class); } @Test(description = "Test class has only 1 failed test method") public void testOrderHasOnlyFailedMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethod.class); } @Test(description = "Test class has only 1 failed test method and uses invocation counts") public void testOrderHasOnlyFailedMethodMultipleInvocations() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethodMultipleInvocations.class); } @Test( description = "Test class has only 1 failed test method and uses invocation counts but configured" + "to skip failed invocations") public void testOrderHasOnlyFailedMethodMultipleInvocationsAndSkipFailedInvocations() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethodMultipleInvocations.class, true); } @Test(description = "Test class has passed/failed/skipped test methods") public void testOrderHasPassedFailedSkippedMethods() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithPassFailMethods.class); } @Test(description = "Test class has only 1 failed test method and is powered by factory") public void testOrderHasOnlyFailedMethodPoweredByFactory() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_FACTORY, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassPoweredByFactoryWithFailedMethod.class); } @Test(description = "Test class has only 1 failed test method with retry analyzer") public void testOrderHasOnlyFailedMethodWithRetryMechanism() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethodHasRetryAnalyzer.class, true); } private static void runTest(List expected, Class clazz) { runTest(expected, clazz, false); } private static void runTest(List expected, Class clazz, boolean skipInvocationCount) { TestNG testng = create(clazz); testng.setSkipFailedInvocationCounts(skipInvocationCount); UniversalListener listener = new UniversalListener(); testng.addListener(listener); testng.alwaysRunListeners(true); testng.run(); Assertions.assertThat(listener.getMessages()).containsExactlyElementsOf(expected); } } ListenerInvocationListenerInvocationDisabledBehaviorTest.java000066400000000000000000000543741475274123300427320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import static test.listeners.ordering.Constants.IALTERSUITELISTENER_ALTER; import static test.listeners.ordering.Constants.IANNOTATIONTRANSFORMER_DATAPROVIDER; import static test.listeners.ordering.Constants.IANNOTATIONTRANSFORMER_FACTORY; import static test.listeners.ordering.Constants.IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS; import static test.listeners.ordering.Constants.IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS; import static test.listeners.ordering.Constants.ICLASSLISTENER_ON_AFTER_CLASS; import static test.listeners.ordering.Constants.ICLASSLISTENER_ON_BEFORE_CLASS; import static test.listeners.ordering.Constants.ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION; import static test.listeners.ordering.Constants.ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE; import static test.listeners.ordering.Constants.ICONFIGURATIONLISTENER_ON_CONFIGURATION_SKIP; import static test.listeners.ordering.Constants.ICONFIGURATIONLISTENER_ON_CONFIGURATION_SUCCESS; import static test.listeners.ordering.Constants.IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION; import static test.listeners.ordering.Constants.IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION; import static test.listeners.ordering.Constants.IEXECUTIONLISTENER_ON_EXECUTION_FINISH; import static test.listeners.ordering.Constants.IEXECUTIONLISTENER_ON_EXECUTION_START; import static test.listeners.ordering.Constants.IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION; import static test.listeners.ordering.Constants.IINVOKEDMETHODLISTENER_AFTER_INVOCATION; import static test.listeners.ordering.Constants.IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT; import static test.listeners.ordering.Constants.IINVOKEDMETHODLISTENER_BEFORE_INVOCATION; import static test.listeners.ordering.Constants.IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT; import static test.listeners.ordering.Constants.IREPORTER_GENERATE_REPORT; import static test.listeners.ordering.Constants.ISUITELISTENER_ON_FINISH; import static test.listeners.ordering.Constants.ISUITELISTENER_ON_START; import static test.listeners.ordering.Constants.ITESTLISTENER_ON_FINISH_TEST_TAG; import static test.listeners.ordering.Constants.ITESTLISTENER_ON_START_TEST_METHOD; import static test.listeners.ordering.Constants.ITESTLISTENER_ON_START_TEST_TAG; import static test.listeners.ordering.Constants.ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD; import static test.listeners.ordering.Constants.ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD; import static test.listeners.ordering.Constants.ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD; import static test.listeners.ordering.Constants.METHODINTERCEPTOR_INTERCEPT; import java.util.Arrays; import java.util.List; import org.assertj.core.api.Assertions; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ListenerInvocationListenerInvocationDisabledBehaviorTest extends SimpleBaseTest { // Test methods along with configurations @Test(description = "Test class has only 1 passed config and test method") public void testOrderHasOnlyPassedConfigAndTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_SUCCESS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithPassConfigAndMethod.class); } @Test(description = "Test class has only 1 failed config and skipped test method") public void testOrderHasOnlyFailedConfigAndSkippedTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE, ITESTLISTENER_ON_START_TEST_METHOD, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedConfigAndSkippedTestMethod.class); } @Test( description = "Test class has only 1 failed config, 1 skipped config and skipped test method") public void testOrderHasOnlyFailedAndSkippedConfigAndSkippedTestMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_TRANSFORM_4_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ICONFIGURATIONLISTENER_BEFORE_CONFIGURATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_FAILURE, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ICONFIGURATIONLISTENER_ON_CONFIGURATION_SKIP, ITESTLISTENER_ON_START_TEST_METHOD, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedAndSkippedConfigAndSkippedTestMethod.class); } // All Data driven scenarios @Test(description = "Test class has only 1 passed test method powered by a data provider") public void testOrderHasOnlyDataDrivenPassedMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_DATAPROVIDER, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION, IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithDataDrivenPassMethod.class); } @Test( description = "Test class has only 1 data provider driven test method with 1 passed and 1 failed iteration.") public void testOrderHasOnlyDataDrivenMethodWithPassedAndFailedIteration() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_DATAPROVIDER, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, IDATAPROVIDERLISTENER_BEFORE_DATA_PROVIDER_EXECUTION, IDATAPROVIDERLISTENER_AFTER_DATA_PROVIDER_EXECUTION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithDataDrivenMethodPassAndFailedIterations.class); } // Regular test methods without any configuration methods. @Test(description = "Test class has only 1 passed test method") public void testOrderHasOnlyPassedMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithPassMethod.class); } @Test(description = "Test class has only 1 failed test method") public void testOrderHasOnlyFailedMethod() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethod.class); } @Test(description = "Test class has only 1 failed test method and uses invocation counts") public void testOrderHasOnlyFailedMethodMultipleInvocations() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethodMultipleInvocations.class); } @Test( description = "Test class has only 1 failed test method and uses invocation counts but configured" + "to skip failed invocations") public void testOrderHasOnlyFailedMethodMultipleInvocationsAndSkipFailedInvocations() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethodMultipleInvocations.class, true); } @Test(description = "Test class has passed/failed/skipped test methods") public void testOrderHasPassedFailedSkippedMethods() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SUCCESS_TEST_METHOD, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_START_TEST_METHOD, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithPassFailMethods.class); } @Test(description = "Test class has only 1 failed test method and is powered by factory") public void testOrderHasOnlyFailedMethodPoweredByFactory() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, IANNOTATIONTRANSFORMER_FACTORY, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassPoweredByFactoryWithFailedMethod.class); } @Test(description = "Test class has only 1 failed test method with retry analyzer") public void testOrderHasOnlyFailedMethodWithRetryMechanism() { List expected = Arrays.asList( IEXECUTIONLISTENER_ON_EXECUTION_START, IALTERSUITELISTENER_ALTER, IANNOTATIONTRANSFORMER_TRANSFORM_3_ARGS, ISUITELISTENER_ON_START, ITESTLISTENER_ON_START_TEST_TAG, METHODINTERCEPTOR_INTERCEPT, METHODINTERCEPTOR_INTERCEPT, ICLASSLISTENER_ON_BEFORE_CLASS, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_SKIPPED_TEST_METHOD, ITESTLISTENER_ON_START_TEST_METHOD, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION, IINVOKEDMETHODLISTENER_BEFORE_INVOCATION_WITH_CONTEXT, IINVOKEDMETHODLISTENER_AFTER_INVOCATION, IINVOKEDMETHODLISTENER_AFTER_INVOCATION_WITH_CONTEXT, ITESTLISTENER_ON_TEST_FAILURE_TEST_METHOD, ICLASSLISTENER_ON_AFTER_CLASS, IEXECUTION_VISUALISER_CONSUME_DOT_DEFINITION, ITESTLISTENER_ON_FINISH_TEST_TAG, ISUITELISTENER_ON_FINISH, IREPORTER_GENERATE_REPORT, IEXECUTIONLISTENER_ON_EXECUTION_FINISH); runTest(expected, SimpleTestClassWithFailedMethodHasRetryAnalyzer.class, true); } private static void runTest(List expected, Class clazz) { runTest(expected, clazz, false); } private static void runTest(List expected, Class clazz, boolean skipInvocationCount) { TestNG testng = create(clazz); testng.setSkipFailedInvocationCounts(skipInvocationCount); UniversalListener listener = new UniversalListener(); testng.addListener(listener); testng.alwaysRunListeners(false); testng.run(); Assertions.assertThat(listener.getMessages()).containsExactlyElementsOf(expected); } } SimpleTestClassPoweredByFactoryWithFailedMethod.java000066400000000000000000000007271475274123300407260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class SimpleTestClassPoweredByFactoryWithFailedMethod { @Factory public static Object[] create() { return new Object[] { new SimpleTestClassPoweredByFactoryWithFailedMethod(), new SimpleTestClassPoweredByFactoryWithFailedMethod(), }; } @Test public void testWillFail() { Assert.fail(); } } SimpleTestClassWithDataDrivenMethodPassAndFailedIterations.java000066400000000000000000000006641475274123300430330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SimpleTestClassWithDataDrivenMethodPassAndFailedIterations { @Test(dataProvider = "dp") public void testWillPass(int i) { if (i == 1) { Assert.fail(); } } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } SimpleTestClassWithDataDrivenPassMethod.java000066400000000000000000000005271475274123300372370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SimpleTestClassWithDataDrivenPassMethod { @Test(dataProvider = "dp") public void testWillPass(int i) {} @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } SimpleTestClassWithFailedAndSkippedConfigAndSkippedTestMethod.java000066400000000000000000000006451475274123300434500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SimpleTestClassWithFailedAndSkippedConfigAndSkippedTestMethod { @BeforeClass public void beforeClass() { Assert.fail(); } @BeforeMethod public void beforeMethod() {} @Test public void testWillPass() {} } SimpleTestClassWithFailedConfigAndSkippedTestMethod.java000066400000000000000000000004761475274123300415070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class SimpleTestClassWithFailedConfigAndSkippedTestMethod { @BeforeClass public void beforeClass() { Assert.fail(); } @Test public void testWillPass() {} } SimpleTestClassWithFailedMethod.java000066400000000000000000000003211475274123300355430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.Test; public class SimpleTestClassWithFailedMethod { @Test public void testWillFail() { Assert.fail(); } } SimpleTestClassWithFailedMethodHasRetryAnalyzer.java000066400000000000000000000010001475274123300407260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.Test; public class SimpleTestClassWithFailedMethodHasRetryAnalyzer { @Test(retryAnalyzer = OnceMore.class) public void testWillFail() { Assert.fail(); } public static class OnceMore implements IRetryAnalyzer { private int counter = 1; @Override public boolean retry(ITestResult result) { return counter++ != 2; } } } SimpleTestClassWithFailedMethodMultipleInvocations.java000066400000000000000000000003711475274123300415010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.Test; public class SimpleTestClassWithFailedMethodMultipleInvocations { @Test(invocationCount = 2) public void testWillFail() { Assert.fail(); } } SimpleTestClassWithPassConfigAndMethod.java000066400000000000000000000004011475274123300370350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class SimpleTestClassWithPassConfigAndMethod { @BeforeClass public void beforeClass() {} @Test public void testWillPass() {} } SimpleTestClassWithPassFailMethods.java000066400000000000000000000005111475274123300362450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.Assert; import org.testng.annotations.Test; public class SimpleTestClassWithPassFailMethods { @Test public void testWillPass() {} @Test public void testWillFail() { Assert.fail(); } @Test(dependsOnMethods = "testWillFail") public void testWillSkip() {} } SimpleTestClassWithPassMethod.java000066400000000000000000000002371475274123300352730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/orderingpackage test.listeners.ordering; import org.testng.annotations.Test; public class SimpleTestClassWithPassMethod { @Test public void testWillPass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/listeners/ordering/UniversalListener.java000066400000000000000000000203721475274123300331270ustar00rootroot00000000000000package test.listeners.ordering; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.List; import org.testng.IAlterSuiteListener; import org.testng.IAnnotationTransformer; import org.testng.IClassListener; import org.testng.IConfigurationListener; import org.testng.IDataProviderListener; import org.testng.IDataProviderMethod; import org.testng.IExecutionListener; import org.testng.IExecutionVisualiser; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestClass; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.IListenersAnnotation; import org.testng.annotations.ITestAnnotation; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; public class UniversalListener implements IExecutionListener, IAlterSuiteListener, ISuiteListener, ITestListener, IClassListener, IInvokedMethodListener, IDataProviderListener, IReporter, IExecutionVisualiser, IMethodInterceptor, IAnnotationTransformer, IConfigurationListener { private List messages = Lists.newLinkedList(); public List getMessages() { return messages; } public void onConfigurationSuccess(ITestResult itr) { messages.add("org.testng.IConfigurationListener.onConfigurationSuccess(ITestResult itr)"); } public void onConfigurationFailure(ITestResult itr) { messages.add("org.testng.IConfigurationListener.onConfigurationFailure(ITestResult itr)"); } public void onConfigurationSkip(ITestResult itr) { messages.add("org.testng.IConfigurationListener.onConfigurationSkip(ITestResult itr)"); } public void beforeConfiguration(ITestResult tr) { messages.add("org.testng.IConfigurationListener.beforeConfiguration(ITestResult tr)"); } @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { messages.add( "org.testng.IReporter.generateReport(List xmlSuites, List suites, String outputDirectory)"); } @Override public void beforeDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { messages.add( "org.testng.IDataProviderListener.beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext)"); } @Override public void afterDataProviderExecution( IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { messages.add( "org.testng.IDataProviderListener.afterDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext)"); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { messages.add( "org.testng.IInvokedMethodListener.beforeInvocation(IInvokedMethod method, ITestResult testResult)"); } @Override public void beforeInvocation( IInvokedMethod method, ITestResult testResult, ITestContext context) { messages.add( "org.testng.IInvokedMethodListener.beforeInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context)"); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { messages.add( "org.testng.IInvokedMethodListener.afterInvocation(IInvokedMethod method, ITestResult testResult)"); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) { messages.add( "org.testng.IInvokedMethodListener.afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context)"); } @Override public void onAfterClass(ITestClass testClass) { messages.add("org.testng.IClassListener.onAfterClass(ITestClass testClass)"); } @Override public void onBeforeClass(ITestClass testClass) { messages.add("org.testng.IClassListener.onBeforeClass(ITestClass testClass)"); } @Override public void alter(List suites) { messages.add("org.testng.IAlterSuiteListener.alter(List suites)"); } @Override public void onExecutionStart() { messages.add("org.testng.IExecutionListener.onExecutionStart()"); } @Override public void onExecutionFinish() { messages.add("org.testng.IExecutionListener.onExecutionFinish()"); } @Override public void onStart(ISuite suite) { messages.add("org.testng.ISuiteListener.onStart()"); } @Override public void onFinish(ISuite suite) { messages.add("org.testng.ISuiteListener.onFinish()"); } @Override public void onStart(ITestContext context) { messages.add("org.testng.ITestListener.onStart(ITestContext context)"); } @Override public void onFinish(ITestContext context) { messages.add("org.testng.ITestListener.onFinish(ITestContext context)"); } @Override public void onTestStart(ITestResult result) { messages.add("org.testng.ITestListener.onTestStart(ITestResult result)"); } @Override public void onTestSuccess(ITestResult result) { messages.add("org.testng.ITestListener.onTestSuccess(ITestResult result)"); } @Override public void onTestFailure(ITestResult result) { messages.add("org.testng.ITestListener.onTestFailure(ITestResult result)"); } @Override public void onTestFailedWithTimeout(ITestResult result) { messages.add("org.testng.ITestListener.onTestFailedWithTimeout(ITestResult result)"); } @Override public void onTestSkipped(ITestResult result) { messages.add("org.testng.ITestListener.onTestSkipped(ITestResult result)"); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { messages.add( "org.testng.ITestListener.onTestFailedButWithinSuccessPercentage(ITestResult result)"); } @Override public void consumeDotDefinition(String dotDefinition) { messages.add("org.testng.IExecutionVisualiser.consumeDotDefinition(String dotDefinition)"); } @Override public List intercept(List methods, ITestContext context) { String text = "org.testng.IMethodInterceptor.intercept(List methods, ITestContext context)"; messages.add(text); return methods; } @Override public void transform(IFactoryAnnotation annotation, Method method) { String text = "org.testng.IAnnotationTransformer.transform(IFactoryAnnotation annotation, Method method)"; if (!messages.contains(text)) { messages.add(text); } } @Override public void transform(IListenersAnnotation annotation, Class testClass) { String text = "org.testng.IAnnotationTransformer.transform(IListenersAnnotation annotation, Class testClass)"; if (!messages.contains(text)) { messages.add(text); } } @Override public void transform(IDataProviderAnnotation annotation, Method method) { String text = "org.testng.IAnnotationTransformer.transform(IDataProviderAnnotation annotation, Method method)"; if (!messages.contains(text)) { messages.add(text); } } @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { String text = "org.testng.IAnnotationTransformer.transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod)"; if (!messages.contains(text)) { messages.add(text); } } @Override public void transform( IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { String text = "org.testng.IAnnotationTransformer.transform(IConfigurationAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod)"; if (!messages.contains(text)) { messages.add(text); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/000077500000000000000000000000001475274123300253105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MAnnotation2SampleTest.java000066400000000000000000000074201475274123300324710ustar00rootroot00000000000000package test.mannotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.ITestAnnotation; import org.testng.annotations.Test; import org.testng.internal.IConfiguration; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.IBeforeSuite; public class MAnnotation2SampleTest { private IConfiguration m_configuration = new org.testng.internal.Configuration(); private IAnnotationFinder m_finder; @BeforeClass(enabled = true, groups = "current") public void init() { m_finder = m_configuration.getAnnotationFinder(); } @Test public void verifyTestGroupsInheritance() throws SecurityException, NoSuchMethodException { Map> dataset = new HashMap<>(); dataset.put("groups1", Arrays.asList("method-test3", "child-class-test3", "base-class")); dataset.put("groups2", Arrays.asList("child-class-test3", "base-class")); for (Map.Entry> data : dataset.entrySet()) { Method method = MTest3.class.getMethod(data.getKey()); ITestAnnotation test1 = m_finder.findAnnotation(method, ITestAnnotation.class); List expected = data.getValue(); Assert.assertEqualsNoOrder(expected.toArray(new String[expected.size()]), test1.getGroups()); } } @Test public void verifyTestDependsOnGroupsInheritance() throws SecurityException, NoSuchMethodException { Map> dataset = new HashMap<>(); dataset.put("dependsOnGroups1", Arrays.asList("dog2", "dog1", "dog3")); dataset.put("dependsOnGroups2", Arrays.asList("dog1", "dog3")); for (Map.Entry> data : dataset.entrySet()) { Method method = MTest3.class.getMethod(data.getKey()); ITestAnnotation test1 = m_finder.findAnnotation(method, ITestAnnotation.class); List expected = data.getValue(); Assert.assertEqualsNoOrder( expected.toArray(new String[expected.size()]), test1.getDependsOnGroups()); } } @Test public void verifyTestDependsOnMethodsInheritance() throws SecurityException, NoSuchMethodException { Map> dataset = new HashMap<>(); dataset.put("dependsOnMethods1", Arrays.asList("dom2", "dom3", "dom1")); dataset.put("dependsOnMethods2", Arrays.asList("dom1", "dom3")); for (Map.Entry> data : dataset.entrySet()) { Method method = MTest3.class.getMethod(data.getKey()); ITestAnnotation test1 = m_finder.findAnnotation(method, ITestAnnotation.class); List expected = data.getValue(); Assert.assertEqualsNoOrder( expected.toArray(new String[expected.size()]), test1.getDependsOnMethods()); } } @Test public void verifyConfigurationGroupsInheritance() throws SecurityException, NoSuchMethodException { Method method = MTest3.class.getMethod("beforeSuite"); IConfigurationAnnotation test1 = (IConfigurationAnnotation) m_finder.findAnnotation(method, IBeforeSuite.class); Assert.assertEqualsNoOrder(new String[] {"method-test3"}, test1.getGroups()); } @Test(groups = "current") public void verifyTestEnabledInheritance() throws SecurityException, NoSuchMethodException { String[] methods = new String[] {"enabled1", "enabled2"}; Boolean[] expected = new Boolean[] {false, true}; for (int i = 0; i < methods.length; i++) { Method method = MTest3.class.getMethod(methods[i]); ITestAnnotation test1 = m_finder.findAnnotation(method, ITestAnnotation.class); Assert.assertEquals(test1.getEnabled(), expected[i].booleanValue()); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MAnnotationSampleTest.java000066400000000000000000000127521475274123300324130ustar00rootroot00000000000000package test.mannotation; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.IConfigurationAnnotation; import org.testng.annotations.IDataProviderAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.IParametersAnnotation; import org.testng.annotations.ITestAnnotation; import org.testng.annotations.Test; import org.testng.internal.IConfiguration; import org.testng.internal.annotations.IAfterSuite; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.IBeforeSuite; @Test public class MAnnotationSampleTest { private IConfiguration m_configuration = new org.testng.internal.Configuration(); private IAnnotationFinder m_finder; @BeforeClass public void init() { m_finder = m_configuration.getAnnotationFinder(); } public void verifyTestClassLevel() { // // Tests on MTest1SampleTest // ITestAnnotation test1 = m_finder.findAnnotation(MTest1.class, ITestAnnotation.class); Assert.assertTrue(test1.getEnabled()); Assert.assertEquals(test1.getGroups(), new String[] {"group1", "group2"}); Assert.assertTrue(test1.getAlwaysRun()); Assert.assertEqualsNoOrder( test1.getDependsOnGroups(), new String[] {"dg1", "dg2"}, "depends on groups"); Assert.assertEqualsNoOrder(test1.getDependsOnMethods(), new String[] {"dm1", "dm2"}); Assert.assertEquals(test1.getTimeOut(), 42); Assert.assertEquals(test1.getInvocationCount(), 43); Assert.assertEquals(test1.getSuccessPercentage(), 44); Assert.assertEquals(test1.getThreadPoolSize(), 3); Assert.assertEquals(test1.getDataProvider(), "dp"); Assert.assertEquals(test1.getDescription(), "Class level description"); // // Tests on MTest1SampleTest (test defaults) // ITestAnnotation test2 = m_finder.findAnnotation(MTest2.class, ITestAnnotation.class); // test default for enabled Assert.assertTrue(test2.getEnabled()); Assert.assertFalse(test2.getAlwaysRun()); Assert.assertEquals(test2.getTimeOut(), 0); Assert.assertEquals(test2.getInvocationCount(), 1); Assert.assertEquals(test2.getSuccessPercentage(), 100); Assert.assertEquals(test2.getDataProvider(), ""); } public void verifyTestMethodLevel() throws SecurityException, NoSuchMethodException { // // Tests on MTest1SampleTest // Method method = MTest1.class.getMethod("f"); ITestAnnotation test1 = m_finder.findAnnotation(method, ITestAnnotation.class); Assert.assertTrue(test1.getEnabled()); Assert.assertEqualsNoOrder( test1.getGroups(), new String[] {"group1", "group3", "group4", "group2"}); Assert.assertTrue(test1.getAlwaysRun()); Assert.assertEqualsNoOrder( test1.getDependsOnGroups(), new String[] {"dg1", "dg2", "dg3", "dg4"}); Assert.assertEqualsNoOrder( test1.getDependsOnMethods(), new String[] {"dm1", "dm2", "dm3", "dm4"}); Assert.assertEquals(test1.getTimeOut(), 142); Assert.assertEquals(test1.getInvocationCount(), 143); Assert.assertEquals(test1.getSuccessPercentage(), 61); Assert.assertEquals(test1.getDataProvider(), "dp2"); Assert.assertEquals(test1.getDescription(), "Method description"); Class[] exceptions = test1.getExpectedExceptions(); Assert.assertEquals(exceptions.length, 1); Assert.assertEquals(exceptions[0], NullPointerException.class); } public void verifyDataProvider() throws SecurityException, NoSuchMethodException { Method method = MTest1.class.getMethod("otherConfigurations"); IDataProviderAnnotation dataProvider = m_finder.findAnnotation(method, IDataProviderAnnotation.class); Assert.assertNotNull(dataProvider); Assert.assertEquals(dataProvider.getName(), "dp4"); } public void verifyFactory() throws SecurityException, NoSuchMethodException { Method method = MTest1.class.getMethod("factory"); IFactoryAnnotation factory = m_finder.findAnnotation(method, IFactoryAnnotation.class); Assert.assertNotNull(factory); } public void verifyParameters() throws SecurityException, NoSuchMethodException { Method method = MTest1.class.getMethod("parameters"); IParametersAnnotation parameters = m_finder.findAnnotation(method, IParametersAnnotation.class); Assert.assertNotNull(parameters); Assert.assertEquals(parameters.getValue(), new String[] {"pp1", "pp2", "pp3"}); } public void verifyNewConfigurationBefore() throws SecurityException, NoSuchMethodException { Method method = MTest1.class.getMethod("newBefore"); IConfigurationAnnotation configuration = (IConfigurationAnnotation) m_finder.findAnnotation(method, IBeforeSuite.class); Assert.assertNotNull(configuration); Assert.assertTrue(configuration.getBeforeSuite()); // Default values Assert.assertTrue(configuration.getEnabled()); Assert.assertTrue(configuration.getInheritGroups()); Assert.assertFalse(configuration.getAlwaysRun()); } public void verifyNewConfigurationAfter() throws SecurityException, NoSuchMethodException { Method method = MTest1.class.getMethod("newAfter"); IConfigurationAnnotation configuration = (IConfigurationAnnotation) m_finder.findAnnotation(method, IAfterSuite.class); Assert.assertNotNull(configuration); Assert.assertTrue(configuration.getAfterSuite()); // Default values Assert.assertTrue(configuration.getEnabled()); Assert.assertTrue(configuration.getInheritGroups()); Assert.assertFalse(configuration.getAlwaysRun()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MBase.java000066400000000000000000000003261475274123300271430ustar00rootroot00000000000000package test.mannotation; import org.testng.annotations.Test; @Test(groups = "base-class", dependsOnGroups = "dog3", dependsOnMethods = "dom3", enabled = true) public class MBase { public void baseTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MBaseCapture.java000066400000000000000000000005311475274123300304650ustar00rootroot00000000000000package test.mannotation; import org.testng.annotations.Test; /** * Make sure that if a method is declared in the base class and a child class adds a class-scoped * group to it, that method receives it as well. * * @author cbeust * @date Mar 22, 2006 */ public class MBaseCapture { @Test public void shouldBelongToGroupChild() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MChildCaptureTest.java000066400000000000000000000002461475274123300315010ustar00rootroot00000000000000package test.mannotation; import org.testng.annotations.Test; @Test(groups = "child") public class MChildCaptureTest extends MBaseCapture { public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MTest1.java000066400000000000000000000044061475274123300272740ustar00rootroot00000000000000package test.mannotation; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @Test( enabled = true, groups = {"group1", "group2"}, alwaysRun = true, dependsOnGroups = {"dg1", "dg2"}, dependsOnMethods = {"dm1", "dm2"}, timeOut = 42, invocationCount = 43, successPercentage = 44, threadPoolSize = 3, dataProvider = "dp", description = "Class level description") public class MTest1 { public MTest1() {} @Test( enabled = true, groups = {"group3", "group4"}, alwaysRun = true, dependsOnGroups = {"dg3", "dg4"}, dependsOnMethods = {"dm3", "dm4"}, timeOut = 142, invocationCount = 143, successPercentage = 61, dataProvider = "dp2", description = "Method description", expectedExceptions = NullPointerException.class) public void f() {} @BeforeSuite @BeforeTest @BeforeGroups({"b1", "b2"}) @BeforeClass @BeforeMethod public void before() {} @AfterSuite @AfterTest @AfterGroups({"a1", "a2"}) @AfterClass @AfterMethod public void after() {} @Test( groups = {"ogroup1", "ogroup2"}, dependsOnGroups = {"odg1", "odg2"}, dependsOnMethods = {"odm1", "odm2"}, description = "beforeSuite description", enabled = false, alwaysRun = true, expectedExceptions = {MTest1.class, MTest2.class}) @DataProvider(name = "dp4") public Object[][] otherConfigurations() { return null; } @Factory public void factory() {} @Parameters({"pp1", "pp2", "pp3"}) public void parameters() {} @BeforeSuite @BeforeTest @BeforeGroups @BeforeClass @BeforeMethod public void newBefore() {} @AfterSuite @AfterTest @AfterGroups @AfterClass @AfterMethod public void newAfter() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MTest2.java000066400000000000000000000001601475274123300272660ustar00rootroot00000000000000package test.mannotation; import org.testng.annotations.Test; @Test(alwaysRun = false) public class MTest2 {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/MTest3.java000066400000000000000000000013311475274123300272700ustar00rootroot00000000000000package test.mannotation; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; @Test(groups = "child-class-test3", dependsOnGroups = "dog1", dependsOnMethods = "dom1") public class MTest3 extends MBase { @Test(groups = "method-test3") public void groups1() {} @Test public void groups2() {} @Test(dependsOnGroups = "dog2") public void dependsOnGroups1() {} @Test public void dependsOnGroups2() {} @Test(dependsOnMethods = "dom2") public void dependsOnMethods1() {} @Test public void dependsOnMethods2() {} @Test(enabled = false) public void enabled1() {} @Test public void enabled2() {} @BeforeSuite(groups = "method-test3") public void beforeSuite() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/issue1976/000077500000000000000000000000001475274123300267675ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mannotation/issue1976/IssueTest.java000066400000000000000000000125451475274123300315710ustar00rootroot00000000000000package test.mannotation.issue1976; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Lists; import testhelper.CompiledCode; import testhelper.SimpleCompiler; import testhelper.SourceCode; public class IssueTest extends ClassLoader { private static final File dir = SimpleCompiler.createTempDir(); private static final class MyClassLoader extends ClassLoader { public Class injectByteCode(CompiledCode byteCode) throws ClassNotFoundException { Class clazz = defineClass(byteCode.getName(), byteCode.getByteCode(), 0, byteCode.getByteCode().length); return loadClass(clazz.getName()); } } @Test( dataProvider = "dp", expectedExceptions = TypeNotPresentException.class, description = "GITHUB-1976") public void testMethod(SourceCode... sources) throws IOException, ClassNotFoundException { TestNG tng = new TestNG(false); MyClassLoader classLoader = new MyClassLoader(); tng.addClassLoader(classLoader); List byteCodes = SimpleCompiler.compileSourceCode(sources); List> classes = Lists.newArrayList(); for (CompiledCode byteCode : byteCodes) { if (byteCode.isSkipLoading()) { continue; } classes.add(classLoader.injectByteCode(byteCode)); } tng.setTestClasses(classes.toArray(new Class[0])); tng.run(); Arrays.stream(sources).forEach(sourceCode -> sourceCode.getLocation().delete()); } @DataProvider(name = "dp") public Object[][] getTestData() throws IOException { return new Object[][] { {new SourceCode[] {missingTypeAtMethodLevel(), exception1()}}, {new SourceCode[] {missingTypeAtClassLevel(), exception2()}}, {new SourceCode[] {missingTypeAtConstructor(), dataProvider()}}, // TODO fix test {new SourceCode[]{missingTypeAtListenerAnnotation(), listener()}}, {new SourceCode[] {missingTypeAtBaseClass(), childClass(), exception3()}}, }; } private static SourceCode missingTypeAtMethodLevel() throws IOException { String source = "import org.testng.annotations.Test\n;"; source += "public class Sample1 {\n"; source += " @Test(expectedExceptions = MyFancyException.class)\n"; source += " public void testMethod() {\n"; source += " }\n"; source += "}\n"; return new SourceCode("Sample1", source, dir, false); } private static SourceCode exception1() throws IOException { String source = "public class MyFancyException extends RuntimeException {}"; return new SourceCode("MyFancyException", source, dir, true); } private static SourceCode missingTypeAtClassLevel() throws IOException { String source = "import org.testng.annotations.Test\n;"; source += "@Test(expectedExceptions = AnotherException.class)\n"; source += "public class Sample2 {\n"; source += " public void testMethod() {\n"; source += " }\n"; source += "}\n"; return new SourceCode("Sample2", source, dir, false); } private static SourceCode missingTypeAtBaseClass() throws IOException { String source = "@org.testng.annotations.Test(expectedExceptions = ThirdException.class)\n"; source += "public class MyBaseClass {}\n"; return new SourceCode("MyBaseClass", source, dir, false); } private static SourceCode childClass() throws IOException { String source = "public class ChildClass extends MyBaseClass {\n;"; source += "public void testMethod() {}\n"; source += "}\n"; return new SourceCode("ChildClass", source, dir, false); } private static SourceCode exception2() throws IOException { String source = "public class AnotherException extends RuntimeException {}"; return new SourceCode("AnotherException", source, dir, true); } private static SourceCode exception3() throws IOException { String source = "public class ThirdException extends RuntimeException {}"; return new SourceCode("ThirdException", source, dir, true); } private static SourceCode missingTypeAtConstructor() throws IOException { String source = "import org.testng.annotations.Factory;\n"; source += "public class FactorySample {\n"; source += " @Factory(dataProviderClass = ExampleDP.class)\n"; source += " public FactorySample(Object object) { }\n"; source += "}\n"; return new SourceCode("FactorySample", source, dir, false); } private static SourceCode dataProvider() throws IOException { String source = "import org.testng.annotations.DataProvider;\n"; source += "public class ExampleDP {\n"; source += " @DataProvider\n"; source += " public Object[][] dp() {\n"; source += " return new Object[][] {{}};"; source += " }\n"; source += "}"; return new SourceCode("ExampleDP", source, dir, true); } private static SourceCode missingTypeAtListenerAnnotation() throws IOException { String source = "import org.testng.annotations.Listeners\n"; source += "@Listeners(SampleListener.class)\n"; source += "public class Sample4 {}\n"; return new SourceCode("Sample4", source, dir, false); } private static SourceCode listener() throws IOException { String source = "public class SampleListener implements org.testng.ITestListener {}"; return new SourceCode("SampleListener", source, dir, true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/000077500000000000000000000000001475274123300267035ustar00rootroot00000000000000FastTestsFirstInterceptor.java000066400000000000000000000016121475274123300346360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptorspackage test.methodinterceptors; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.annotations.Test; public class FastTestsFirstInterceptor implements IMethodInterceptor { @Override public List intercept(List methods, ITestContext context) { List result = new ArrayList<>(); for (IMethodInstance m : methods) { Test test = m.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class); Set groups = new HashSet<>(); for (String group : test.groups()) { groups.add(group); } if (groups.contains("fast")) { result.add(0, m); } else { result.add(m); } } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/FooTest.java000066400000000000000000000003241475274123300311300ustar00rootroot00000000000000package test.methodinterceptors; import org.testng.annotations.Test; public class FooTest { @Test(groups = "fast") public void zzzfast() {} @Test public void slow() {} @Test public void a() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/Issue392.java000066400000000000000000000003741475274123300311000ustar00rootroot00000000000000package test.methodinterceptors; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public class Issue392 { @AfterClass public void afterClass() {} @Test public void test1() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/Issue392Test.java000066400000000000000000000024211475274123300317330ustar00rootroot00000000000000package test.methodinterceptors; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import org.testng.*; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class Issue392Test extends SimpleBaseTest { @Test(description = "test for https://github.com/cbeust/testng/issues/392") public void AfterClass_method_should_be_fired_when_IMethodInterceptor_removes_test_methods() { TestNG tng = create(Issue392.class); tng.setMethodInterceptor( new IMethodInterceptor() { @Override public List intercept( List methods, ITestContext context) { List instances = new ArrayList<>(); for (IMethodInstance instance : methods) { if (!instance.getMethod().getMethodName().equals("test1")) { instances.add(instance); } } return instances; } }); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getInvokedMethodNames()).containsExactly("test2", "afterClass"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/Issue521.java000066400000000000000000000003771475274123300310750ustar00rootroot00000000000000package test.methodinterceptors; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class Issue521 { @BeforeClass public void beforeClass() {} @Test public void test1() {} @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/Issue521Test.java000066400000000000000000000024231475274123300317270ustar00rootroot00000000000000package test.methodinterceptors; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import org.testng.*; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class Issue521Test extends SimpleBaseTest { @Test(description = "test for https://github.com/cbeust/testng/issues/521") public void BeforeClass_method_should_be_fired_when_IMethodInterceptor_removes_test_methods() { TestNG tng = create(Issue521.class); tng.setMethodInterceptor( new IMethodInterceptor() { @Override public List intercept( List methods, ITestContext context) { List instances = new ArrayList<>(); for (IMethodInstance instance : methods) { if (!instance.getMethod().getMethodName().equals("test1")) { instances.add(instance); } } return instances; } }); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getInvokedMethodNames()).containsExactly("beforeClass", "test2"); } } LockUpInterceptorSampleTest.java000066400000000000000000000007031475274123300351050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptorspackage test.methodinterceptors; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners({RemoveAMethodInterceptor.class}) public class LockUpInterceptorSampleTest { @Test public void one() { log("one"); } @Test public void two() { log("two"); } @Test public void three() { log("three"); } private static void log(String s) { // System.out.println("[MITest] " + s); } } MethodInterceptorTest.java000066400000000000000000000065151475274123300337750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptorspackage test.methodinterceptors; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.internal.Parser; import org.xml.sax.SAXException; import test.SimpleBaseTest; import test.TestHelper; public class MethodInterceptorTest extends SimpleBaseTest { private String XML = TestHelper.SUITE_XML_HEADER + "" + "" + "" + " " + "" + "" + " " + " " + " " + " " + " " + "" + ""; @Test public void noMethodsShouldRun() { TestNG tng = create(); tng.setTestClasses(new Class[] {FooTest.class}); testNullInterceptor(tng); } private void testNullInterceptor(TestNG tng) { tng.setMethodInterceptor(new NullMethodInterceptor()); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 0); Assert.assertEquals(tla.getFailedTests().size(), 0); Assert.assertEquals(tla.getSkippedTests().size(), 0); } private void testFast(boolean useInterceptor) { TestNG tng = create(); tng.setTestClasses(new Class[] {FooTest.class}); if (useInterceptor) { tng.setMethodInterceptor(new FastTestsFirstInterceptor()); } TestListenerAdapter tla = new TestListenerAdapter(); // tng.setParallel("methods"); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 3); ITestResult first = tla.getPassedTests().get(0); String method = "zzzfast"; if (useInterceptor) { Assert.assertEquals(first.getMethod().getMethodName(), method); } else { Assert.assertNotSame(first.getMethod().getMethodName(), method); } } @Test public void fastShouldRunFirst() { testFast(true /* use interceptor */); } @Test public void fastShouldNotRunFirst() { testFast(false /* don't use interceptor */); } @Test public void nullMethodInterceptorWorksInTestngXml() throws IOException, ParserConfigurationException, SAXException { File f = File.createTempFile("testng-tests-", ""); f.deleteOnExit(); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write(XML); bw.close(); try { List xmlSuites = new Parser(f.getAbsolutePath()).parseToList(); TestNG tng = create(); tng.setXmlSuites(xmlSuites); testNullInterceptor(tng); } catch (Exception ex) { ex.printStackTrace(); } } @Test(timeOut = 1000) public void shouldNotLockUpWithInterceptorThatRemovesMethods() { TestNG tng = create(LockUpInterceptorSampleTest.class); tng.setParallel(XmlSuite.ParallelMode.METHODS); tng.run(); } } NullMethodInterceptor.java000066400000000000000000000006221475274123300337610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptorspackage test.methodinterceptors; import java.util.ArrayList; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; public class NullMethodInterceptor implements IMethodInterceptor { @Override public List intercept(List methods, ITestContext context) { return new ArrayList<>(); } } RemoveAMethodInterceptor.java000066400000000000000000000031451475274123300344100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptorspackage test.methodinterceptors; import java.util.ArrayList; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; /** An interceptor that removes the method called "two". */ public class RemoveAMethodInterceptor implements IMethodInterceptor { @Override public List intercept(List methods, ITestContext context) { List result = new ArrayList<>(); for (IMethodInstance method : methods) { String name = method.getMethod().getMethodName(); if (!name.equals("two")) { result.add(method); } } log(this, methods, result); return result; } public static void log( IMethodInterceptor listener, List input, List output) { StringBuilder msg = new StringBuilder() .append(listener.getClass().getName()) .append(" - Input:") .append(getMethodNames(input)) .append(" ") .append(input.size()) .append(" methods.") .append(" Output:") .append(getMethodNames(output)) .append(" ") .append(output.size()) .append(" methods"); log(msg.toString()); } public static List getMethodNames(List methods) { List names = new ArrayList<>(); for (IMethodInstance m : methods) { names.add(m.getMethod().getMethodName()); } return names; } private static void log(String s) { // System.out.println("[MI2] " + s); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/issue1726/000077500000000000000000000000001475274123300303535ustar00rootroot00000000000000CustomInterceptorTest.java000066400000000000000000000033521475274123300354730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/issue1726package test.methodinterceptors.issue1726; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestNGListener; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class CustomInterceptorTest extends SimpleBaseTest { @Test public void testOrderingWhenInvolvingCustomInterceptors() { XmlSuite suite = createXmlSuite("suite"); suite.setPreserveOrder(false); XmlTest xmlTest = createXmlTest(suite, "test", TestClassSample1.class, TestClassSample2.class); xmlTest.setPreserveOrder(false); TestNG testng = create(suite); testng.addListener(new PriorityInterceptor()); testng.addListener((ITestNGListener) new MethodOrderTracker()); testng.run(); List expected = Arrays.asList( "TestClassSample2.Test3", "TestClassSample1.Test1", "TestClassSample1.Test2", "TestClassSample2.Test4"); assertThat(MethodOrderTracker.ordered).containsExactlyElementsOf(expected); } public static class MethodOrderTracker implements IInvokedMethodListener { static List ordered = new ArrayList<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { String clazz = method.getTestMethod().getRealClass().getSimpleName() + "."; ordered.add(clazz + method.getTestMethod().getMethodName()); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/issue1726/Priority.java000066400000000000000000000005021475274123300330340ustar00rootroot00000000000000package test.methodinterceptors.issue1726; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface Priority { int value() default 0; } PriorityInterceptor.java000066400000000000000000000020121475274123300351720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/issue1726package test.methodinterceptors.issue1726; import java.lang.reflect.Method; import java.util.Comparator; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; public class PriorityInterceptor implements IMethodInterceptor { public List intercept(List methods, ITestContext context) { Comparator comparator = Comparator.comparingInt(PriorityInterceptor::getPriority); methods.sort(comparator); return methods; } private static int getPriority(IMethodInstance mi) { int result = 0; Method method = mi.getMethod().getConstructorOrMethod().getMethod(); Priority a1 = method.getAnnotation(Priority.class); if (a1 != null) { return a1.value(); } Class cls = method.getDeclaringClass(); Priority classPriority = cls.getAnnotation(Priority.class); if (classPriority != null) { result = classPriority.value(); } return result; } } TestClassSample1.java000066400000000000000000000010301475274123300342610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/issue1726package test.methodinterceptors.issue1726; import org.testng.Reporter; import org.testng.annotations.Test; public class TestClassSample1 { @Priority(4) @Test(description = "Test Multiple Day Absence Request flow", groups = "Test") public void Test1() { Reporter.log(getClass().getName() + ".Test1", false); } @Priority(8) @Test( description = "Test Single Day Absence Request Flow", groups = {"Regression", "Test"}) public void Test2() { Reporter.log(getClass().getName() + ".Test2", false); } } TestClassSample2.java000066400000000000000000000010301475274123300342620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/issue1726package test.methodinterceptors.issue1726; import org.testng.Reporter; import org.testng.annotations.Test; public class TestClassSample2 { @Priority(3) @Test(description = "Test Multiple Day Absence Request flow", groups = "Test") public void Test3() { Reporter.log(getClass().getName() + ".Test3", false); } @Priority(9) @Test( description = "Test Single Day Absence Request Flow", groups = {"Regression", "Test"}) public void Test4() { Reporter.log(getClass().getName() + ".Test4", false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptors/000077500000000000000000000000001475274123300332005ustar00rootroot00000000000000FirstInterceptor.java000066400000000000000000000002601475274123300372700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptorspackage test.methodinterceptors.multipleinterceptors; public class FirstInterceptor extends MethodNameFilterInterceptor { public FirstInterceptor() { super("a"); } } FooTest.java000066400000000000000000000003551475274123300353520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptorspackage test.methodinterceptors.multipleinterceptors; import org.testng.annotations.Test; public class FooTest { @Test public void a() {} @Test public void b() {} @Test public void c() {} @Test public void d() {} } MethodNameFilterInterceptor.java000066400000000000000000000021561475274123300413760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptorspackage test.methodinterceptors.multipleinterceptors; import java.util.ArrayList; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.ITestNGMethod; public abstract class MethodNameFilterInterceptor implements IMethodInterceptor { private final String methodName; protected MethodNameFilterInterceptor(String methodName) { this.methodName = methodName; } @Override public List intercept(List methods, ITestContext context) { List result = new ArrayList<>(); for (IMethodInstance methodInstance : methods) { ITestNGMethod method = methodInstance.getMethod(); String name = method.getMethodName(); if (!name.equals(methodName)) { result.add(methodInstance); String currentDescription = method.getDescription(); if (currentDescription == null) { method.setDescription(methodName); } else { method.setDescription(currentDescription + methodName); } } } return result; } } MultipleInterceptorsTest.java000066400000000000000000000024561475274123300410300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptorspackage test.methodinterceptors.multipleinterceptors; import java.util.Collections; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class MultipleInterceptorsTest extends SimpleBaseTest { @Test public void testMultipleInterceptors() { TestNG tng = create(FooTest.class); tng.setMethodInterceptor(new FirstInterceptor()); tng.setMethodInterceptor(new SecondInterceptor()); tng.setMethodInterceptor(new ThirdInterceptor()); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); Assert.assertEquals(tla.getPassedTests().get(0).getName(), "d"); } @Test public void testMultipleInterceptorsWithPreserveOrder() { TestNG tng = create(); tng.setTestSuites( Collections.singletonList( getPathToResource( "/methodinterceptors/multipleinterceptors/multiple-interceptors.xml"))); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().get(0).getMethod().getDescription(), "abc"); } } SecondInterceptor.java000066400000000000000000000002621475274123300374160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptorspackage test.methodinterceptors.multipleinterceptors; public class SecondInterceptor extends MethodNameFilterInterceptor { public SecondInterceptor() { super("b"); } } ThirdInterceptor.java000066400000000000000000000002601475274123300372530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodinterceptors/multipleinterceptorspackage test.methodinterceptors.multipleinterceptors; public class ThirdInterceptor extends MethodNameFilterInterceptor { public ThirdInterceptor() { super("c"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methods/000077500000000000000000000000001475274123300244245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methods/SampleMethod1.java000066400000000000000000000016121475274123300277320ustar00rootroot00000000000000package test.methods; import org.testng.annotations.Test; /** * This class is used to test invocation of methods * * @author cbeust */ public class SampleMethod1 { private static boolean m_ok1 = false; private static boolean m_ok2 = false; private static boolean m_ok3 = true; private static boolean m_ok4 = true; public static void reset() { m_ok1 = false; m_ok2 = false; m_ok3 = true; m_ok4 = true; } @Test(groups = {"sample1"}) public void shouldRun1() { m_ok1 = true; } @Test(groups = {"sample1"}) public void shouldRun2() { m_ok2 = true; } @Test public void shouldNotRun1() { m_ok3 = false; } @Test public void shouldNotRun2() { m_ok4 = false; } public static void verify() { assert m_ok1 && m_ok2 && m_ok3 && m_ok4 : "All booleans should be true: " + m_ok1 + " " + m_ok2 + " " + m_ok3 + " " + m_ok4; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methods/VerifyMethod1.java000066400000000000000000000006111475274123300277530ustar00rootroot00000000000000package test.methods; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; /** * This class verifies that the correct methods were run * * @author cbeust */ @Test(dependsOnGroups = {"sample1"}) public class VerifyMethod1 { @BeforeSuite public void init() { SampleMethod1.reset(); } @Test public void verify() { SampleMethod1.verify(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselection/000077500000000000000000000000001475274123300261475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselection/DollarMethodSample.java000066400000000000000000000004601475274123300325320ustar00rootroot00000000000000package test.methodselection; import org.testng.annotations.Test; public class DollarMethodSample { @Test public void $() {} @Test public void another_test() {} @Test public void another$_test() {} @Test public void another$_test$() {} @Test public void $another$_test$() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselection/MethodSelectionTest.java000066400000000000000000000024741475274123300327470ustar00rootroot00000000000000package test.methodselection; import static org.assertj.core.api.Assertions.assertThat; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class MethodSelectionTest extends SimpleBaseTest { @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] { // Method name {"$", "$"}, {"another_test", "another_test"}, {"another$_test", "another$_test"}, {"another$_test$", "another$_test$"}, // Regex {"another\\$_test\\$$", "another$_test$"}, {"\\$.*", new String[] {"$", "$another$_test$"}}, {"\\$.*$", new String[] {"$", "$another$_test$"}} }; } @Test(dataProvider = "dp") public void testDollarMethodSelection(String methodName, String... expected) { XmlSuite xmlSuite = createXmlSuite("Dollar method Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Dollar method Test"); XmlClass xmlClass = createXmlClass(xmlTest, DollarMethodSample.class); createXmlInclude(xmlClass, methodName); InvokedMethodNameListener listener = run(xmlSuite); assertThat(listener.getInvokedMethodNames()).containsExactly(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/000077500000000000000000000000001475274123300261655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/AllTestsMethodSelector.java000066400000000000000000000010251475274123300334230ustar00rootroot00000000000000package test.methodselectors; import java.util.List; import org.testng.IMethodSelector; import org.testng.IMethodSelectorContext; import org.testng.ITestNGMethod; public class AllTestsMethodSelector implements IMethodSelector { @Override public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) { context.setStopped(true); return true; } @Override public void setTestMethods(List testMethods) { // TODO Auto-generated method stub } } ClassWithManyMethodsSample.java000066400000000000000000000006251475274123300341700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectorspackage test.methodselectors; import org.testng.Assert; import org.testng.annotations.Test; @Test(description = "GITHUB-1507") public class ClassWithManyMethodsSample { public void testa() { Assert.assertTrue(true); } public void testb() { Assert.assertTrue(true); } public void testc() { Assert.assertTrue(true); } public void testd() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/CommandLineTest.java000066400000000000000000000134331475274123300320620ustar00rootroot00000000000000package test.methodselectors; import java.util.List; import org.assertj.core.api.Assertions; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import test.SimpleBaseTest; import testhelper.OutputDirectoryPatch; public class CommandLineTest extends SimpleBaseTest { private final String[] ARG_WITHOUT_CLASSES = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-methodselectors", "", "" }; private final String[] ARG_WITH_GROUPS = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-testclass", "test.methodselectors.SampleTest", "-methodselectors", "", "-groups", "" }; private final String[] ARG_WITHOUT_GROUPS = new String[] { "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-testclass", "test.methodselectors.SampleTest", "-methodselectors", "", }; private TestListenerAdapter tla; @BeforeMethod public void setup() { tla = new TestListenerAdapter(); } @Test public void commandLineNegativePriorityAllGroups() { ARG_WITHOUT_GROUPS[7] = "test.methodselectors.AllTestsMethodSelector:-1"; TestNG.privateMain(ARG_WITHOUT_GROUPS, tla); String[] passed = {"test1", "test2", "test3"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineNegativePriorityGroup2() { ARG_WITHOUT_GROUPS[7] = "test.methodselectors.Test2MethodSelector:-1"; TestNG.privateMain(ARG_WITHOUT_GROUPS, tla); String[] passed = {"test2"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineLessThanPriorityTest1Test() { ARG_WITH_GROUPS[7] = "test.methodselectors.Test2MethodSelector:5"; ARG_WITH_GROUPS[9] = "test1"; TestNG.privateMain(ARG_WITH_GROUPS, tla); String[] passed = {"test1", "test2"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineGreaterThanPriorityTest1Test2() { ARG_WITH_GROUPS[7] = "test.methodselectors.Test2MethodSelector:15"; ARG_WITH_GROUPS[9] = "test1"; TestNG.privateMain(ARG_WITH_GROUPS, tla); String[] passed = {"test2"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineLessThanPriorityAllTests() { ARG_WITH_GROUPS[7] = "test.methodselectors.AllTestsMethodSelector:5"; ARG_WITH_GROUPS[9] = "test1"; TestNG.privateMain(ARG_WITH_GROUPS, tla); String[] passed = {"test1", "test2", "test3"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineMultipleSelectors() { ARG_WITH_GROUPS[7] = "test.methodselectors.NoTestSelector:7,test.methodselectors.Test2MethodSelector:5"; ARG_WITH_GROUPS[9] = "test1"; TestNG.privateMain(ARG_WITH_GROUPS, tla); String[] passed = {"test1", "test2"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineNoTest1Selector() { ARG_WITHOUT_GROUPS[7] = "test.methodselectors.NoTest1MethodSelector:5"; TestNG.privateMain(ARG_WITHOUT_GROUPS, tla); String[] passed = {"test2", "test3"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test public void commandLineTestWithXmlFile() { ARG_WITHOUT_CLASSES[5] = "test.methodselectors.NoTest1MethodSelector:5"; ARG_WITHOUT_CLASSES[6] = getPathToResource("testng-methodselectors.xml"); TestNG.privateMain(ARG_WITHOUT_CLASSES, tla); String[] passed = {"test2", "test3"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test(description = "GITHUB-2407") public void testOverrideExcludedMethodsCommandLineExclusions() { String[] args = new String[] { "src/test/resources/test/methodselectors/sampleTest.xml", "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-excludegroups", "test1", "-overrideincludedmethods" }; TestNG.privateMain(args, tla); // test1 is excluded, so only test2 is left in the passed list String[] passed = {"test2"}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } @Test(description = "GITHUB-2407") public void testOverrideExcludedMethodsSuiteExclusions() { String[] args = new String[] { "src/test/resources/test/methodselectors/sampleTestExclusions.xml", "-log", "0", "-d", OutputDirectoryPatch.getOutputDirectory(), "-overrideincludedmethods" }; TestNG.privateMain(args, tla); String[] passed = {}; String[] failed = {}; verifyTests("Passed", passed, tla.getPassedTests()); verifyTests("Failed", failed, tla.getFailedTests()); } private void verifyTests(String title, String[] expected, List found) { Assertions.assertThat(found.stream().map(ITestResult::getName).toArray(String[]::new)) .describedAs(title) .isEqualTo(expected); } } MethodSelectorInSuiteTest.java000066400000000000000000000046271475274123300340440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectorspackage test.methodselectors; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlClass; import org.testng.xml.XmlMethodSelector; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import testhelper.OutputDirectoryPatch; public class MethodSelectorInSuiteTest extends SimpleBaseTest { private TestListenerAdapter m_tla; @BeforeMethod public void setup() { m_tla = new TestListenerAdapter(); } @Test public void programmaticXmlSuite() { TestNG tng = create(); XmlSuite suite = new XmlSuite(); XmlMethodSelector methodSelector = new XmlMethodSelector(); methodSelector.setName("test.methodselectors.Test2MethodSelector"); methodSelector.setPriority(-1); List methodSelectors = Lists.newArrayList(); methodSelectors.add(methodSelector); suite.setMethodSelectors(methodSelectors); XmlTest test = new XmlTest(suite); XmlClass testClass = new XmlClass(test.methodselectors.SampleTest.class); test.setXmlClasses(Collections.singletonList(testClass)); tng.setXmlSuites(Collections.singletonList(suite)); tng.addListener((ITestNGListener) m_tla); tng.run(); validate(new String[] {"test2"}); } @Test public void xmlXmlSuite() { TestNG tng = create(); tng.setTestSuites(Collections.singletonList(getPathToResource("methodselector-in-xml.xml"))); tng.addListener((ITestNGListener) m_tla); tng.run(); validate(new String[] {"test2"}); } @Test public void fileOnCommandLine() { String[] args = new String[] { "-d", OutputDirectoryPatch.getOutputDirectory(), getPathToResource("methodselector-in-xml.xml") }; TestNG.privateMain(args, m_tla); validate(new String[] {"test2"}); } private void validate(String[] expectPassed) { List passed = m_tla.getPassedTests(); Assert.assertEquals(passed.size(), expectPassed.length); // doing this index based is probably not the best for (int i = 0; i < expectPassed.length; i++) { Assert.assertEquals(passed.get(i).getName(), expectPassed[i]); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/MethodSelectorTest.java000066400000000000000000000061161475274123300326150ustar00rootroot00000000000000package test.methodselectors; import org.testng.Assert; import org.testng.annotations.Test; import test.BaseTest; import test.methodselectors.issue1985.FilteringMethodSelector; import test.methodselectors.issue1985.TestClassSample; public class MethodSelectorTest extends BaseTest { @Test public void negativePriorityAllGroups() { addClass("test.methodselectors.SampleTest"); addMethodSelector("test.methodselectors.AllTestsMethodSelector", -1); run(); String[] passed = { "test1", "test2", "test3", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void negativePriorityGroup2() { addClass("test.methodselectors.SampleTest"); addMethodSelector("test.methodselectors.Test2MethodSelector", -1); run(); String[] passed = { "test2", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void lessThanPriorityTest1Test() { addClass("test.methodselectors.SampleTest"); addIncludedGroup("test1"); addMethodSelector("test.methodselectors.Test2MethodSelector", 5); run(); String[] passed = { "test1", "test2", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void greaterThanPriorityTest1Test2() { addClass("test.methodselectors.SampleTest"); addIncludedGroup("test1"); addMethodSelector("test.methodselectors.Test2MethodSelector", 15); run(); String[] passed = { "test2", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void lessThanPriorityAllTests() { addClass("test.methodselectors.SampleTest"); addIncludedGroup("test1"); addMethodSelector("test.methodselectors.AllTestsMethodSelector", 5); run(); String[] passed = {"test1", "test2", "test3"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test(description = "GITHUB-1507") public void testNoMethodsAreExecutedWithNoMatchFound() { String className = ClassWithManyMethodsSample.class.getName(); addClass(className); addIncludedMethod(className, "cars_sedan"); addIncludedMethod(className, "train_Local"); addIncludedMethod(className, "flight_Domestic"); run(); Assert.assertTrue(getPassedTests().isEmpty()); Assert.assertTrue(getFailedTests().isEmpty()); Assert.assertTrue(getSkippedTests().isEmpty()); } @Test(description = "GITHUB-1985") public void testFilteringOfMethodsWork() { System.setProperty(FilteringMethodSelector.GROUP, "bat"); String className = TestClassSample.class.getName(); addClass(className); addMethodSelector(FilteringMethodSelector.class.getName(), 0); run(); String[] passed = {"batTest"}; verifyTests("Passed", passed, getPassedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/NoTest.java000066400000000000000000000000731475274123300302440ustar00rootroot00000000000000package test.methodselectors; public @interface NoTest {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/NoTest1MethodSelector.java000066400000000000000000000011421475274123300331650ustar00rootroot00000000000000package test.methodselectors; import java.util.List; import org.testng.IMethodSelector; import org.testng.IMethodSelectorContext; import org.testng.ITestNGMethod; public class NoTest1MethodSelector implements IMethodSelector { @Override public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) { for (String group : method.getGroups()) { if (group.equals("test1")) { context.setStopped(true); return false; } } return true; } @Override public void setTestMethods(List testMethods) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/NoTestSelector.java000066400000000000000000000007051475274123300317470ustar00rootroot00000000000000package test.methodselectors; import java.util.List; import org.testng.IMethodSelector; import org.testng.IMethodSelectorContext; import org.testng.ITestNGMethod; public class NoTestSelector implements IMethodSelector { @Override public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) { return false; } @Override public void setTestMethods(List testMethods) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/PrioritySampleTest.java000066400000000000000000000002751475274123300326570ustar00rootroot00000000000000package test.methodselectors; import org.testng.annotations.Test; public class PrioritySampleTest { @Test public void alwaysRun() {} @Test @NoTest public void neverRun() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/PriorityTest.java000066400000000000000000000027351475274123300315200ustar00rootroot00000000000000package test.methodselectors; import java.util.List; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; public class PriorityTest { private void runTest(int priority, String[] passedTests) { TestNG tng = new TestNG(); tng.setTestClasses(new Class[] {PrioritySampleTest.class}); tng.addMethodSelector("test.methodselectors.NoTestSelector", priority); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); List passed = tla.getPassedTests(); Assert.assertEquals(passedTests.length, passed.size()); if (passedTests.length == 1) { String passed0 = passed.get(0).getName(); Assert.assertEquals(passed0, passedTests[0]); } if (passedTests.length == 2) { String passed0 = passed.get(0).getName(); String passed1 = passed.get(1).getName(); Assert.assertTrue(passed0.equals(passedTests[0]) || passed0.equals(passedTests[1])); Assert.assertTrue(passed1.equals(passedTests[0]) || passed1.equals(passedTests[1])); } } // @Test public void negativePriority() { runTest(-5, new String[] {}); } @Test public void lessThanTenPriority() { runTest(5, new String[] {"alwaysRun"}); } // @Test public void greaterThanTenPriority() { runTest(15, new String[] {"alwaysRun", "neverRun"}); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/SampleTest.java000066400000000000000000000004021475274123300311050ustar00rootroot00000000000000package test.methodselectors; import org.testng.annotations.Test; public class SampleTest { @Test(groups = {"test1"}) public void test1() {} @Test(groups = {"test2"}) public void test2() {} @Test(groups = {"test3"}) public void test3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/ScriptNegativeTest.java000066400000000000000000000026261475274123300326250ustar00rootroot00000000000000package test.methodselectors; import java.util.Collections; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlMethodSelector; import org.testng.xml.XmlScript; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class ScriptNegativeTest extends SimpleBaseTest { private static final String LANGUAGE_NAME = "MissingLanguage"; @BeforeMethod public void setup() { System.setProperty("skip.caller.clsLoader", Boolean.TRUE.toString()); } @AfterMethod public void cleanup() { System.setProperty("skip.caller.clsLoader", Boolean.FALSE.toString()); } @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = ".*No engine found for language: " + LANGUAGE_NAME + ".*") public void testNegativeScenario() { XmlSuite suite = createXmlSuite("suite"); XmlTest test = createXmlTest(suite, "test", "test.methodselectors.SampleTest"); XmlScript script = new XmlScript(); script.setLanguage(LANGUAGE_NAME); script.setExpression("expression"); XmlMethodSelector selector = new XmlMethodSelector(); selector.setScript(script); test.setMethodSelectors(Collections.singletonList(selector)); TestNG tng = create(suite); tng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/ScriptTest.java000066400000000000000000000015571475274123300311440ustar00rootroot00000000000000package test.methodselectors; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.BaseTest; public class ScriptTest extends BaseTest { @DataProvider public static Object[][] dataProvider() { return new Object[][] { new Object[] { "beanshell", "groups.\n containsKey \t (\"test1\")", new String[] {"test1"} }, new Object[] { "groovy", "groups.\n containsKey \t (\"test2\")", new String[] {"test2"} }, }; } @Test(dataProvider = "dataProvider") public void onlyGroup1(String language, String expression, String[] passed) { addClass(test.methodselectors.SampleTest.class); setScript(language, expression); run(); String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/Test2MethodSelector.java000066400000000000000000000012141475274123300326710ustar00rootroot00000000000000package test.methodselectors; import java.util.List; import org.testng.IMethodSelector; import org.testng.IMethodSelectorContext; import org.testng.ITestNGMethod; public class Test2MethodSelector implements IMethodSelector { @Override public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) { for (String group : method.getGroups()) { if (group.equals("test2")) { context.setStopped(true); return true; } } return false; } @Override public void setTestMethods(List testMethods) { // TODO Auto-generated method stub } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/issue1985/000077500000000000000000000000001475274123300276445ustar00rootroot00000000000000FilteringMethodSelector.java000066400000000000000000000016371475274123300352240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/issue1985package test.methodselectors.issue1985; import java.util.Arrays; import java.util.List; import org.testng.IMethodSelector; import org.testng.IMethodSelectorContext; import org.testng.ITestNGMethod; public class FilteringMethodSelector implements IMethodSelector { private static final String ALL = "all"; public static final String GROUP = "group"; private String whichGroup; public FilteringMethodSelector() { whichGroup = System.getProperty(GROUP, ALL); } @Override public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) { if (ALL.equalsIgnoreCase(whichGroup)) { return true; } boolean isEqual = Arrays.equals(new String[] {whichGroup}, method.getGroups()); if (context != null) { context.setStopped(true); } return isEqual; } @Override public void setTestMethods(List testMethods) {} } TestClassSample.java000066400000000000000000000005131475274123300334760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/methodselectors/issue1985package test.methodselectors.issue1985; import org.testng.annotations.Test; public class TestClassSample { @Test(groups = {"bat"}) public void batTest() {} @Test(groups = {"p1"}) public void p1Test() {} @Test(groups = {"p2"}) public void p2Test() {} @Test(groups = {"bat", "p3"}) public void batp3Test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mixed/000077500000000000000000000000001475274123300240675ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mixed/JUnit3Test1.java000066400000000000000000000003501475274123300267650ustar00rootroot00000000000000package test.mixed; import junit.framework.TestCase; /** @author lukas */ public class JUnit3Test1 extends TestCase { public JUnit3Test1(String name) { super(name); } public void testA() {} public void testB() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mixed/JUnit4Test1.java000066400000000000000000000002431475274123300267670ustar00rootroot00000000000000package test.mixed; import org.junit.Test; /** @author lukas */ public class JUnit4Test1 { @Test public void atest() {} @Test public void bTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mixed/MixedTest.java000066400000000000000000000037111475274123300266420ustar00rootroot00000000000000package test.mixed; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.BaseTest; import testhelper.OutputDirectoryPatch; /** @author lukas */ public class MixedTest extends BaseTest { @Test public void mixedWithExcludedGroups() { String[] argv = { "-d", OutputDirectoryPatch.getOutputDirectory(), "-log", "0", "-mixed", "-groups", "unit", "-excludegroups", "ignore", "-testclass", "test.mixed.JUnit3Test1,test.mixed.JUnit4Test1,test.mixed.TestNGTest1,test.mixed.TestNGGroups" }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); Assert.assertEquals( tla.getPassedTests().size(), 5); // 2 from junit3test1, 2 from junit4test1, 0 from testngtest1 (no groups), 1 from // testnggroups (1 is included, 1 is excluded) Assert.assertEquals(tla.getFailedTests().size(), 0); } @Test public void mixedClasses() { String[] argv = { "-d", OutputDirectoryPatch.getOutputDirectory(), "-log", "0", "-mixed", "-testclass", "test.mixed.JUnit3Test1,test.mixed.JUnit4Test1,test.mixed.TestNGTest1" }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); Assert.assertEquals(tla.getPassedTests().size(), 6); Assert.assertEquals(tla.getFailedTests().size(), 0); } @Test public void mixedMethods() { String[] argv = { "-d", OutputDirectoryPatch.getOutputDirectory(), "-mixed", "-log", "0", "-methods", "test.mixed.JUnit3Test1.testB,test.mixed.JUnit4Test1.atest,test.mixed.TestNGTest1.tngCustomTest1" }; TestListenerAdapter tla = new TestListenerAdapter(); TestNG.privateMain(argv, tla); Assert.assertEquals(tla.getPassedTests().size(), 3); Assert.assertEquals(tla.getFailedTests().size(), 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mixed/TestNGGroups.java000066400000000000000000000003311475274123300272730ustar00rootroot00000000000000package test.mixed; import org.testng.annotations.Test; @Test(groups = {"unit"}) public class TestNGGroups { @Test public void tngTest1() {} @Test(groups = {"ignore"}) public void tngShouldBeIgnored() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/mixed/TestNGTest1.java000066400000000000000000000002741475274123300270220ustar00rootroot00000000000000package test.mixed; import org.testng.annotations.Test; /** @author lukas */ public class TestNGTest1 { @Test public void tngTest1() {} @Test public void tngCustomTest1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/morten/000077500000000000000000000000001475274123300242655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/morten/SampleTest.java000066400000000000000000000014471475274123300272170ustar00rootroot00000000000000package test.morten; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class SampleTest { private int capacity = 10; private float loadFactor = 0.3f; public class SampleTestTestFactory { public SampleTestTestFactory() {} // CTR necessary ? @Factory public Object[] createInstances() { return new SampleTest[] { new SampleTest(1, 0.1f), new SampleTest(10, 0.5f), }; } } public SampleTest() {} public SampleTest(int capacity, float loadFactor) { System.out.println("CREATING TEST WITH " + capacity); this.capacity = capacity; this.loadFactor = loadFactor; } @Test public void testPut() { // FIXME: This test does nothing // HashMap hashTable = new HashMap(capacity, loadFactor); // ... } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/morten/SampleTestFactory.java000066400000000000000000000004501475274123300305400ustar00rootroot00000000000000package test.morten; import org.testng.annotations.Factory; public class SampleTestFactory { public SampleTestFactory() {} // CTR necessary ? @Factory public Object[] createInstances() { return new SampleTest[] { new SampleTest(1, 0.1f), new SampleTest(10, 0.5f), }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiple/000077500000000000000000000000001475274123300246145ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiple/Test1.java000066400000000000000000000005421475274123300264600ustar00rootroot00000000000000package test.multiple; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; public class Test1 { private static int m_count = 0; @Test public void f1() { assertTrue(m_count < 1, "FAILING"); m_count++; } @AfterTest public void cleanUp() { m_count = 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiple/TestMultiple.java000066400000000000000000000010361475274123300301120ustar00rootroot00000000000000package test.multiple; import org.testng.annotations.Test; import test.BaseTest; public class TestMultiple extends BaseTest { private static final String CLASS_NAME = "test.multiple.ThisFactory"; @Test(groups = {"current"}) public void multiple() { addClass(CLASS_NAME); run(); String[] passed = { "f1", }; String[] failed = { "f1", "f1", "f1", "f1", "f1", "f1", "f1", "f1", "f1", }; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiple/ThisFactory.java000066400000000000000000000005611475274123300277200ustar00rootroot00000000000000package test.multiple; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; /** * This class * * @author cbeust */ public class ThisFactory { @Factory public Object[] create() { List result = new ArrayList(); for (int i = 0; i < 10; i++) { result.add(new Test1()); } return result.toArray(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiplelisteners/000077500000000000000000000000001475274123300265455ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiplelisteners/SimpleReporter.java000066400000000000000000000017121475274123300323650ustar00rootroot00000000000000package test.multiplelisteners; import java.lang.reflect.Field; import java.util.List; import org.testng.IReporter; import org.testng.ISuite; import org.testng.SuiteRunner; import org.testng.TestListenerAdapter; import org.testng.internal.IConfiguration; import org.testng.xml.XmlSuite; import test.listeners.ListenerAssert; public class SimpleReporter implements IReporter { @Override public void generateReport( final List xmlSuites, final List suites, final String outputDirectory) { for (final ISuite iSuite : suites) { try { final Field field = SuiteRunner.class.getDeclaredField("configuration"); field.setAccessible(true); final IConfiguration conf = (IConfiguration) field.get(iSuite); ListenerAssert.assertListenerType( conf.getConfigurationListeners(), TestListenerAdapter.class); } catch (final Exception e) { throw new RuntimeException(e); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiplelisteners/Test1.java000066400000000000000000000002451475274123300304110ustar00rootroot00000000000000package test.multiplelisteners; import org.testng.annotations.Test; @Test public class Test1 { public void test() { // Reporter.log("test1", true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/multiplelisteners/TestMaker.java000066400000000000000000000025651475274123300313170ustar00rootroot00000000000000package test.multiplelisteners; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; public class TestMaker { @Test(description = "Make sure only one listener is created and not 2^3") public void run() { final TestNG tng = new TestNG(); tng.setUseDefaultListeners(false); tng.setListenerClasses(Arrays.asList(TestListenerAdapter.class, SimpleReporter.class)); final List suites = createSuites(); tng.setXmlSuites(suites); tng.run(); // Reporter.log(tng.getSuiteListeners().size() + "", true); // for (final XmlSuite xmlSuite : suites) // { // Reporter.log(xmlSuite.getName() + ": " + xmlSuite.getListeners().size(), true); // } } private List createSuites() { final List ret = Lists.newArrayList(); for (int i = 0; i < 3; i++) { ret.add(createSuite(i)); } return ret; } private XmlSuite createSuite(final int nr) { final XmlSuite suite = new XmlSuite(); suite.setName("Suite_" + nr); new XmlTest(suite).setXmlClasses(Collections.singletonList(new XmlClass(Test1.class))); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/000077500000000000000000000000001475274123300237015ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/BlankNameSample.java000066400000000000000000000004371475274123300275420ustar00rootroot00000000000000package test.name; import org.testng.Assert; import org.testng.ITest; import org.testng.annotations.Test; public class BlankNameSample implements ITest { @Test public void test() { Assert.assertTrue(true); } @Override public String getTestName() { return ""; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/ITestSample.java000066400000000000000000000021201475274123300267310ustar00rootroot00000000000000package test.name; import org.testng.Assert; import org.testng.ITest; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; // From https://stackoverflow.com/q/33404335/4234729 public class ITestSample implements ITest { public ThreadLocal testName = new ThreadLocal<>(); @DataProvider(name = "dp", parallel = true) public Object[][] getTests() { return new Object[][] { new Object[] {"test1"}, new Object[] {"test2"}, new Object[] {"test3"}, new Object[] {"test4"}, new Object[] {"test5"} }; } @Test(dataProvider = "dp") public void run(String testName) { Assert.assertEquals(testName, this.testName.get()); } @BeforeMethod public void init(Object[] testArgs) { testName.set((String) testArgs[0]); } @AfterMethod public void tearDown(Object[] testArgs) { Assert.assertEquals((String) testArgs[0], this.testName.get()); } @Override public String getTestName() { return testName.get(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/NameSample.java000066400000000000000000000003111475274123300265610ustar00rootroot00000000000000package test.name; import org.testng.Assert; import org.testng.annotations.Test; @Test(testName = "NAME") public class NameSample { @Test public void test() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/NameTest.java000066400000000000000000000153361475274123300262740ustar00rootroot00000000000000package test.name; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class NameTest extends SimpleBaseTest { @Test public void itestTest() { TestNG tng = create(SimpleITestSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), "NAME"); Assert.assertEquals(result.getTestName(), "NAME"); } @Test public void itestTestWithXml() { TestNG tng = createTests("suite", SimpleITestSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), "NAME"); Assert.assertEquals(result.getTestName(), "NAME"); } @Test public void testNameTest() { TestNG tng = create(NameSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), "NAME"); Assert.assertEquals(result.getTestName(), "NAME"); } @Test public void testNameTestWithXml() { TestNG tng = createTests("suite", NameSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), "NAME"); Assert.assertEquals(result.getTestName(), "NAME"); } @Test public void noNameTest() { TestNG tng = create(NoNameSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), "test"); Assert.assertNull(result.getTestName()); } @Test public void noNameTestWithXml() { TestNG tng = createTests("suite", NoNameSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), "test"); Assert.assertNull(result.getTestName()); } @Test public void complexITestTest() { TestNG tng = create(ITestSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 5); List testNames = new ArrayList<>(Arrays.asList("test1", "test2", "test3", "test4", "test5")); for (ITestResult testResult : adapter.getPassedTests()) { Assert.assertTrue( testNames.remove(testResult.getName()), "Duplicate test names " + getNames(adapter.getPassedTests())); } Assert.assertEquals(testNames, Collections.emptyList()); } private static List getNames(List results) { List names = new ArrayList<>(results.size()); for (ITestResult result : results) { names.add(result.getName()); } return names; } @Test(description = "GITHUB-922: ITestResult doesn't contain name if a class has @Test") public void testOnClassFromReporter() { TestNG tng = create(TestOnClassSample.class); TestOnClassListener listener = new TestOnClassListener(); tng.addListener(listener); tng.run(); Assert.assertEquals(listener.getNames().size(), 1); Assert.assertEquals(listener.getNames().get(0), "test"); // testName should be ignored if not specified Assert.assertEquals(listener.getTestNames().size(), 1); Assert.assertNull(listener.getTestNames().get(0)); } @Test public void blankNameTest() { TestNG tng = create(BlankNameSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), ""); Assert.assertEquals(result.getTestName(), ""); } @Test public void blankNameTestWithXml() { TestNG tng = createTests("suite", BlankNameSample.class); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener(adapter); tng.run(); Assert.assertTrue(adapter.getFailedTests().isEmpty()); Assert.assertTrue(adapter.getSkippedTests().isEmpty()); Assert.assertEquals(adapter.getPassedTests().size(), 1); ITestResult result = adapter.getPassedTests().get(0); Assert.assertEquals(result.getMethod().getMethodName(), "test"); Assert.assertEquals(result.getName(), ""); Assert.assertEquals(result.getTestName(), ""); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/NoNameSample.java000066400000000000000000000002621475274123300270630ustar00rootroot00000000000000package test.name; import org.testng.Assert; import org.testng.annotations.Test; public class NoNameSample { @Test public void test() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/SimpleITestSample.java000066400000000000000000000004451475274123300301130ustar00rootroot00000000000000package test.name; import org.testng.Assert; import org.testng.ITest; import org.testng.annotations.Test; public class SimpleITestSample implements ITest { @Test public void test() { Assert.assertTrue(true); } @Override public String getTestName() { return "NAME"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/TestOnClassListener.java000066400000000000000000000015171475274123300304600ustar00rootroot00000000000000package test.name; import java.util.ArrayList; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IReporter; import org.testng.ISuite; import org.testng.xml.XmlSuite; public class TestOnClassListener implements IReporter { private final List names = new ArrayList<>(); private final List testNames = new ArrayList<>(); @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { for (ISuite suite : suites) { for (IInvokedMethod method : suite.getAllInvokedMethods()) { names.add(method.getTestResult().getName()); testNames.add(method.getTestResult().getTestName()); } } } public List getNames() { return names; } public List getTestNames() { return testNames; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/TestOnClassSample.java000066400000000000000000000002031475274123300301030ustar00rootroot00000000000000package test.name; import org.testng.annotations.Test; @Test public class TestOnClassSample { @Test public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/github1046/000077500000000000000000000000001475274123300254765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/github1046/LocalTestNameGatherer.java000066400000000000000000000022071475274123300325170ustar00rootroot00000000000000package test.name.github1046; import java.util.List; import java.util.Set; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.collections.Sets; import org.testng.xml.XmlSuite; public class LocalTestNameGatherer implements IReporter { private Set testnames = Sets.newHashSet(); @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { for (ISuite suite : suites) { for (ISuiteResult suiteResult : suite.getResults().values()) { List testResults = Lists.newArrayList(); testResults.addAll(suiteResult.getTestContext().getPassedTests().getAllResults()); testResults.addAll(suiteResult.getTestContext().getFailedTests().getAllResults()); testResults.addAll(suiteResult.getTestContext().getSkippedTests().getAllResults()); for (ITestResult result : testResults) { testnames.add(result.getName()); } } } } public Set getTestnames() { return testnames; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/github1046/TestClassSample.java000066400000000000000000000025031475274123300314100ustar00rootroot00000000000000package test.name.github1046; import static org.testng.Assert.assertNotEquals; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestClassSample implements IHookable { @DataProvider(name = "dp", parallel = true) public Object[][] getTestData() { return new Object[][] {{1}, {2}, {3}, {4}, {5}}; } @Test(dataProvider = "dp") public void testSample1(int num) { assertNotEquals(num, 0); } @Test(dataProvider = "dp") public void testSample2(int num) { assertNotEquals(num, 0); } @Test public void ordinaryTestMethod() {} @Test public void dontChangeName() {} @Override public void run(IHookCallBack callBack, ITestResult testResult) { if (!("dontChangeName".equals(testResult.getMethod().getMethodName()))) { Object param = "999"; Object[] parameters = callBack.getParameters(); if (parameters.length != 0) { param = parameters[0]; } String testName = name(testResult.getMethod().getMethodName(), param); testResult.setTestName(testName); } callBack.runTestMethod(testResult); } private static String name(String prefix, Object count) { return prefix + "_TestNG_TestCase_" + count.toString(); } } TestCustomNamesForTests.java000066400000000000000000000017711475274123300330600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/name/github1046package test.name.github1046; import java.util.Arrays; import java.util.Set; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Sets; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class TestCustomNamesForTests extends SimpleBaseTest { @Test public void testCustomTestNames() { XmlSuite xmlSuite = createXmlSuite("Suite", "Test", TestClassSample.class); TestNG tng = create(xmlSuite); LocalTestNameGatherer reporter = new LocalTestNameGatherer(); tng.addListener(reporter); tng.run(); Set expectedNames = Sets.newHashSet(); for (String method : Arrays.asList("testSample1", "testSample2")) { for (int i = 1; i <= 5; i++) { expectedNames.add(method + "_TestNG_TestCase_" + i); } } expectedNames.add("ordinaryTestMethod_TestNG_TestCase_999"); expectedNames.add("dontChangeName"); Assert.assertEqualsNoOrder(reporter.getTestnames(), expectedNames); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/nested/000077500000000000000000000000001475274123300242435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/nested/GarfTest.java000066400000000000000000000005571475274123300266340ustar00rootroot00000000000000package test.nested; import org.testng.Assert; import org.testng.annotations.Test; import test.nested.foo.AccountTypeEnum; @Test( groups = {"unittest"}, enabled = true) public class GarfTest { @Test() public void testGarf() { AccountTypeEnum foo = AccountTypeEnum.ClearingMember; Assert.assertEquals(foo, AccountTypeEnum.ClearingMember); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/nested/foo/000077500000000000000000000000001475274123300250265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/nested/foo/AccountTypeEnum.java000066400000000000000000000001711475274123300307530ustar00rootroot00000000000000package test.nested.foo; public class AccountTypeEnum { public static final AccountTypeEnum ClearingMember = null; } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/nested2/000077500000000000000000000000001475274123300243255ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/nested2/TmpA.java000066400000000000000000000010021475274123300260220ustar00rootroot00000000000000package test.nested2; import org.testng.annotations.Test; public class TmpA { public static class NestedAWithTest { @Test public void nestedA() {} } public static class NestedAWithoutTest { public NestedAWithoutTest() { throw new RuntimeException("TestNG should not instantiate me"); } public void nestedA() {} } @Test public static class DummyBase {} public static class NestedAWithInheritedTest extends DummyBase { public void nestedWithInheritedTest() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/000077500000000000000000000000001475274123300256175ustar00rootroot00000000000000BadMethodObjectFactoryFactory.java000066400000000000000000000003221475274123300342360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactorypackage test.objectfactory; import org.testng.annotations.ObjectFactory; public class BadMethodObjectFactoryFactory { @ObjectFactory public Object create() { return new LoggingObjectFactory(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/ClassObjectFactory.java000066400000000000000000000007421475274123300322110ustar00rootroot00000000000000package test.objectfactory; import java.lang.reflect.Constructor; import org.testng.ITestObjectFactory; import org.testng.internal.objects.InstanceCreator; public class ClassObjectFactory implements ITestObjectFactory { public T newInstance(Constructor constructor, Object... parameters) { T object = InstanceCreator.newInstance(constructor, parameters); if (object instanceof ISetValue) { ((ISetValue) object).setValue(42); } return object; } } ClassObjectFactorySampleTest.java000066400000000000000000000004761475274123300341400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactorypackage test.objectfactory; import org.testng.Assert; import org.testng.annotations.Test; public class ClassObjectFactorySampleTest implements ISetValue { public static int m_n = 0; @Test public void f() { Assert.assertEquals(m_n, 42); } @Override public void setValue(int i) { m_n = i; } } CombinedTestAndObjectFactorySample.java000066400000000000000000000020501475274123300352240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactorypackage test.objectfactory; import java.lang.reflect.Constructor; import org.testng.Assert; import org.testng.ITestObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.testng.internal.objects.InstanceCreator; public class CombinedTestAndObjectFactorySample implements ITestObjectFactory { private boolean configured = false; @ObjectFactory public ITestObjectFactory create() { return new CombinedTestAndObjectFactorySample(); } @Test public void isConfigured() { Assert.assertTrue(configured, "Should have been configured by object factory"); } @Override public T newInstance(Constructor constructor, Object... params) { try { T o = InstanceCreator.newInstance(constructor, params); if (o instanceof CombinedTestAndObjectFactorySample) { CombinedTestAndObjectFactorySample s = (CombinedTestAndObjectFactorySample) o; s.configured = true; } return o; } catch (Exception e) { throw new RuntimeException(e); } } } CombinedTestAndObjectFactoryTest.java000066400000000000000000000014241475274123300347260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactorypackage test.objectfactory; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class CombinedTestAndObjectFactoryTest extends SimpleBaseTest { @Test void combinedTestAndObjectFactory() { TestNG tng = create(CombinedTestAndObjectFactorySample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).containsExactly("isConfigured"); } } ContextAwareObjectFactoryFactory.java000066400000000000000000000006671475274123300350270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactorypackage test.objectfactory; import org.testng.ITestContext; import org.testng.ITestObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.internal.objects.ObjectFactoryImpl; public class ContextAwareObjectFactoryFactory { public static int invoked; @ObjectFactory public ITestObjectFactory create(ITestContext context) { assert context != null; invoked++; return new ObjectFactoryImpl(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/CustomFactoryTest.java000066400000000000000000000036721475274123300321340ustar00rootroot00000000000000package test.objectfactory; import org.testng.Assert; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class CustomFactoryTest extends SimpleBaseTest { @BeforeMethod public void resetCount() { LoggingObjectFactory.invoked = 0; } @Test public void setFactoryOnTestNG() { TestNG tng = create(SimpleSample.class); tng.setObjectFactory(LoggingObjectFactory.class); tng.run(); Assert.assertEquals(LoggingObjectFactory.invoked, 1); } @Test public void setFactoryOnSuite() { XmlSuite suite = createXmlSuite("objectfactory", "TmpTest", SimpleSample.class); suite.setObjectFactoryClass(LoggingObjectFactory.class); TestNG tng = create(suite); tng.run(); Assert.assertEquals(LoggingObjectFactory.invoked, 1); } @Test(description = "This broke after I made the change to enable AbstractTest") public void setFactoryByAnnotation() { XmlSuite suite = createXmlSuite( "objectfactory", "TmpTest", SimpleSample.class, MyObjectFactoryFactory.class); TestNG tng = create(suite); tng.run(); Assert.assertEquals(LoggingObjectFactory.invoked, 1); } @Test public void factoryReceivesContext() { XmlSuite suite = createXmlSuite( "objectfactory", "TmpTest", SimpleSample.class, ContextAwareObjectFactoryFactory.class); suite.setObjectFactoryClass(LoggingObjectFactory.class); TestNG tng = create(suite); tng.run(); Assert.assertEquals(ContextAwareObjectFactoryFactory.invoked, 1); } @Test(expectedExceptions = TestNGException.class) public void setInvalidMethodFactoryByAnnotation() { XmlSuite suite = createXmlSuite( "objectfactory", "TmpTest", SimpleSample.class, BadMethodObjectFactoryFactory.class); TestNG tng = create(suite); tng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/ISetValue.java000066400000000000000000000001241475274123300303200ustar00rootroot00000000000000package test.objectfactory; public interface ISetValue { void setValue(int i); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/LoggingObjectFactory.java000066400000000000000000000005661475274123300325360ustar00rootroot00000000000000package test.objectfactory; import java.lang.reflect.Constructor; import org.testng.internal.objects.ObjectFactoryImpl; public class LoggingObjectFactory extends ObjectFactoryImpl { public static int invoked; @Override public T newInstance(Constructor constructor, Object... params) { invoked++; return super.newInstance(constructor, params); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/MyObjectFactoryFactory.java000066400000000000000000000003751475274123300330630ustar00rootroot00000000000000package test.objectfactory; import org.testng.ITestObjectFactory; import org.testng.annotations.ObjectFactory; public class MyObjectFactoryFactory { @ObjectFactory public ITestObjectFactory create() { return new LoggingObjectFactory(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/ObjectFactory2Test.java000066400000000000000000000017711475274123300321500ustar00rootroot00000000000000package test.objectfactory; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; /** Test IObjectFactory2, which is an object factory that receives just the Class in parameter. */ public class ObjectFactory2Test extends SimpleBaseTest { private void testFactory(boolean onSuite) { ClassObjectFactorySampleTest.m_n = 0; XmlSuite suite = createXmlSuite("Test IObjectFactory2", "TmpTest", ClassObjectFactorySampleTest.class); TestNG tng = create(suite); if (onSuite) { suite.setObjectFactoryClass(ClassObjectFactory.class); } else { tng.setObjectFactory(ClassObjectFactory.class); } tng.run(); Assert.assertEquals(ClassObjectFactorySampleTest.m_n, 42); } @Test public void factoryOnSuiteShouldWork() { testFactory(true /* on suite object */); } @Test public void factoryOnTestNGShouldWork() { testFactory(false /* on TestNG object */); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/ObjectFactoryTest.java000066400000000000000000000053701475274123300320650ustar00rootroot00000000000000package test.objectfactory; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; import test.objectfactory.github1131.EmptyConstructorSample; import test.objectfactory.github1131.IntConstructorSample; import test.objectfactory.github1131.MyObjectFactory; import test.objectfactory.github1131.StringConstructorSample; import test.objectfactory.github1827.GitHub1827Sample; import test.objectfactory.issue2676.LocalSuiteAlteringListener; import test.objectfactory.issue2676.LoggingObjectFactorySample; import test.objectfactory.issue2676.TestClassSample; public class ObjectFactoryTest extends SimpleBaseTest { @Test(description = "GITHUB-2676") public void ensureObjectFactoryIsInvokedWhenAddedViaListeners() { TestNG testng = create(TestClassSample.class); testng.addListener(new LocalSuiteAlteringListener()); testng.run(); assertThat(LoggingObjectFactorySample.wasInvoked).isTrue(); } @Test( expectedExceptions = TestNGException.class, expectedExceptionsMessageRegExp = ".*Check to make sure it can be instantiated", description = "GITHUB-1827") public void ensureExceptionThrownWhenNoSuitableConstructorFound() { TestNG testng = create(GitHub1827Sample.class); testng.run(); } @Test(dataProvider = "dp", description = "GITHUB-1131") public void factoryWithEmptyConstructorShouldWork(boolean bool) { testFactory(bool, EmptyConstructorSample.class); assertThat(MyObjectFactory.allParams).containsExactly(new Object[] {}, new Object[] {}); } @Test(dataProvider = "dp", description = "GITHUB-1131") public void factoryWithIntConstructorShouldWork(boolean bool) { testFactory(bool, IntConstructorSample.class); assertThat(MyObjectFactory.allParams).containsExactly(new Object[] {1}, new Object[] {2}); } @Test(dataProvider = "dp", description = "GITHUB-1131") public void factoryWithStringConstructorShouldWork(boolean bool) { testFactory(bool, StringConstructorSample.class); assertThat(MyObjectFactory.allParams) .containsExactly(new Object[] {"foo"}, new Object[] {"bar"}); } private void testFactory(boolean onSuite, Class sample) { MyObjectFactory.allParams.clear(); XmlSuite suite = createXmlSuite("Test IObjectFactory2", "TmpTest", sample); TestNG tng = create(suite); if (onSuite) { suite.setObjectFactoryClass(MyObjectFactory.class); } else { tng.setObjectFactory(MyObjectFactory.class); } tng.run(); } @DataProvider public static Object[][] dp() { return new Object[][] {new Object[] {true}, new Object[] {false}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/SimpleSample.java000066400000000000000000000002021475274123300310470ustar00rootroot00000000000000package test.objectfactory; import org.testng.annotations.Test; public class SimpleSample { @Test public void dummy() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1131/000077500000000000000000000000001475274123300274075ustar00rootroot00000000000000EmptyConstructorSample.java000066400000000000000000000007501475274123300347030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1131package test.objectfactory.github1131; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class EmptyConstructorSample { public static int count = 0; @Factory(dataProvider = "dataProvider") public EmptyConstructorSample() { count++; } @Test public void test() {} @DataProvider public static Object[][] dataProvider() { return new Object[][] {new Object[] {}, new Object[] {}}; } } IntConstructorSample.java000066400000000000000000000011351475274123300343350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1131package test.objectfactory.github1131; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class IntConstructorSample { public static final List parameters = new ArrayList<>(); @Factory(dataProvider = "dataProvider") public IntConstructorSample(int parameter) { parameters.add(parameter); } @Test public void test() {} @DataProvider public static Object[][] dataProvider() { return new Object[][] {new Object[] {1}, new Object[] {2}}; } } MyObjectFactory.java000066400000000000000000000012311475274123300332340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1131package test.objectfactory.github1131; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.testng.ITestObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.internal.objects.ObjectFactoryImpl; public class MyObjectFactory extends ObjectFactoryImpl { public static final List allParams = new ArrayList<>(); @Override public T newInstance(Constructor constructor, Object... params) { allParams.add(params); return super.newInstance(constructor, params); } @ObjectFactory public ITestObjectFactory newInstance() { return new MyObjectFactory(); } } StringConstructorSample.java000066400000000000000000000011551475274123300350530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1131package test.objectfactory.github1131; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class StringConstructorSample { public static final List parameters = new ArrayList<>(); @Factory(dataProvider = "dataProvider") public StringConstructorSample(String parameter) { parameters.add(parameter); } @Test public void test() {} @DataProvider public static Object[][] dataProvider() { return new Object[][] {new Object[] {"foo"}, new Object[] {"bar"}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1827/000077500000000000000000000000001475274123300274235ustar00rootroot00000000000000GitHub1827Sample.java000066400000000000000000000004761475274123300330640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/github1827package test.objectfactory.github1827; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; public class GitHub1827Sample { private final int value; public GitHub1827Sample(int value) { this.value = value; } @Test public void test() { assertEquals(value, 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/issue2676/000077500000000000000000000000001475274123300272745ustar00rootroot00000000000000LocalSuiteAlteringListener.java000066400000000000000000000005511475274123300353210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/issue2676package test.objectfactory.issue2676; import java.util.List; import org.testng.IAlterSuiteListener; import org.testng.xml.XmlSuite; public class LocalSuiteAlteringListener implements IAlterSuiteListener { @Override public void alter(List suites) { suites.forEach(each -> each.setObjectFactoryClass(LoggingObjectFactorySample.class)); } } LoggingObjectFactorySample.java000066400000000000000000000007271475274123300352750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/issue2676package test.objectfactory.issue2676; import java.lang.reflect.Constructor; import org.testng.ITestObjectFactory; import org.testng.internal.objects.InstanceCreator; public class LoggingObjectFactorySample implements ITestObjectFactory { public static boolean wasInvoked = false; @Override public T newInstance(Constructor constructor, Object... parameters) { wasInvoked = true; return InstanceCreator.newInstance(constructor, parameters); } } TestClassSample.java000066400000000000000000000002321475274123300331240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/objectfactory/issue2676package test.objectfactory.issue2676; import org.testng.annotations.Test; public class TestClassSample { @Test public void sampleTestMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/order/000077500000000000000000000000001475274123300240745ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/order/OrderTest.java000066400000000000000000000021271475274123300266540ustar00rootroot00000000000000package test.order; import static org.assertj.core.api.Assertions.assertThat; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.order.github288.Actual1Sample; import test.order.github288.Actual2Sample; public class OrderTest extends SimpleBaseTest { @Test(description = "GITHUB-288") public void interleavingMethodsInDifferentClasses() { InvokedMethodNameListener listener = run(Actual1Sample.class, Actual2Sample.class); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .containsExactly( "beforeClass", "test1", // "test3", // The result is not exactly the one from #288 (prior 6.8) // but it respects the class separation "test4(one)", "test4(two)", "test4(three)", "test4(four)", "test3", "afterClass", "beforeClass", "test2", "afterClass"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/order/github288/000077500000000000000000000000001475274123300256205ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/order/github288/Actual1Sample.java000066400000000000000000000010141475274123300311130ustar00rootroot00000000000000package test.order.github288; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Actual1Sample extends BaseSample { @DataProvider public Object[][] parameters() { return new Object[][] { new Object[] {"one"}, new Object[] {"two"}, new Object[] {"three"}, new Object[] {"four"} }; } @Test public void test1() {} @Test(dependsOnMethods = "test1") public void test3() {} @Test(dataProvider = "parameters") public void test4(String parameter) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/order/github288/Actual2Sample.java000066400000000000000000000002301475274123300311130ustar00rootroot00000000000000package test.order.github288; import org.testng.annotations.Test; public class Actual2Sample extends BaseSample { @Test public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/order/github288/BaseSample.java000066400000000000000000000004051475274123300304760ustar00rootroot00000000000000package test.order.github288; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class BaseSample { @BeforeClass protected void beforeClass() {} @AfterClass(alwaysRun = true) protected void afterClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/override/000077500000000000000000000000001475274123300246005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/override/OverrideSampleTest.java000066400000000000000000000004051475274123300312230ustar00rootroot00000000000000package test.override; import org.testng.annotations.Test; public class OverrideSampleTest { @Test(groups = "goodGroup") public void good() {} @Test(groups = "badGroup") public void bad() { throw new RuntimeException("Should not happen"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/override/OverrideTest.java000066400000000000000000000040561475274123300300670ustar00rootroot00000000000000package test.override; import java.io.File; import java.io.IOException; import java.util.Collections; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.reporters.Files; import test.SimpleBaseTest; import test.TestHelper; /** * Verify that command line switches override parameters in testng.xml. * * @author Cedric Beust */ public class OverrideTest extends SimpleBaseTest { private static File createTempFile(String content) { try { // Create temp file. File result = File.createTempFile("testng-tmp", ""); // Delete temp file when program exits. result.deleteOnExit(); Files.writeFile(content, result); return result; } catch (IOException e) { throw new TestNGException(e); } } private void runTest(String include, String exclude) { File f = createTempFile( TestHelper.SUITE_XML_HEADER + "" + " " + " " + " " + " " + " " + ""); TestNG tng = create(); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); if (include != null) tng.setGroups(include); if (exclude != null) tng.setExcludedGroups(exclude); tng.setTestSuites(Collections.singletonList(f.getAbsolutePath())); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } @Test(description = "Override -groups") public void overrideIncludeShouldWork() { runTest("goodGroup", null); } @Test(description = "Override -excludegroups") public void overrideExcludeShouldWork() { runTest(null, "badGroup"); } @Test(description = "Override -groups and -excludegroups") public void overrideIncludeAndExcludeShouldWork() { runTest("goodGroup", "badGroup"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/000077500000000000000000000000001475274123300251245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/BeforeWithParameterSample.java000066400000000000000000000013201475274123300330240ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class BeforeWithParameterSample { @BeforeMethod @Parameters("parameter") public static void beforeMethod(String parameter) { Assert.assertEquals(parameter, "parameter value"); } @DataProvider(name = "dataProvider") public static Object[][] dataProvider() { return new Object[][] {{"abc", "def"}}; } @Test(dataProvider = "dataProvider") public static void testExample(String a, String b) { Assert.assertEquals(a, "abc"); Assert.assertEquals(b, "def"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/EnumParameterSample.java000066400000000000000000000005271475274123300317020ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class EnumParameterSample { public enum MyEnum { VALUE_1, VALUE_2 } @Test @Parameters("parameter") public void testMethod(MyEnum parameter) { Assert.assertNotNull(parameter); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/InheritFromSuiteChild1.java000066400000000000000000000012321475274123300322520ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * Checks to see if the parameters from parent suite are passed onto the child suite (referred by * ) */ public class InheritFromSuiteChild1 { @Test @Parameters({"parameter1", "parameter2", "parameter3", "parameter4"}) public void inheritedParameter(String p1, String p2, @Optional("foobar") String p3, String p4) { Assert.assertEquals(p1, "p1"); Assert.assertEquals(p2, "c1p2"); Assert.assertEquals(p3, "foobar"); Assert.assertEquals(p4, "c1p4"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/InheritFromSuiteChild2.java000066400000000000000000000012231475274123300322530ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * Checks to see if the parameters from parent suite are passed onto the child suite (referred by * ) */ public class InheritFromSuiteChild2 { @Test @Parameters({"parameter1", "parameter2", "parameter3", "parameter4"}) public void inheritedParameter(String p1, String p2, String p3, @Optional("abc") String p4) { Assert.assertEquals(p1, "p1"); Assert.assertEquals(p2, "c2p2"); Assert.assertEquals(p3, "c2p3"); Assert.assertEquals(p4, "abc"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/InheritFromSuiteChild3.java000066400000000000000000000011331475274123300322540ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * Checks to see if the parameters from parent suite are passed onto the child suite (referred by * ) */ public class InheritFromSuiteChild3 { @Test @Parameters({"parameter1", "parameter2", "parameter3", "parameter4"}) public void inheritedParameter(String p1, String p2, String p3, String p4) { Assert.assertEquals(p1, "p1"); Assert.assertEquals(p2, "c3p2"); Assert.assertEquals(p3, "c2p3"); Assert.assertEquals(p4, "c3p4"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/Issue1061Sample.java000066400000000000000000000014701475274123300305330ustar00rootroot00000000000000package test.parameters; import org.testng.ITestResult; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class Issue1061Sample { private final long timeout; private final long waitTime; @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {1_000, 2_000}, new Object[] {3_000, 6_000} }; } @Factory(dataProvider = "dp") public Issue1061Sample(long timeout, long waitTime) { this.timeout = timeout; this.waitTime = waitTime; } @BeforeMethod public void setup(ITestResult result) { result.getMethod().setTimeOut(timeout); } @Test public void test() throws InterruptedException { Thread.sleep(waitTime); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/Issue1554TestClassSample.java000066400000000000000000000011041475274123300323620ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class Issue1554TestClassSample { private String browser; private ITestContext context; @Parameters({"browser"}) @BeforeTest public void setUpTest(String browser, ITestContext context) { this.browser = browser; this.context = context; } @Test() public void aTest() { Assert.assertNotNull(browser); Assert.assertNotNull(context); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/OptionalParameterTest.java000066400000000000000000000006201475274123300322530ustar00rootroot00000000000000package test.parameters; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class OptionalParameterTest { @Parameters("optional") public OptionalParameterTest(@Optional String optional) {} @Test(description = "GITHUB-564") public void testWithParameterOnlyOptionalAnnotation(@Optional String unUsedParameter) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/Override1Sample.java000066400000000000000000000011101475274123300307620ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @Test public class Override1Sample { @Parameters({"InheritedFromSuite", "InheritedFromTest", "InheritedFromClass"}) public void g(String suite, String test, String cls) { Assert.assertEquals(suite, "InheritedFromSuite"); Assert.assertEquals(test, "InheritedFromTest"); Assert.assertEquals(cls, "InheritedFromClass"); } public void h() {} @Parameters("a") public void f(String p) { Assert.assertEquals(p, "Correct"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/ParamInheritanceTest.java000066400000000000000000000042721475274123300320460ustar00rootroot00000000000000package test.parameters; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ParamInheritanceTest extends SimpleBaseTest { @Test( description = "When verbose is set to >1, TNG prints test results on CLI which are printed " + "using SuiteResultCounts.calculateResultCounts(). This method has been throwing NPE " + "because it's unable to find SuiteRunner in HashMap, because the list of parameters in " + "SuiteRunner changed" + " during execution. This test makes sure we dont run into any NPEs") public void noNPEInCountingResults() { TestNG tng = create(); tng.setTestSuites(Arrays.asList(getPathToResource("param-inheritance/parent-suite.xml"))); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); OutputStream os = new ByteArrayOutputStream(); PrintStream out = System.out; PrintStream err = System.err; try { /* * Changing system print streams so that exception or results stmt is not logged * while running test (avoid confusing person running tests) */ System.setOut(new PrintStream(os)); System.setErr(new PrintStream(os)); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } finally { try { os.close(); } catch (IOException e) { // no need to handle this } System.setOut(out); System.setErr(err); } } @Test(description = "Checks to make sure parameters are inherited and overridden properly") public void parameterInheritanceAndOverriding() { TestNG tng = create(); tng.setTestSuites(Arrays.asList(getPathToResource("parametertest/parent-suite.xml"))); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 3); } } ParameterInjectAndOptionSample.java000066400000000000000000000013541475274123300337460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameterspackage test.parameters; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.testng.xml.XmlTest; public class ParameterInjectAndOptionSample { @BeforeSuite @Parameters({"beforesuitedata"}) public void beforeSuite( ITestContext context, @Optional("optionalbeforesuitedata") String beforesuitedata) { Assert.assertEquals(beforesuitedata, "optionalbeforesuitedata"); } @Test @Parameters({"testdata"}) public void test(XmlTest xmlTest, @Optional("optionaltestdata") String testdata) { Assert.assertEquals(testdata, "optionaltestdata"); } } ParameterInjectAndOptionTest.java000066400000000000000000000010561475274123300334430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameterspackage test.parameters; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ParameterInjectAndOptionTest extends SimpleBaseTest { @Test public void test() { TestNG tng = create(ParameterInjectAndOptionSample.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/ParameterOverrideTest.java000066400000000000000000000041161475274123300322510ustar00rootroot00000000000000package test.parameters; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class ParameterOverrideTest extends SimpleBaseTest { enum Status { PASS_TEST, PASS_CLASS, PASS_INCLUDE } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {"testOverrideSuite", Status.PASS_TEST}, new Object[] {"classOverrideSuite", Status.PASS_CLASS}, new Object[] {"includeOverrideClass", Status.PASS_INCLUDE}, }; } @Test(dataProvider = "dp") public void testOverrideParameter(String name, Status status) { XmlSuite suite = createXmlSuite("suite"); suite.getParameters().put("a", "Incorrect"); suite.getParameters().put("InheritedFromSuite", "InheritedFromSuite"); XmlTest test = createXmlTest(suite, "test"); test.getLocalParameters().put("InheritedFromTest", "InheritedFromTest"); XmlClass clazz = createXmlClass(test, Override1Sample.class); clazz.getLocalParameters().put("InheritedFromClass", "InheritedFromClass"); XmlInclude includeF = createXmlInclude(clazz, "f"); XmlInclude includeG = createXmlInclude(clazz, "g"); switch (status) { case PASS_TEST: test.getLocalParameters().put("a", "Correct"); break; case PASS_CLASS: clazz.getLocalParameters().put("a", "Correct"); break; case PASS_INCLUDE: includeF.getLocalParameters().put("a", "Correct"); break; } TestNG tng = create(suite); InvokedMethodNameListener tla = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) tla); tng.run(); assertThat(tla.getSucceedMethodNames()) .containsExactly( "f(Correct)", "g(InheritedFromSuite,InheritedFromTest,InheritedFromClass)"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/ParameterSample.java000066400000000000000000000012461475274123300310540ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ParameterSample { @Parameters({"first-name"}) @BeforeMethod public void beforeTest(String firstName) { Assert.assertEquals(firstName, "Cedric"); } @Parameters({"first-name"}) @Test(groups = {"singleString"}) public void testSingleString(String firstName) { Assert.assertEquals(firstName, "Cedric"); } @Parameters({"this parameter doesn't exist"}) @Test public void testNonExistentParameter(@Optional String foo) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/ParameterTest.java000066400000000000000000000113621475274123300305520ustar00rootroot00000000000000package test.parameters; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class ParameterTest extends SimpleBaseTest { @Test public void stringSingle() { XmlSuite suite = createXmlSuite("stringSingle"); XmlTest test = createXmlTest(suite, "Before with parameter sample", ParameterSample.class); test.addParameter("first-name", "Cedric"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .containsExactly( "beforeTest(Cedric)", "testNonExistentParameter(null)", "beforeTest(Cedric)", "testSingleString(Cedric)"); } @Test public void beforeMethodWithParameters() { XmlSuite suite = createXmlSuite("beforeMethodWithParameters"); XmlTest test = createXmlTest(suite, "Before with parameter sample", BeforeWithParameterSample.class); test.addParameter("parameter", "parameter value"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()) .containsExactly("beforeMethod(parameter value)", "testExample(abc,def)"); } @Test public void enumParameters() { XmlSuite suite = createXmlSuite("enumParameters"); XmlTest test = createXmlTest(suite, "Enum parameter sample", EnumParameterSample.class); test.addParameter("parameter", "VALUE_1"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).containsExactly("testMethod(VALUE_1)"); } @Test(description = "GITHUB-1105: Test skipped instead failed if incorrect enum value") public void invalidEnumParameters() { XmlSuite suite = createXmlSuite("enumParameters"); XmlTest test = createXmlTest(suite, "Enum parameter sample", EnumParameterSample.class); test.addParameter("parameter", "INVALID_VALUE"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getFailedBeforeInvocationMethodNames()).containsExactly("testMethod"); Throwable exception = listener.getResult("testMethod").getThrowable(); assertThat(exception) .isInstanceOf(TestNGException.class) .hasCauseInstanceOf(IllegalArgumentException.class); } @Test(description = "GITHUB-1061") public void testNativeInjection() { TestNG testng = create(Issue1061Sample.class); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); assertThat(listener.getFailedTests().size()).isEqualTo(2); String[] expectedMsgs = new String[] { "Method test.parameters.Issue1061Sample.test() didn't finish within the time-out 1000", "Method test.parameters.Issue1061Sample.test() didn't finish within the time-out 3000" }; List actualMsgs = Lists.newArrayList(); for (ITestResult result : listener.getFailedTests()) { actualMsgs.add(result.getThrowable().getMessage()); } assertThat(actualMsgs).containsExactlyInAnyOrder(expectedMsgs); } @Test(description = "GITHUB-1554") public void testNativeInjectionAndParamsInjection() { XmlSuite suite = createXmlSuite("suite"); XmlTest test = createXmlTest(suite, "test", Issue1554TestClassSample.class); Map params = new HashMap<>(); params.put("browser", "chrome"); test.setParameters(params); TestNG testng = create(suite); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); assertThat(listener.getPassedTests().isEmpty()).isFalse(); } } ParametersPackageLevelMethodTest.java000066400000000000000000000011151475274123300342560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameterspackage test.parameters; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.internal.ParametersTest; import test.SimpleBaseTest; public class ParametersPackageLevelMethodTest extends SimpleBaseTest { @Test public void test() { TestNG tng = create(ParametersTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/Sample.java000066400000000000000000000002331475274123300272060ustar00rootroot00000000000000package test.parameters; import org.testng.annotations.Test; public class Sample { @Test public void foo() { // purposefully does nothing } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/Shadow1Sample.java000066400000000000000000000004071475274123300304400ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class Shadow1Sample { @Parameters("a") @Test public void test1(String a) { Assert.assertEquals(a, "First"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/Shadow2Sample.java000066400000000000000000000004101475274123300304330ustar00rootroot00000000000000package test.parameters; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class Shadow2Sample { @Parameters("a") @Test public void test2(String a) { Assert.assertEquals(a, "Second"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/ShadowTest.java000066400000000000000000000023001475274123300300470ustar00rootroot00000000000000package test.parameters; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class ShadowTest extends SimpleBaseTest { @Test public void parametersShouldNotBeShadowed() { XmlSuite suite = createXmlSuite("suite"); XmlTest test = createXmlTest(suite, "test"); XmlClass class1 = createXmlClass(test, Shadow1Sample.class); class1.getLocalParameters().put("a", "First"); XmlInclude include1 = createXmlInclude(class1, "test1"); XmlClass class2 = createXmlClass(test, Shadow2Sample.class); class2.getLocalParameters().put("a", "Second"); XmlInclude include2 = createXmlInclude(class2, "test2"); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("test1(First)", "test2(Second)"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/issue2238/000077500000000000000000000000001475274123300265735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/issue2238/ExampleTestCase.java000066400000000000000000000005441475274123300324700ustar00rootroot00000000000000package test.parameters.issue2238; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ExampleTestCase { @Test @Parameters("value") public void testMethod(int value) { int expected = Integer.parseInt(System.getProperty("value")); Assert.assertEquals(value, expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/parameters/issue2238/IssueTest.java000066400000000000000000000037201475274123300313700ustar00rootroot00000000000000package test.parameters.issue2238; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void ensureParametersCanBeOverriddenAtSuiteLevel() { XmlSuite xmlSuite = createXmlSuite("suite", "test", ExampleTestCase.class); xmlSuite.getParameters().put("value", "100"); runTest(xmlSuite); } @Test public void ensureParametersCanBeOverriddenAtTestLevel() { XmlSuite xmlSuite = createXmlSuite("suite"); XmlTest xmltest = createXmlTest(xmlSuite, "test", ExampleTestCase.class); xmltest.getLocalParameters().put("value", "100"); runTest(xmlSuite); } @Test public void ensureParametersCanBeOverriddenAtClassLevel() { XmlSuite xmlSuite = createXmlSuite("suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "test"); XmlClass xmlclass = createXmlClass(xmlTest, ExampleTestCase.class); xmlclass.getLocalParameters().put("value", "100"); runTest(xmlSuite); } @Test public void ensureParametersCanBeOverriddenAtMethodLevel() { XmlSuite xmlSuite = createXmlSuite("suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "test"); XmlClass xmlclass = createXmlClass(xmlTest, ExampleTestCase.class); XmlInclude xmlInclude = new XmlInclude(); xmlInclude.setName("testMethod"); xmlInclude.getLocalParameters().put("value", "100"); xmlclass.getIncludedMethods().add(xmlInclude); runTest(xmlSuite); } private void runTest(XmlSuite xmlSuite) { System.setProperty("value", "200"); TestNG testng = create(xmlSuite); TestListenerAdapter listener = new TestListenerAdapter(); testng.addListener(listener); testng.run(); assertThat(listener.getFailedTests()).isEmpty(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pholser/000077500000000000000000000000001475274123300244355ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pholser/Captor.java000066400000000000000000000015131475274123300265300ustar00rootroot00000000000000package test.pholser; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Paul Holser * @version $Id: Captor.java,v 1.3 2004/08/26 22:25:22 cedric Exp $ */ public class Captor { private static Captor instance = null; private List captives; public static Captor instance() { if (null == instance) { instance = new Captor(); } return instance; } public static void reset() { // System.out.println("@@PHOLSER RESETTING CAPTOR"); instance().captives = new ArrayList<>(); } public void capture(String aString) { // System.out.println("@@PHOLSER CAPTURING " + aString); captives.add(aString); } public List captives() { return Collections.unmodifiableList(captives); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pholser/Demo.java000066400000000000000000000032041475274123300261630ustar00rootroot00000000000000package test.pholser; import java.util.Arrays; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Paul Holser * @version $Id: Demo.java,v 1.5 2006/06/22 13:45:01 cedric Exp $ */ public class Demo { @BeforeClass public void setUpFixture() { Captor.reset(); Captor.instance().capture("Demo.setUpFixture"); } @BeforeMethod public void setUp() { Captor.instance().capture("Demo.setUp"); } @AfterMethod public void tearDown() { Captor.instance().capture("Demo.tearDown"); } @AfterClass public void tearDownFixture() { final List expected = Arrays.asList(new String[] {"Demo.setUpFixture", "Demo.setUp", "Demo.tearDown"}); final List actual = Captor.instance().captives(); verify(expected, actual); } @Test public void go() { final List expected = Arrays.asList(new String[] {"Demo.setUpFixture", "Demo.setUp"}); final List actual = Captor.instance().captives(); verify(expected, actual); } private void verify(List expected, List actual) { if (!expected.equals(actual)) { throw new AssertionError( "\nExpected:" + dumpList(expected) + "\n Got:" + dumpList(actual)); } } private String dumpList(List list) { StringBuffer result = new StringBuffer(); for (String l : list) { result.append(" " + l); } return result.toString(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pholser/Saboteur.java000066400000000000000000000015431475274123300270670ustar00rootroot00000000000000package test.pholser; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Paul Holser * @version $Id: Saboteur.java,v 1.4 2006/06/22 13:45:01 cedric Exp $ */ public class Saboteur { @BeforeClass public void setUpFixture() { Captor.reset(); Captor.instance().capture("Saboteur.setUpFixture"); } @BeforeMethod public void setUp() { Captor.instance().capture("Saboteur.setUp"); } @AfterMethod public void tearDown() { Captor.instance().capture("Saboteur.tearDown"); } @AfterClass public void tearDownFixture() { Captor.instance().capture("Saboteur.tearDownFixture"); } @Test public void go() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pkg/000077500000000000000000000000001475274123300235425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pkg/PackageTest.java000066400000000000000000000046201475274123300266020ustar00rootroot00000000000000package test.pkg; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import test.BaseTest; import test.pkg2.Test2; /** * Tests that in testng.xml works. * *

Created on Aug 2, 2005 * * @author cbeust */ public class PackageTest extends BaseTest { public static boolean NON_TEST_CONSTRUCTOR = false; @Test public void stringSingle() { addPackage("test.pkg2", new String[0], new String[0]); run(); String[] passed = { "method11", "method12", "method31", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void packageWithNonTestClasses() { addPackage("test.pkg2", new String[0], new String[0]); run(); assertTrue(!NON_TEST_CONSTRUCTOR, Test2.class.getName() + " should not be considered"); } @Test public void packageWithRegExp1() { addPackage("test.pkg2", new String[] {".*1.*"}, new String[0]); run(); String[] passed = { "method11", "method12", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void packageWithRegExp2() { addPackage("test.pkg2", new String[0], new String[] {".*1.*"}); run(); String[] passed = { "method31", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void packageWithRegExp3() { addPackage("test.pkg2", new String[] {".*3.*"}, new String[] {".*1.*"}); run(); String[] passed = { "method31", }; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void packageWithRegExp4() { addPackage("test.pkg2", new String[] {".*1.*"}, new String[] {".*3.*"}); run(); String[] passed = {"method11", "method12"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void packageWithRegExp5() { addPackage("test.pkg2", new String[0], new String[] {"Test.*"}); run(); String[] passed = {}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pkg2/000077500000000000000000000000001475274123300236245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pkg2/Test1.java000066400000000000000000000002321475274123300254640ustar00rootroot00000000000000package test.pkg2; import org.testng.annotations.Test; public class Test1 { @Test public void method11() {} @Test public void method12() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pkg2/Test2.java000066400000000000000000000002741475274123300254730ustar00rootroot00000000000000package test.pkg2; import test.pkg.PackageTest; public class Test2 { private Test2(float afloat) { PackageTest.NON_TEST_CONSTRUCTOR = true; } public void nonTestMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/pkg2/Test3.java000066400000000000000000000001651475274123300254730ustar00rootroot00000000000000package test.pkg2; import org.testng.annotations.Test; public class Test3 { @Test public void method31() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/000077500000000000000000000000001475274123300256505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/A.java000066400000000000000000000002621475274123300266730ustar00rootroot00000000000000package test.preserveorder; import org.testng.annotations.Test; public class A { @Test public void a1() {} @Test public void a2() {} @Test public void a3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/B.java000066400000000000000000000002621475274123300266740ustar00rootroot00000000000000package test.preserveorder; import org.testng.annotations.Test; public class B { @Test public void b1() {} @Test public void b2() {} @Test public void b3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/C.java000066400000000000000000000002621475274123300266750ustar00rootroot00000000000000package test.preserveorder; import org.testng.annotations.Test; public class C { @Test public void c1() {} @Test public void c2() {} @Test public void c3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/Chuck3Sample.java000066400000000000000000000006131475274123300307750ustar00rootroot00000000000000package test.preserveorder; import org.testng.annotations.Test; public class Chuck3Sample { @Test( groups = {"functional"}, dependsOnMethods = {"c3TestTwo"}) public void c3TestThree() {} @Test(groups = {"functional"}) public static void c3TestOne() {} @Test( groups = {"functional"}, dependsOnMethods = {"c3TestOne"}) public static void c3TestTwo() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/Chuck4Sample.java000066400000000000000000000006131475274123300307760ustar00rootroot00000000000000package test.preserveorder; import org.testng.annotations.Test; public class Chuck4Sample { @Test( groups = {"functional"}, dependsOnMethods = {"c4TestTwo"}) public void c4TestThree() {} @Test(groups = {"functional"}) public static void c4TestOne() {} @Test( groups = {"functional"}, dependsOnMethods = {"c4TestOne"}) public static void c4TestTwo() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/ClassSample.java000066400000000000000000000007551475274123300307310ustar00rootroot00000000000000/* * @(#) TestClass.java * Created: Aug 10, 2011 * By: Wolfgang & Monika Baltes * Copyright 2011 Wolfgang Baltes * WOLFGANG & MONIKA BALTES PROPRIETARY/CONFIDENTIAL. * Use is subject to license terms. */ package test.preserveorder; import org.testng.Assert; import org.testng.annotations.Test; public class ClassSample { private final int val; public ClassSample(int val) { this.val = val; } @Test public void checkVal() { Assert.assertTrue(this.val != 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/ClassSampleFactory.java000066400000000000000000000004411475274123300322510ustar00rootroot00000000000000package test.preserveorder; import org.testng.annotations.Factory; public class ClassSampleFactory { @Factory public Object[] f() { final Object[] res = new Object[4]; for (int i = 0; i < res.length; i++) { res[i] = new ClassSample(i + 1); } return res; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/Issue1122Sample.java000066400000000000000000000005501475274123300312530ustar00rootroot00000000000000package test.preserveorder; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; public class Issue1122Sample { @Test public void test(ITestContext context) { Assert.assertEquals( context.getCurrentXmlTest().getPreserveOrder(), XmlSuite.DEFAULT_PRESERVE_ORDER); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/preserveorder/PreserveOrderTest.java000066400000000000000000000076741475274123300321600ustar00rootroot00000000000000package test.preserveorder; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Iterator; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class PreserveOrderTest extends SimpleBaseTest { @DataProvider public static Object[][] dpTests() { return new Class[][] { new Class[] {A.class, B.class, C.class}, new Class[] {A.class, C.class, B.class}, new Class[] {B.class, A.class, C.class}, new Class[] {B.class, C.class, A.class}, new Class[] {C.class, B.class, A.class}, new Class[] {C.class, A.class, B.class} }; } @Test(dataProvider = "dpTests") public void preserveClassOrder(Class[] tests) { TestNG tng = create(); XmlSuite suite = createXmlSuite("Suite"); XmlTest test = createXmlTest(suite, "Test", tests); test.setPreserveOrder(true); tng.setXmlSuites(Arrays.asList(suite)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getInvokedMethodNames()).hasSize(9); Iterator methods = listener.getInvokedMethodNames().iterator(); for (Class testClass : tests) { for (int i = 1; i <= 3; i++) { String methodName = methods.next(); Assert.assertEquals(methodName, testClass.getSimpleName().toLowerCase() + i); } } } @DataProvider public static Object[][] dpMethods() { return new String[][] { new String[] {"a1", "a2", "a3"}, new String[] {"a1", "a3", "a2"}, new String[] {"a2", "a1", "a3"}, new String[] {"a2", "a3", "a1"}, new String[] {"a3", "a2", "a1"}, new String[] {"a3", "a1", "a2"} }; } @Test(dataProvider = "dpMethods") public void preserveMethodOrder(String[] methods) { TestNG tng = create(); XmlSuite suite = createXmlSuite("Suite"); XmlTest test = createXmlTest(suite, "Test", A.class); addMethods(test.getXmlClasses().get(0), methods); test.setPreserveOrder(true); tng.setXmlSuites(Arrays.asList(suite)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getInvokedMethodNames()).containsExactly(methods); } @Test public void orderShouldBePreservedWithDependencies() { TestNG tng = create(); XmlSuite suite = createXmlSuite("PreserveOrder"); XmlTest test = createXmlTest(suite, "Test", Chuck4Sample.class, Chuck3Sample.class); test.setPreserveOrder(true); tng.setXmlSuites(Arrays.asList(suite)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()) .containsExactly( "c4TestOne", "c4TestTwo", "c4TestThree", "c3TestOne", "c3TestTwo", "c3TestThree"); } @Test(description = "preserve-order on a factory doesn't cause an NPE") public void factoryPreserve() { TestNG tng = create(); XmlSuite suite = createXmlSuite("FactoryPreserve"); XmlTest test = createXmlTest(suite, "Test", ClassSampleFactory.class); test.setPreserveOrder(true); tng.setXmlSuites(Arrays.asList(suite)); tng.run(); } @Test(description = "GITHUB-1122 Use default value for preserve-order") public void preserveOrderValueShouldBeTheDefaultOne() { TestNG tng = create(Issue1122Sample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/000077500000000000000000000000001475274123300246425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/PriorityTest.java000066400000000000000000000103771475274123300301760ustar00rootroot00000000000000package test.priority; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.priority.issue2075.InterruptTest; import test.priority.issue2137.IssueTest; import test.priority.issue2137.OrderListener; public class PriorityTest extends SimpleBaseTest { private void runTest(Class cls, boolean parallel, String... methods) { TestNG tng = create(cls); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); if (parallel) { tng.setParallel(XmlSuite.ParallelMode.METHODS); } tng.run(); if (parallel) { // If tests are being executed in parallel, then order of methods is non-deterministic. assertThat(listener.getInvokedMethodNames()).containsExactlyInAnyOrder(methods); } else { assertThat(listener.getInvokedMethodNames()).containsExactly(methods); } } @Test(enabled = false, description = "Make sure priorities work in parallel mode") public void priorityInParallel1() { runTest(WithPrioritySampleTest.class, true /* parallel */, "first", "second"); } @Test(enabled = false, description = "Make sure priorities work in parallel mode") public void priorityInParallel2() { runTest(WithPrioritySample2Test.class, true /* parallel */, "second", "first"); } @Test(description = "Make sure priorities work in sequential mode") public void priorityInSequential1() { runTest(WithPrioritySampleTest.class, false /* sequential */, "first", "second"); } @Test(description = "Make sure priorities work in sequential mode") public void priorityInSequential2() { runTest(WithPrioritySample2Test.class, false /* sequential */, "second", "first"); } @Test( description = "GITHUB #793: Test suite with tests using dependency and priority has wrong behavior") public void priorityWithDependsOnMethods() { runTest( WithPriorityAndDependsMethodsSample.class, false /* sequential */, "first", "second", "third"); } @Test( description = "Test suite with tests using dependency, priority, and parallel has wrong behavior") public void priorityWithDependsOnMethodsParallel() { runTest( WithPriorityAndDependsMethodsSample.class, true /* parallel */, "first", "third", "second"); } @Test( description = "GITHUB #1334: Order by priority gets messed up when there are failures and dependsOnMethods") public void priorityWithDependencyAndFailures() { TestNG tng = create(SampleTest01.class, SampleTest02.class); tng.setParallel(XmlSuite.ParallelMode.CLASSES); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); List expected = Arrays.asList("test0010_createAction", "test0030_advancedSearch", "test0060_deleteAction"); List allSkipped = listener.getSkippedMethodNames(); // Remove skipped methods from SampleTest01's invoked methods. List actual = listener.getMethodsForTestClass(SampleTest01.class).stream() .filter(each -> !allSkipped.contains(each)) .collect(Collectors.toList()); assertThat(actual).containsExactlyElementsOf(expected); } @Test(description = "GITHUB-2075") public void testInterruptStatusWithMethodsThatHavePriorities() { XmlSuite xmlSuite = createXmlSuite("my_suite", "my_test", InterruptTest.class); TestNG tng = create(xmlSuite); TestListenerAdapter listener = new TestListenerAdapter(); tng.addListener(listener); tng.run(); assertThat(listener.getFailedTests()).isEmpty(); } @Test(description = "GITHUB-2137") public void testPriorityOrdering() { TestNG testNG = create(IssueTest.class); OrderListener listener = new OrderListener(); testNG.addListener(listener); testNG.run(); String[] expected = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "z"}; assertThat(listener.getLogs()).containsExactly(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/SampleTest01.java000066400000000000000000000016251475274123300277330ustar00rootroot00000000000000package test.priority; import org.testng.Assert; import org.testng.annotations.Test; public class SampleTest01 extends SampleTestBase { @Test(priority = 1) public void test0010_createAction() { throw new RuntimeException("Simulating failure"); } @Test( priority = 2, dependsOnMethods = {"test0010_createAction"}) public void test0020_simpleSearch() { Assert.assertTrue(true); } @Test(priority = 3) public void test0030_advancedSearch() { Assert.assertTrue(true); } @Test( priority = 4, dependsOnMethods = {"test0010_createAction"}) public void test0040_viewAction() { Assert.assertTrue(true); } @Test( priority = 5, dependsOnMethods = {"test0010_createAction"}) public void test0050_modifyAction() { Assert.assertTrue(true); } @Test(priority = 6) public void test0060_deleteAction() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/SampleTest02.java000066400000000000000000000015751475274123300277400ustar00rootroot00000000000000package test.priority; import org.testng.Assert; import org.testng.annotations.Test; public class SampleTest02 extends SampleTestBase { @Test(priority = 1) public void test0210_createAction() { Assert.assertTrue(true); } @Test( priority = 2, dependsOnMethods = {"test0210_createAction"}) public void test0220_simpleSearch() { Assert.assertTrue(true); } @Test(priority = 3) public void test0230_advancedSearch() { Assert.assertTrue(true); } @Test( priority = 4, dependsOnMethods = {"test0210_createAction"}) public void test0240_viewAction() { Assert.assertTrue(true); } @Test( priority = 5, dependsOnMethods = {"test0210_createAction"}) public void test0250_modifyAction() { Assert.assertTrue(true); } @Test(priority = 6) public void test0260_deleteAction() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/SampleTestBase.java000066400000000000000000000003561475274123300303650ustar00rootroot00000000000000package test.priority; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public abstract class SampleTestBase { @BeforeClass public void setUp() {} @AfterClass public void closeBrowser() {} } WithPriorityAndDependsMethodsSample.java000066400000000000000000000004051475274123300345160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/prioritypackage test.priority; import org.testng.annotations.Test; public class WithPriorityAndDependsMethodsSample { @Test public void first() {} @Test(dependsOnMethods = {"first"}) public void second() {} @Test(priority = 1) public void third() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/WithPrioritySample2Test.java000066400000000000000000000003101475274123300322400ustar00rootroot00000000000000package test.priority; import org.testng.annotations.Test; public class WithPrioritySample2Test { @Test(priority = -2) public void first() {} @Test(priority = -3) public void second() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/WithPrioritySampleTest.java000066400000000000000000000003071475274123300321640ustar00rootroot00000000000000package test.priority; import org.testng.annotations.Test; public class WithPrioritySampleTest { @Test(priority = -2) public void first() {} @Test(priority = -1) public void second() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/WithoutPrioritySampleTest.java000066400000000000000000000002551475274123300327160ustar00rootroot00000000000000package test.priority; import org.testng.annotations.Test; public class WithoutPrioritySampleTest { @Test public void first() {} @Test public void second() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/issue2075/000077500000000000000000000000001475274123300263105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/issue2075/InterruptTest.java000066400000000000000000000005611475274123300320110ustar00rootroot00000000000000package test.priority.issue2075; import org.testng.annotations.Test; public class InterruptTest { @Test(priority = 1) public void interruptsTheCurrentThread() { Thread.currentThread().interrupt(); } @Test(priority = 2) public void shouldntGetInterruptedButDoes() throws InterruptedException { Thread.sleep(0); // this will throw an exception } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/issue2137/000077500000000000000000000000001475274123300263075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/issue2137/IssueTest.java000066400000000000000000000013551475274123300311060ustar00rootroot00000000000000package test.priority.issue2137; import org.testng.annotations.Test; public class IssueTest { @Test(priority = Integer.MIN_VALUE) public void a() {} @Test(priority = 1) public void b() {} @Test(priority = 2) public void c() {} @Test(priority = 3) public void d() {} @Test(priority = 4) public void e() {} @Test(priority = 5) public void f() {} @Test(priority = 6) public void g() {} @Test(priority = 7) public void h() {} @Test(priority = 8) public void i() {} @Test(priority = 9) public void j() {} @Test(priority = 10) public void k() {} @Test(priority = 11) public void l() {} @Test(priority = 12) public void m() {} @Test(priority = Integer.MAX_VALUE) public void z() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/issue2137/OrderListener.java000066400000000000000000000010021475274123300317240ustar00rootroot00000000000000package test.priority.issue2137; import java.util.ArrayList; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class OrderListener implements IInvokedMethodListener { private List logs = new ArrayList<>(); public List getLogs() { return logs; } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { logs.add(method.getTestMethod().getMethodName()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/parallel/000077500000000000000000000000001475274123300264365ustar00rootroot00000000000000EfficientPriorityParallelizationTest.java000066400000000000000000000270161475274123300366010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/parallelpackage test.priority.parallel; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.*; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.BaseParallelizationTest; import test.thread.parallelization.TestNgRunStateListener; import test.thread.parallelization.TestNgRunStateTracker.EventLog; public class EfficientPriorityParallelizationTest extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(EfficientPriorityParallelizationTest2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_A_TEST_A = "TestSuiteA-HighPriorityTestClassTest"; private static final String SUITE_A_TEST_B = "TestSuiteA-LowPriorityTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteOneTestTwoTestMethodLevelEventLogs; private EventLog suiteOneSuiteListenerOnStartEventLog; private EventLog suiteOneSuiteListenerOnFinishEventLog; private EventLog suiteOneTestOneListenerOnStartEventLog; private EventLog suiteOneTestOneListenerOnFinishEventLog; private EventLog suiteOneTestTwoListenerOnStartEventLog; private EventLog suiteOneTestTwoListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlTest testA = createXmlTest(suiteOne, SUITE_A_TEST_A, HighPriorityTestSample.class); XmlTest testB = createXmlTest(suiteOne, SUITE_A_TEST_B, LowPriorityTestSample.class); suiteOne.setParallel(XmlSuite.ParallelMode.TESTS); suiteOne.setThreadCount(THREAD_POOL_SIZE); testA.setParallel(XmlSuite.ParallelMode.METHODS); testA.setThreadCount(THREAD_POOL_SIZE); testB.setParallel(XmlSuite.ParallelMode.METHODS); testB.setThreadCount(THREAD_POOL_SIZE); // High priority but slow test does slowness on its own. addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "50"); // Low priority but quick addParams(suiteOne, SUITE_A, SUITE_A_TEST_B, "50"); TestNG tng = create(suiteOne); tng.setSuiteThreadPoolSize(THREAD_POOL_SIZE); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning EfficientPriorityParallelizationTest. This test scenario consists of 1 suite " + "with 2 tests. Parallel is set to TESTS at the suite level, METHODS at the test level, and the thread pool size is 2. One test shall consist of a " + "single test class with a single, high-priority, slow-running method, while the other test shall " + "consist of a single test class with several low-priority, quick-running methods. There are no " + "dependencies, data providers or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + HighPriorityTestSample.class.getCanonicalName() + ". Thread count: 2"); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_B + ", Test class: " + LowPriorityTestSample.class.getCanonicalName() + ". Thread count: 2"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteOneTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_B); testEventLogsMap.put(SUITE_A_TEST_A, getTestLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A)); testEventLogsMap.put(SUITE_A_TEST_B, getTestLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_B)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_B); suiteOneTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_B); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_A + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 12, "There should 12 test method level events logged for " + SUITE_A + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 12, "There should be 12 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassForMethods( SUITE_A, SUITE_A_TEST_A, HighPriorityTestSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, HighPriorityTestSample.class); verifyNumberOfInstancesOfTestClassForMethods( SUITE_A, SUITE_A_TEST_B, LowPriorityTestSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_A, SUITE_A_TEST_B, LowPriorityTestSample.class); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteOneTestTwoListenerOnStartEventLog, suiteOneTestTwoTestMethodLevelEventLogs, suiteOneTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_B + ". Test listener onStart event log: " + suiteOneTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestTwoTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( HighPriorityTestSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( LowPriorityTestSample.class, SUITE_A, SUITE_A_TEST_B); } // Verifies that the slow, high-priority method started before and ended after the faster, // low-priority methods. @Test public void verifyThatSlowMethodStartedFirstAndEndedLast() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestTwoTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All the test two methods should run between when test one starts and ends. Start Event: " + suiteOneTestOneListenerOnStartEventLog + ". In between events: " + suiteOneTestTwoTestMethodLevelEventLogs + ". Final event: " + suiteOneTestOneListenerOnFinishEventLog); } } EfficientPriorityParallelizationTest2.java000066400000000000000000000266311475274123300366650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/parallelpackage test.priority.parallel; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.*; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.BaseParallelizationTest; import test.thread.parallelization.TestNgRunStateListener; import test.thread.parallelization.TestNgRunStateTracker.EventLog; public class EfficientPriorityParallelizationTest2 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(EfficientPriorityParallelizationTest2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_A_TEST_A = "TestSuiteA-HighPriorityTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private EventLog suiteOneSuiteListenerOnStartEventLog; private EventLog suiteOneSuiteListenerOnFinishEventLog; private EventLog suiteOneTestOneListenerOnStartEventLog; private EventLog suiteOneTestOneListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlTest testA = createXmlTest( suiteOne, SUITE_A_TEST_A, HighPriorityTestSample.class, LowPriorityTestSample.class); suiteOne.setParallel(XmlSuite.ParallelMode.NONE); suiteOne.setThreadCount(1); testA.setParallel(XmlSuite.ParallelMode.METHODS); testA.setThreadCount(THREAD_POOL_SIZE); // High priority test takes care of itself addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "50"); TestNG tng = create(suiteOne); tng.setSuiteThreadPoolSize(THREAD_POOL_SIZE); tng.addListener((ITestNGListener) new TestNgRunStateListener()); // TODO: modify this log.debug( "Beginning EfficientPriorityParallelizationTest. This test scenario consists of 1 suite " + "with 2 tests. Parallel is set to METHODS and the thread pool size is 2. One test shall consist of a " + "single test class with a single, high-priority, slow-running method, while the other test shall " + "consist of a single test class with several low-priority, quick-running methods. There are no " + "dependencies, data providers or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + HighPriorityTestSample.class.getCanonicalName() + ", " + LowPriorityTestSample.class.getCanonicalName() + ". Thread count: 2"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneTestMethodLevelEventLogs.stream() .filter(e -> e.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_START); testEventLogsMap.put(SUITE_A_TEST_A, getTestLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 12, "There should 12 test method level events logged for " + SUITE_A + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 12, "There should be 12 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); } @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassForMethods( SUITE_A, SUITE_A_TEST_A, HighPriorityTestSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, HighPriorityTestSample.class); verifyNumberOfInstancesOfTestClassForMethods( SUITE_A, SUITE_A_TEST_A, LowPriorityTestSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, LowPriorityTestSample.class); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( HighPriorityTestSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( LowPriorityTestSample.class, SUITE_A, SUITE_A_TEST_A); } // Verifies that the slow, high-priority method started before and ended after the faster, // low-priority methods. @Test public void verifyThatSlowMethodStartedFirstAndEndedLast() { EventLog highPriStart = suiteOneTestOneTestMethodLevelEventLogs.stream() .filter( e -> { String classData = (String) e.getData(EventInfo.CLASS_NAME); boolean rightClass = classData.contains(HighPriorityTestSample.class.getSimpleName()); return e.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_START && rightClass; }) .findFirst() .get(); EventLog highPriEnd = suiteOneTestOneTestMethodLevelEventLogs.stream() .filter( e -> { String classData = (String) e.getData(EventInfo.CLASS_NAME); boolean rightClass = classData.contains(HighPriorityTestSample.class.getSimpleName()); return e.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_PASS && rightClass; }) .findFirst() .get(); ; List lowPriEvents = suiteOneTestOneTestMethodLevelEventLogs.stream() .filter( e -> { String classData = (String) e.getData(EventInfo.CLASS_NAME); boolean rightClass = classData.contains(LowPriorityTestSample.class.getSimpleName()); return rightClass; }) .collect(Collectors.toList()); verifyEventsOccurBetween( highPriStart, lowPriEvents, highPriEnd, "All the test two methods should run between when test one starts and ends.\nStart Event: " + highPriStart + ".\nIn between events: " + lowPriEvents + ".\nFinal event: " + highPriEnd); } } HighPriorityTestSample.java000066400000000000000000000026721475274123300336540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/parallelpackage test.priority.parallel; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.*; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class HighPriorityTestSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test(priority = -10) public void slowMethod(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "slowMethod") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); // This is supposed to be the slow one, so multiply by 80 so we sleep extra long. TimeUnit.MILLISECONDS.sleep(80 * Integer.parseInt(sleepFor)); } } LowPriorityTestSample.java000066400000000000000000000063071475274123300335350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/priority/parallelpackage test.priority.parallel; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.*; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class LowPriorityTestSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test(priority = 10) public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test(priority = 10) public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test(priority = 10) public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/privatemethod/000077500000000000000000000000001475274123300256345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/privatemethod/PrivateMethodTest.java000066400000000000000000000007541475274123300321200ustar00rootroot00000000000000package test.privatemethod; import org.testng.Assert; import org.testng.annotations.Test; public class PrivateMethodTest { public PrivateMethodTest(String name, int value) {} private int privateMethod() { return 1; } public static class PrivateMethodInnerTest { @Test public void testPrivateMethod() { PrivateMethodTest pmt = new PrivateMethodTest("aname", 1); int returnValue = pmt.privateMethod(); Assert.assertEquals(returnValue, 1); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reflect/000077500000000000000000000000001475274123300244055ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reflect/ReflectionRecipesTest.java000066400000000000000000000327521475274123300315260ustar00rootroot00000000000000package test.reflect; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.TestRunner; import org.testng.annotations.DataProvider; import org.testng.annotations.NoInjection; import org.testng.annotations.Test; import org.testng.internal.reflect.InjectableParameter; import org.testng.internal.reflect.Parameter; import org.testng.internal.reflect.ReflectionRecipes; import org.testng.log4testng.Logger; import org.testng.xml.XmlTest; /** @author Nitin Verma */ public class ReflectionRecipesTest { private static final Logger log = Logger.getLogger(ReflectionRecipesTest.class); private static final Object[] A0 = new Object[] {343, true}; private static final Parameter[] S0 = getMethodParameters(T.class, "s0"); private static final Parameter[] S1 = getMethodParameters(T.class, "s1"); private static final Parameter[] S2 = getMethodParameters(T.class, "s2"); private static final Parameter[] S3 = getMethodParameters(T.class, "s3"); private static Parameter[] getMethodParameters(final Class clazz, final String methodName) { Method method = null; Parameter[] parameters = null; for (final Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { method = m; } } if (method != null) { parameters = ReflectionRecipes.getMethodParameters(method); } return parameters; } @DataProvider public Object[][] methodInputParameters() { return new Object[][] {S0, S1, S2, S3}; } @DataProvider public Object[][] methodInputParamArgsPair() { return new Object[][] { new Object[] {S0, A0}, new Object[] {S1, A0}, new Object[] {S2, A0}, new Object[] {S3, A0}, }; } @DataProvider public Object[][] exactMatchDP() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final Method[] methods = ExactMatchTest.class.getDeclaredMethods(); final List objects = new ArrayList<>(); log.debug("exactMatchDP:"); for (int i = 0; i < methods.length; i++) { final Method method = methods[i]; final ExactMatchTest.Expectation annotation = method.getAnnotation(ExactMatchTest.Expectation.class); if (annotation != null) { final String provider = annotation.expectationProvider(); final int flag = annotation.flag(); Assert.assertNotNull(provider); final Method providerMethod = ExactMatchTest.class.getMethod(provider, int.class); final Object out = providerMethod.invoke(ExactMatchTest.class, flag); Assert.assertTrue(out instanceof Object[][]); log.debug(method.getName() + ", " + out); objects.add(new Object[] {out, method}); } } return objects.toArray(new Object[objects.size()][]); } @DataProvider public Object[][] matchArrayEndingDP() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final Method[] methods = MatchArrayEndingTest.class.getDeclaredMethods(); final List objects = new ArrayList<>(); log.debug("matchArrayEndingDP:"); for (int i = 0; i < methods.length; i++) { final Method method = methods[i]; final MatchArrayEndingTest.Expectation annotation = method.getAnnotation(MatchArrayEndingTest.Expectation.class); if (annotation != null) { final String provider = annotation.expectationProvider(); final int flag = annotation.flag(); Assert.assertNotNull(provider); final Method providerMethod = MatchArrayEndingTest.class.getMethod(provider, int.class); final Object out = providerMethod.invoke(MatchArrayEndingTest.class, flag); Assert.assertTrue(out instanceof Object[][]); log.debug(method.getName() + ", " + out); objects.add(new Object[] {out, method}); } } return objects.toArray(new Object[objects.size()][]); } @DataProvider public Object[][] testContexts() { return new Object[][] { {TestRunner.class}, {ITestContext.class}, {TestContextJustForTesting.class} }; } @DataProvider public Object[][] notTestContexts() { return new Object[][] {{Object.class}, {Class.class}, {Connection.class}}; } @Test(dataProvider = "matchArrayEndingDP") public void matchArrayEndingTest(final Object[][] expected, @NoInjection final Method method) { if (expected != null) { final Parameter[] methodParameters = ReflectionRecipes.getMethodParameters(method); Assert.assertNotNull(methodParameters); final Parameter[] filteredParameters = ReflectionRecipes.filter(methodParameters, InjectableParameter.Assistant.ALL_INJECTS); Assert.assertNotNull(filteredParameters); for (final Object[] expect : expected) { Assert.assertNotNull(expect); Assert.assertEquals(expect.length, 2); Assert.assertNotNull(expect[0]); Assert.assertTrue(expect[0] instanceof Object[]); Assert.assertNotNull(expect[1]); Assert.assertTrue(expect[1] instanceof Boolean); Assert.assertEquals( ReflectionRecipes.matchArrayEnding(filteredParameters, (Object[]) expect[0]), expect[1]); } } } @Test(dataProvider = "exactMatchDP") public void exactMatchTest(final Object[][] expected, @NoInjection final Method method) { if (expected != null) { final Parameter[] methodParameters = ReflectionRecipes.getMethodParameters(method); Assert.assertNotNull(methodParameters); final Parameter[] filteredParameters = ReflectionRecipes.filter(methodParameters, InjectableParameter.Assistant.ALL_INJECTS); Assert.assertNotNull(filteredParameters); for (final Object[] expect : expected) { Assert.assertNotNull(expect); Assert.assertEquals(expect.length, 2); Assert.assertNotNull(expect[0]); Assert.assertTrue(expect[0] instanceof Object[]); Assert.assertNotNull(expect[1]); Assert.assertTrue(expect[1] instanceof Boolean); Assert.assertEquals( ReflectionRecipes.exactMatch(filteredParameters, (Object[]) expect[0]), expect[1]); } } } @Test(dataProvider = "methodInputParameters") public void testFilters(final Parameter[] parameters) { log.debug("In: " + Arrays.asList(parameters)); final Parameter[] parameters1 = ReflectionRecipes.filter(parameters, InjectableParameter.Assistant.ALL_INJECTS); log.debug("Out: " + Arrays.asList(parameters1)); Assert.assertEquals(parameters1.length, 2); Assert.assertEquals(parameters1[0].getType(), int.class); Assert.assertEquals(parameters1[1].getType(), Boolean.class); } @Test(dataProvider = "methodInputParamArgsPair") public void testInject(final Parameter[] parameters, final Object[] args) { log.debug("In: " + Arrays.asList(parameters)); log.debug("args: " + Arrays.asList(args)); final Object[] injectedArgs = ReflectionRecipes.inject( parameters, InjectableParameter.Assistant.ALL_INJECTS, args, (Method) null, null, null); log.debug("injectedArgs: " + Arrays.asList(injectedArgs)); Assert.assertEquals(injectedArgs.length, parameters.length); } @Test(dataProvider = "testContexts") public void testIsOrImplementsInterface(final Class clazz) { Assert.assertTrue(ReflectionRecipes.isOrImplementsInterface(ITestContext.class, clazz)); } @Test(dataProvider = "notTestContexts") public void testNegativeCaseIsOrImplementsInterface(final Class clazz) { Assert.assertFalse(ReflectionRecipes.isOrImplementsInterface(ITestContext.class, clazz)); } private static interface T { public void s0(TestContextJustForTesting testContext, int i, Boolean b); public void s1(int i, ITestContext iTestContext, Boolean b); public void s2(int i, Boolean b, ITestContext iTestContext); public void s3(ITestContext iTestContext1, int i, Boolean b, ITestContext iTestContext2); } public abstract static class ExactMatchTest { public static Object[][] exactMatchData(final int flag) { switch (flag) { case 0: return new Object[][] { new Object[] {new Object[] {}, true}, new Object[] {new Object[] {1}, false}, new Object[] {new Object[] {""}, false}, new Object[] {new Object[] {1, ""}, false}, }; case 1: return new Object[][] { new Object[] {new Object[] {1}, true}, new Object[] {new Object[] {}, false}, new Object[] {new Object[] {""}, false}, new Object[] {new Object[] {1, ""}, false}, new Object[] {new Object[] {"", 1}, false}, }; default: return null; } } @Expectation(expectationProvider = "exactMatchData", flag = 0) public abstract void s0(); @Expectation(expectationProvider = "exactMatchData", flag = 0) public abstract void s0(final ITestContext a0); @Expectation(expectationProvider = "exactMatchData", flag = 0) public abstract void s0(final ITestContext a0, final ITestResult a1); @Expectation(expectationProvider = "exactMatchData", flag = 0) public abstract void s0(final ITestContext a0, final ITestResult a1, final XmlTest a2); @Expectation(expectationProvider = "exactMatchData", flag = 0) public abstract void s0( final ITestContext a0, final ITestResult a1, final XmlTest a2, final Method a3); @Expectation(expectationProvider = "exactMatchData", flag = 1) public abstract void s1(final int a0); @Expectation(expectationProvider = "exactMatchData", flag = 1) public abstract void s1(final ITestContext a0, final int a1); @Expectation(expectationProvider = "exactMatchData", flag = 1) public abstract void s1(final ITestContext a0, final Integer a1, final ITestResult a2); @Expectation(expectationProvider = "exactMatchData", flag = 1) public abstract void s1( final int a0, final ITestContext a1, final ITestResult a2, final XmlTest a3); @Expectation(expectationProvider = "exactMatchData", flag = 1) public abstract void s1( final ITestContext a0, final ITestResult a1, final int a2, final XmlTest a3, final Method a4); @Retention(RUNTIME) @Target({METHOD}) public static @interface Expectation { public String expectationProvider(); public int flag(); } } public abstract static class MatchArrayEndingTest { public static Object[][] matchArrayEndingData(final int flag) { switch (flag) { case 0: return new Object[][] { new Object[] {new Object[] {10f, 2.1f}, true}, new Object[] {new Object[] {10}, true}, new Object[] {new Object[] {10d, ""}, false}, new Object[] {new Object[] {1, ""}, false}, }; case 1: return new Object[][] { new Object[] {new Object[] {1, 10f, 2.1f}, true}, new Object[] {new Object[] {}, false}, new Object[] {new Object[] {""}, false}, new Object[] {new Object[] {10f, "", 2.1f}, false}, new Object[] {new Object[] {"", 10f, 2.1f}, false}, }; default: return null; } } @Expectation(expectationProvider = "matchArrayEndingData", flag = 0) public abstract void s0(final float... f); @Expectation(expectationProvider = "matchArrayEndingData", flag = 0) public abstract void s0(final float[] f, final ITestContext a0); @Expectation(expectationProvider = "matchArrayEndingData", flag = 0) public abstract void s0(final ITestContext a0, final float[] f, final ITestResult a1); @Expectation(expectationProvider = "matchArrayEndingData", flag = 0) public abstract void s0( final ITestContext a0, final ITestResult a1, final XmlTest a2, final float... f); @Expectation(expectationProvider = "matchArrayEndingData", flag = 0) public abstract void s0( final ITestContext a0, final ITestResult a1, final XmlTest a2, final float[] f, final Method a3); @Expectation(expectationProvider = "matchArrayEndingData", flag = 1) public abstract void s1(final int a0, final float... f); @Expectation(expectationProvider = "matchArrayEndingData", flag = 1) public abstract void s1(final ITestContext a0, final int a1, final float... f); @Expectation(expectationProvider = "matchArrayEndingData", flag = 1) public abstract void s1( final ITestContext a0, final Integer a1, final ITestResult a2, final float... f); @Expectation(expectationProvider = "matchArrayEndingData", flag = 1) public abstract void s1( final int a0, final ITestContext a1, final ITestResult a2, final float[] f, final XmlTest a3); @Expectation(expectationProvider = "matchArrayEndingData", flag = 1) public abstract void s1( final ITestContext a0, final ITestResult a1, final int a2, final XmlTest a3, final float[] f, final Method a4); @Retention(RUNTIME) @Target({METHOD}) public static @interface Expectation { public String expectationProvider(); public int flag(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reflect/TestContextJustForTesting.java000066400000000000000000000037341475274123300324160ustar00rootroot00000000000000package test.reflect; import java.util.Collection; import java.util.Date; import java.util.Set; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.xml.XmlTest; /** */ public class TestContextJustForTesting implements ITestContext { @Override public String getName() { return null; } @Override public Date getStartDate() { return null; } @Override public Date getEndDate() { return null; } @Override public IResultMap getPassedTests() { return null; } @Override public IResultMap getSkippedTests() { return null; } @Override public IResultMap getFailedButWithinSuccessPercentageTests() { return null; } @Override public IResultMap getFailedTests() { return null; } @Override public String[] getIncludedGroups() { return new String[0]; } @Override public String[] getExcludedGroups() { return new String[0]; } @Override public String getOutputDirectory() { return null; } @Override public ISuite getSuite() { return null; } @Override public ITestNGMethod[] getAllTestMethods() { return new ITestNGMethod[0]; } @Override public String getHost() { return null; } @Override public Collection getExcludedMethods() { return null; } @Override public IResultMap getPassedConfigurations() { return null; } @Override public IResultMap getSkippedConfigurations() { return null; } @Override public IResultMap getFailedConfigurations() { return null; } @Override public XmlTest getCurrentXmlTest() { return null; } @Override public Object getAttribute(String name) { return null; } @Override public void setAttribute(String name, Object value) {} @Override public Set getAttributeNames() { return null; } @Override public Object removeAttribute(String name) { return null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reflect/TestMethodMatcher.java000066400000000000000000000222711475274123300306400ustar00rootroot00000000000000package test.reflect; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.annotations.DataProvider; import org.testng.annotations.NoInjection; import org.testng.annotations.Test; import org.testng.internal.reflect.DataProviderMethodMatcher; import org.testng.internal.reflect.MethodMatcher; import org.testng.internal.reflect.MethodMatcherContext; import org.testng.internal.reflect.MethodMatcherException; import org.testng.log4testng.Logger; import org.testng.xml.XmlTest; /** * Created on 12/24/15 * * @author Nitin Verma */ public class TestMethodMatcher { private static final Logger log = Logger.getLogger(TestMethodMatcher.class); private static Method getMethod(final String methodName) { Method method = null; for (final Method m : TestMethodMatcher.class.getMethods()) { if (m.getName().equals(methodName)) { method = m; } } return method; } @DataProvider public Object[][] methodParamPairs() { return new Object[][] { new Object[] {"goodTestIssue122", new Object[] {"3", new String[] {"three", "four"}}}, new Object[] {"badTestIssue122", new Object[] {"3", new String[] {"three", "four"}}}, new Object[] {"goodTestIssue122", new Object[] {"3", "three", "four"}}, new Object[] {"badTestIssue122", new Object[] {"3", "three", "four"}}, new Object[] {"mixedArgs", new Object[] {3, true, new String[] {"three"}, "four"}}, new Object[] { "mixedArgs", new Object[] {3, true, new String[] {"three"}, new String[] {"four"}} }, new Object[] { "potpourri0", new Object[] { getMethod("mixedArgs"), new XmlTestJustForTesting(), 3, getMethod("badTestIssue122"), new TestContextJustForTesting(), true, new TestResultJustForTesting(), new String[] {"three"}, new String[] {"four"} } }, new Object[] { "potpourri1", new Object[] { getMethod("mixedArgs"), new XmlTestJustForTesting(), 3, getMethod("badTestIssue122"), new TestContextJustForTesting(), true, new TestResultJustForTesting(), new String[] {"three"}, new String[] {"four"} } }, }; } @DataProvider public Object[][] methodParamFailingPairs() { return new Object[][] { new Object[] {"goodTestIssue122", new Object[] {3, "three", "four"}}, new Object[] {"badTestIssue122", new Object[] {3, "three", "four"}}, new Object[] {"mixedArgs", new Object[] {3, true, "three", "four"}}, }; } @Test(dataProvider = "methodParamPairs") public void testMatcher( final String methodName, final Object[] params, final ITestContext iTestContext, final ITestResult iTestResult) throws Throwable { final Method method = getMethod(methodName); final MethodMatcher matcher = new DataProviderMethodMatcher( new MethodMatcherContext(method, params, iTestContext, iTestResult)); method.invoke(new TestMethodMatcher(), matcher.getConformingArguments()); } @Test(dataProvider = "methodParamFailingPairs") public void testNegativeCaseMatcher( final String methodName, final Object[] params, final ITestContext iTestContext, final ITestResult iTestResult) { final Method method = getMethod(methodName); final MethodMatcher matcher = new DataProviderMethodMatcher( new MethodMatcherContext(method, params, iTestContext, iTestResult)); Assert.assertFalse(matcher.conforms()); assertThatThrownBy( () -> { method.invoke(new TestMethodMatcher(), matcher.getConformingArguments()); }) .isInstanceOf(MethodMatcherException.class) // separate lines are used here to avoid \n vs \r\n if running tests in Windows .hasMessageContaining( "has no parameters defined but was found to be using a data provider (either explicitly specified or inherited from class level annotation") .hasMessageContaining("Method: ") .hasMessageContaining("Arguments: "); } public void goodTestIssue122(String s, String[] strings) { for (String item : strings) { log.debug("An item is \"" + item + "\""); } Assert.assertEquals(s, "3"); } public void badTestIssue122(String s, String... strings) { for (String item : strings) { log.debug("An item is \"" + item + "\""); } Assert.assertEquals(s, "3"); } public void mixedArgs(final int i, final Boolean b, final String[] s1, final String... strings) { for (String item : strings) { log.debug("An item is \"" + item + "\""); } Assert.assertEquals(i, 3); Assert.assertNotNull(b); Assert.assertTrue(b); Assert.assertNotNull(s1); Assert.assertEquals(s1.length, 1); Assert.assertEquals(s1[0], "three"); Assert.assertNotNull(strings); Assert.assertEquals(strings.length, 1); Assert.assertEquals(strings[0], "four"); } public void potpourri0( @NoInjection final Method myMethod1, @NoInjection final XmlTest myXmlTest, final Method currentTestMethod, final int i, final Method myMethod2, final ITestContext iTestContext, @NoInjection final ITestContext myTestContext, final Boolean b, @NoInjection final ITestResult myTestResult, final ITestResult iTestResult, final String[] s1, final XmlTest xmlTest, final String... strings) { log.debug("MyMethod1 is \"" + myMethod1 + "\""); log.debug("MyMethod2 is \"" + myMethod2 + "\""); log.debug("CurrentTestMethod is \"" + currentTestMethod + "\""); log.debug("MyITestContext is \"" + myTestContext + "\""); log.debug("ITestContext is \"" + iTestContext + "\""); log.debug("ITestResult is \"" + iTestResult + "\""); log.debug("MyTestResult is \"" + myTestResult + "\""); log.debug("XmlTest is \"" + xmlTest + "\""); log.debug("MyXmlTest is \"" + myXmlTest + "\""); for (String item : strings) { log.debug("An item is \"" + item + "\""); } Assert.assertNotNull(myTestContext); Assert.assertTrue(myTestContext instanceof TestContextJustForTesting); Assert.assertNotNull(myTestResult); Assert.assertTrue(myTestResult instanceof TestResultJustForTesting); Assert.assertNotNull(myXmlTest); Assert.assertTrue(myXmlTest instanceof XmlTestJustForTesting); Assert.assertNotNull(currentTestMethod); Assert.assertEquals("potpourri0", currentTestMethod.getName()); Assert.assertNotNull(myMethod1); Assert.assertEquals("mixedArgs", myMethod1.getName()); Assert.assertNotNull(myMethod2); Assert.assertEquals("badTestIssue122", myMethod2.getName()); Assert.assertEquals(i, 3); Assert.assertNotNull(b); Assert.assertTrue(b); Assert.assertNotNull(s1); Assert.assertEquals(s1.length, 1); Assert.assertEquals(s1[0], "three"); Assert.assertNotNull(strings); Assert.assertEquals(strings.length, 1); Assert.assertEquals(strings[0], "four"); } public void potpourri1( @NoInjection final Method myMethod1, @NoInjection final XmlTest myXmlTest, final Method currentTestMethod, final int i, final Method myMethod2, final ITestContext iTestContext, @NoInjection final ITestContext myTestContext, final Boolean b, @NoInjection final ITestResult myTestResult, final ITestResult iTestResult, final String[] s1, final XmlTest xmlTest, final String[] strings) { log.debug("MyMethod1 is \"" + myMethod1 + "\""); log.debug("MyMethod2 is \"" + myMethod2 + "\""); log.debug("CurrentTestMethod is \"" + currentTestMethod + "\""); log.debug("MyITestContext is \"" + myTestContext + "\""); log.debug("ITestContext is \"" + iTestContext + "\""); log.debug("ITestResult is \"" + iTestResult + "\""); log.debug("MyTestResult is \"" + myTestResult + "\""); log.debug("XmlTest is \"" + xmlTest + "\""); log.debug("MyXmlTest is \"" + myXmlTest + "\""); for (String item : strings) { log.debug("An item is \"" + item + "\""); } Assert.assertNotNull(myTestContext); Assert.assertTrue(myTestContext instanceof TestContextJustForTesting); Assert.assertNotNull(myTestResult); Assert.assertTrue(myTestResult instanceof TestResultJustForTesting); Assert.assertNotNull(myXmlTest); Assert.assertTrue(myXmlTest instanceof XmlTestJustForTesting); Assert.assertNotNull(currentTestMethod); Assert.assertEquals("potpourri1", currentTestMethod.getName()); Assert.assertNotNull(myMethod1); Assert.assertEquals("mixedArgs", myMethod1.getName()); Assert.assertNotNull(myMethod2); Assert.assertEquals("badTestIssue122", myMethod2.getName()); Assert.assertEquals(i, 3); Assert.assertNotNull(b); Assert.assertTrue(b); Assert.assertNotNull(s1); Assert.assertEquals(s1.length, 1); Assert.assertEquals(s1[0], "three"); Assert.assertNotNull(strings); Assert.assertEquals(strings.length, 1); Assert.assertEquals(strings[0], "four"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reflect/TestResultJustForTesting.java000066400000000000000000000045421475274123300322460ustar00rootroot00000000000000package test.reflect; import java.util.List; import java.util.Set; import java.util.UUID; import org.testng.IClass; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; /** * Created on 12/30/15. * * @author Nitin Verma */ public class TestResultJustForTesting implements ITestResult { private final String id = UUID.randomUUID().toString(); @Override public int getStatus() { return 0; } @Override public void setStatus(int status) {} @Override public ITestNGMethod getMethod() { return null; } @Override public Object[] getParameters() { return new Object[0]; } @Override public void setParameters(Object[] parameters) {} @Override public IClass getTestClass() { return null; } @Override public Throwable getThrowable() { return null; } @Override public void setThrowable(Throwable throwable) {} @Override public long getStartMillis() { return 0; } @Override public long getEndMillis() { return 0; } @Override public void setEndMillis(long millis) {} @Override public String getName() { return null; } @Override public boolean isSuccess() { return false; } @Override public String getHost() { return null; } @Override public Object getInstance() { return null; } @Override public Object[] getFactoryParameters() { return new Object[0]; } @Override public String getTestName() { return null; } @Override public void setTestName(String name) {} @Override public boolean wasRetried() { return false; } @Override public void setWasRetried(boolean wasRetried) {} @Override public List getSkipCausedBy() { return null; } @Override public String getInstanceName() { return null; } @Override public ITestContext getTestContext() { return null; } @Override public int compareTo(ITestResult o) { return 0; } @Override public Object getAttribute(String name) { return null; } @Override public void setAttribute(String name, Object value) {} @Override public Set getAttributeNames() { return null; } @Override public Object removeAttribute(String name) { return null; } @Override public String id() { return id; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reflect/XmlTestJustForTesting.java000066400000000000000000000003231475274123300315210ustar00rootroot00000000000000package test.reflect; import org.testng.xml.XmlTest; /** * Created on 12/30/15. * * @author Nitin Verma */ public class XmlTestJustForTesting extends XmlTest {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/000077500000000000000000000000001475274123300251415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/BeforeTestFailingTest.java000066400000000000000000000011561475274123300322030ustar00rootroot00000000000000package test.regression; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class BeforeTestFailingTest extends SimpleBaseTest { @Test public void beforeTestFailingShouldCauseSkips() { TestNG tng = create(MyTestngTest2.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getSkippedTests().size(), 1); Assert.assertEquals(tla.getPassedTests().size(), 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/MyTestngTest.java000066400000000000000000000006001475274123300304120ustar00rootroot00000000000000package test.regression; import org.testng.ITestContext; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public class MyTestngTest { @BeforeSuite() public void beforeSuite(ITestContext tc) throws Exception {} @BeforeTest() public void beforeTest(ITestContext tc) throws Exception { throw new RuntimeException("barfing now"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/MyTestngTest2.java000066400000000000000000000007521475274123300305040ustar00rootroot00000000000000package test.regression; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class MyTestngTest2 extends MyTestngTest { @BeforeClass() public void beforeClass(ITestContext tc) throws Exception {} @BeforeMethod() public void beforeMethod(ITestContext tc) throws Exception { // throw new Exception("fail me"); } @Test() public void test(ITestContext tc) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/groupsordering/000077500000000000000000000000001475274123300302125ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/groupsordering/A.java000066400000000000000000000002741475274123300312400ustar00rootroot00000000000000package test.regression.groupsordering; import org.testng.annotations.Test; public class A extends Base { @Test(groups = "a") public void testA() { s_childAWasRun = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/groupsordering/B.java000066400000000000000000000003221475274123300312330ustar00rootroot00000000000000package test.regression.groupsordering; import org.testng.annotations.Test; public class B extends Base { @Test(groups = "a") public void testB() throws Exception { Base.s_childBWasRun = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/groupsordering/Base.java000066400000000000000000000013371475274123300317330ustar00rootroot00000000000000package test.regression.groupsordering; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; public abstract class Base { protected static boolean s_childAWasRun; protected static boolean s_childBWasRun; @BeforeGroups(value = "a", groups = "a") public void setUp() { Assert.assertFalse( s_childAWasRun || s_childBWasRun, "Static field was not reset: @AfterGroup method not invoked"); } @AfterGroups(value = "a", groups = "a") public void tearDown() { Assert.assertTrue(s_childAWasRun, "Child A was not run"); Assert.assertTrue(s_childBWasRun, "Child B was not run"); s_childAWasRun = false; s_childBWasRun = false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/regression/groupsordering/testng.xml000066400000000000000000000010631475274123300322400ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/000077500000000000000000000000001475274123300244575ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/EmailableReporterTest.java000066400000000000000000000117201475274123300315610ustar00rootroot00000000000000package test.reports; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.lang.reflect.Method; import java.security.Permission; import org.testng.IReporter; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.reporters.EmailableReporter; import org.testng.reporters.EmailableReporter2; import test.SimpleBaseTest; public class EmailableReporterTest extends SimpleBaseTest { private SecurityManager manager; @BeforeClass(alwaysRun = true) public void setup() { manager = System.getSecurityManager(); System.setSecurityManager(new MySecurityManager(manager)); } @AfterClass(alwaysRun = true) public void cleanup() { System.setSecurityManager(manager); } @Test(dataProvider = "getReporterInstances", priority = 1) public void testReportsNameCustomizationViaRunMethodInvocationAndJVMArguments( IReporter reporter, String jvm) { runTestViaRunMethod(reporter, jvm); } @Test(dataProvider = "getReporterInstances", priority = 2) public void testReportsNameCustomizationViaRunMethodInvocation(IReporter reporter) { runTestViaRunMethod(reporter, null /* no jvm arguments */); } @Test(dataProvider = "getReporterNames", priority = 3) public void testReportsNameCustomizationViaMainMethodInvocation(String clazzName) { runTestViaMainMethod(clazzName, null /* no jvm arguments */); } @Test(dataProvider = "getReporterNames", priority = 4) public void testReportsNameCustomizationViaMainMethodInvocationAndJVMArguments( String clazzName, String jvm) { runTestViaMainMethod(clazzName, jvm); } @DataProvider(name = "getReporterInstances") public Object[][] getReporterInstances(Method method) { if (method.getName().toLowerCase().contains("jvmarguments")) { return new Object[][] { {new EmailableReporter(), "emailable.report.name"}, {new EmailableReporter2(), "emailable.report2.name"} }; } return new Object[][] {{new EmailableReporter()}, {new EmailableReporter2()}}; } @DataProvider(name = "getReporterNames") public Object[][] getReporterNames(Method method) { if (method.getName().toLowerCase().contains("jvmarguments")) { return new Object[][] { {EmailableReporter.class.getName(), "emailable.report.name"}, {EmailableReporter2.class.getName(), "emailable.report2.name"} }; } return new Object[][] { {EmailableReporter.class.getName()}, {EmailableReporter2.class.getName()} }; } private void runTestViaMainMethod(String clazzName, String jvm) { String name = Long.toString(System.currentTimeMillis()); File output = createDirInTempDir(name); String filename = "report" + name + ".html"; String[] args = { "-d", output.getAbsolutePath(), "-reporter", clazzName + ":fileName=" + filename, "src/test/resources/1332.xml" }; try { if (jvm != null) { System.setProperty(jvm, filename); } TestNG.main(args); } catch (SecurityException t) { // Gobble Security exception } finally { if (jvm != null) { // reset the jvm arguments System.setProperty(jvm, ""); } } File actual = new File(output.getAbsolutePath(), filename); assertThat(actual).exists(); } private void runTestViaRunMethod(IReporter reporter, String jvm) { String name = Long.toString(System.currentTimeMillis()); File output = createDirInTempDir(name); String filename = "report" + name + ".html"; if (jvm != null) { System.setProperty(jvm, filename); } try { TestNG testNG = create(); testNG.setOutputDirectory(output.getAbsolutePath()); if (reporter instanceof EmailableReporter2) { ((EmailableReporter2) reporter).setFileName(filename); } if (reporter instanceof EmailableReporter) { ((EmailableReporter) reporter).setFileName(filename); } testNG.addListener((ITestNGListener) reporter); testNG.setTestClasses(new Class[] {ReporterSample.class}); testNG.run(); } finally { if (jvm != null) { // reset the jvm argument if it was set System.setProperty(jvm, ""); } } File actual = new File(output.getAbsolutePath(), filename); assertThat(actual).exists(); } public static class MySecurityManager extends SecurityManager { private SecurityManager baseSecurityManager; MySecurityManager(SecurityManager baseSecurityManager) { this.baseSecurityManager = baseSecurityManager; } @Override public void checkPermission(Permission permission) { if (permission.getName().startsWith("exitVM")) { throw new SecurityException("System exit not allowed"); } if (baseSecurityManager != null) { baseSecurityManager.checkPermission(permission); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/FailedReporterTest.java000066400000000000000000000200571475274123300310750ustar00rootroot00000000000000package test.reports; import static org.assertj.core.api.Assertions.assertThat; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.reporters.FailedReporter; import org.testng.xml.SuiteXmlParser; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.testng.xml.internal.Parser; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; import org.xmlunit.diff.Diff; import test.SimpleBaseTest; import test.reports.issue2611.TestClassFailsAtBeforeGroupsWithBeforeGroupsSuiteTestSample; import test.reports.issue2611.TestClassFailsAtBeforeSuiteWithBeforeGroupsSuiteTestSample; import test.reports.issue2611.TestClassFailsAtBeforeTestWithBeforeGroupsSuiteTestSample; import test.reports.issue2611.TestClassWithBeforeGroupsSample; import test.reports.issue2611.TestClassWithBeforeSuiteSample; import test.reports.issue2611.TestClassWithBeforeTestSample; import test.reports.issue2611.TestClassWithJustTestMethodsSample; public class FailedReporterTest extends SimpleBaseTest { @Test public void failedFile() throws IOException { XmlSuite xmlSuite = createXmlSuite("Suite"); xmlSuite.getParameters().put("n", "42"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); xmlTest.addParameter("o", "43"); XmlClass xmlClass = createXmlClass(xmlTest, SimpleFailedSample.class); xmlClass.getLocalParameters().put("p", "44"); TestNG tng = create(xmlSuite); Path temp = Files.createTempDirectory("tmp"); tng.setOutputDirectory(temp.toAbsolutePath().toString()); tng.addListener(new FailedReporter()); tng.run(); Collection failedSuites = new Parser(temp.resolve(FailedReporter.TESTNG_FAILED_XML).toAbsolutePath().toString()) .parse(); XmlSuite failedSuite = failedSuites.iterator().next(); Assert.assertEquals("42", failedSuite.getParameter("n")); XmlTest failedTest = failedSuite.getTests().get(0); Assert.assertEquals("43", failedTest.getParameter("o")); XmlClass failedClass = failedTest.getClasses().get(0); Assert.assertEquals("44", failedClass.getAllParameters().get("p")); } @Test(description = "ISSUE-2445") public void testParameterPreservationWithFactory() throws IOException { final SuiteXmlParser parser = new SuiteXmlParser(); final String testSuite = "src/test/resources/xml/github2445/test-suite.xml"; final String expectedResult = "src/test/resources/xml/github2445/expected-failed-report.xml"; final XmlSuite xmlSuite = parser.parse(testSuite, new FileInputStream(testSuite), true); final TestNG tng = create(xmlSuite); final Path temp = Files.createTempDirectory("tmp"); tng.setOutputDirectory(temp.toAbsolutePath().toString()); tng.addListener(new FailedReporter()); tng.run(); final Diff myDiff = DiffBuilder.compare(Input.fromFile(expectedResult)) .withTest( Input.fromFile( temp.resolve(FailedReporter.TESTNG_FAILED_XML).toAbsolutePath().toString())) .checkForSimilar() .ignoreWhitespace() .build(); assertThat(myDiff).matches((it) -> !it.hasDifferences(), "!it.hasDifferences()"); } @Test(dataProvider = "getTestData") public void testToEnsureConfigFailuresAreIncluded(ClassMethodInfo pairA, ClassMethodInfo pairB) throws IOException { XmlSuite xmlSuite = createXmlSuite("kungfu-panda-suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "kungfu-panda-test", pairA.getTestClass(), pairB.getTestClass()); xmlTest.addIncludedGroup("dragon-warrior"); TestNG tng = create(xmlSuite); final Path temp = Files.createTempDirectory("tmp"); tng.setOutputDirectory(temp.toAbsolutePath().toString()); tng.addListener(new FailedReporter()); tng.run(); Collection failedSuites = new Parser(temp.resolve(FailedReporter.TESTNG_FAILED_XML).toAbsolutePath().toString()) .parse(); XmlSuite failedSuite = failedSuites.iterator().next(); assertThat(failedSuite.getName()) .withFailMessage("The failed suite should have had the prefix of [Failed suite]") .isEqualTo("Failed suite [kungfu-panda-suite]"); XmlTest failedTest = failedSuite.getTests().iterator().next(); assertThat(failedTest.getName()) .withFailMessage("The failed test should have had the suffix of [(failed)]") .isEqualTo("kungfu-panda-test(failed)"); runIncludedMethodsAssertion( failedTest.getClasses(), pairA.getTestClass(), pairA.getTestMethods()); runIncludedMethodsAssertion( failedTest.getClasses(), pairB.getTestClass(), pairB.getTestMethods()); } @DataProvider(name = "getTestData") public Object[][] getTestData() { return new Object[][] { { new ClassMethodInfo(TestClassWithBeforeTestSample.class, "beforeTest", "afterTest"), new ClassMethodInfo(TestClassWithJustTestMethodsSample.class, "test2Method") }, { new ClassMethodInfo(TestClassWithBeforeSuiteSample.class, "beforeSuite", "afterSuite"), new ClassMethodInfo(TestClassWithJustTestMethodsSample.class, "test2Method") }, { new ClassMethodInfo(TestClassWithBeforeGroupsSample.class, "beforeGroups", "afterGroups"), new ClassMethodInfo(TestClassWithJustTestMethodsSample.class, "test2Method") }, { new ClassMethodInfo( TestClassFailsAtBeforeGroupsWithBeforeGroupsSuiteTestSample.class, "beforeGroups", "afterGroups", "beforeTest", "afterTest", "beforeSuite", "afterSuite"), new ClassMethodInfo(TestClassWithJustTestMethodsSample.class, "test2Method") }, { new ClassMethodInfo( TestClassFailsAtBeforeSuiteWithBeforeGroupsSuiteTestSample.class, "beforeGroups", "afterGroups", "beforeTest", "afterTest", "beforeSuite", "afterSuite"), new ClassMethodInfo(TestClassWithJustTestMethodsSample.class, "test2Method") }, { new ClassMethodInfo( TestClassFailsAtBeforeTestWithBeforeGroupsSuiteTestSample.class, "beforeGroups", "afterGroups", "beforeTest", "afterTest", "beforeSuite", "afterSuite"), new ClassMethodInfo(TestClassWithJustTestMethodsSample.class, "test2Method") } }; } private static void runIncludedMethodsAssertion( List failedClasses, Class cls, String... methods) { XmlClass xmlClass = failedClasses.stream() .filter(each -> each.getName().equals(cls.getName())) .findFirst() .orElseThrow(() -> new IllegalStateException("Failed to locate " + cls.getName())); List includedMethods = xmlClass.getIncludedMethods().stream() .map(XmlInclude::getName) .collect(Collectors.toList()); assertThat(includedMethods) .withFailMessage( String.format( "Included methods:\n%s\n in class\n%s\n should match\n%s", String.join("\n", includedMethods), cls.getName(), String.join("\n", methods))) .containsExactlyInAnyOrder(methods); } public static class ClassMethodInfo { private final Class clazz; private final String[] testMethods; public ClassMethodInfo(Class clazz, String... testMethods) { this.clazz = clazz; this.testMethods = testMethods; } public Class getTestClass() { return clazz; } public String[] getTestMethods() { return testMethods; } @Override public String toString() { return String.format("%s->%s", clazz.toString(), Arrays.toString(testMethods)); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/GitHub1148Sample.java000066400000000000000000000005651475274123300301720ustar00rootroot00000000000000package test.reports; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class GitHub1148Sample { @DataProvider public Object[][] dp() { return new Object[][] {{"Cedric"}, {"Anne"}}; } @Test(dataProvider = "dp") public void verifyData(String n1) { Assert.assertEquals(n1, "Cedric"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/GitHub148Sample.java000066400000000000000000000006131475274123300301030ustar00rootroot00000000000000package test.reports; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class GitHub148Sample { @DataProvider public Object[][] dp() { return new Object[][] {{1}, {2}, {3}}; } @Test(dataProvider = "dp") public void testMethod(int test) { if (test == 3) { throw new RuntimeException("Test Case: " + test + " failed!"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/GitHub447Listener.java000066400000000000000000000015541475274123300304560ustar00rootroot00000000000000package test.reports; import java.util.ArrayList; import java.util.List; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class GitHub447Listener implements ITestListener { private final List parameters = new ArrayList<>(); @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) { parameters.add(result.getParameters()); } @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} public List getParameters() { return parameters; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/GitHub447Sample.java000066400000000000000000000015751475274123300301150ustar00rootroot00000000000000package test.reports; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class GitHub447Sample { @Test(dataProvider = "add") public void add(List list, Object e, String expected) { assertTrue(list.add(e)); assertEquals(list.toString(), expected); } @DataProvider(name = "add") protected static final Object[][] addTestData() { List list = new ArrayList<>(5); Object[][] testData = new Object[][] { {list, null, "[null]"}, {list, "dup", "[null, dup]"}, {list, "dup", "[null, dup, dup]"}, {list, "str", "[null, dup, dup, str]"}, {list, null, "[null, dup, dup, str, null]"}, }; return testData; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/Issue1566Sample.java000066400000000000000000000004761475274123300301050ustar00rootroot00000000000000package test.reports; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Issue1566Sample { @DataProvider public Object[][] dataProvider() { return new Object[][] {{"test \u000C"}}; } @Test(dataProvider = "dataProvider") public void test(String argument) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/Issue1659Sample.java000066400000000000000000000004041475274123300300770ustar00rootroot00000000000000package test.reports; import org.testng.annotations.Test; public class Issue1659Sample { @Test public void testMethod() { triggerExceptions(); } private void triggerExceptions() { throw new RuntimeException("simulating test failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ListenerReporterSample.java000066400000000000000000000011651475274123300317770ustar00rootroot00000000000000package test.reports; import org.testng.ITestContext; import org.testng.Reporter; import org.testng.TestListenerAdapter; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ListenerReporterSample.class) public class ListenerReporterSample extends TestListenerAdapter { @Override public void onStart(ITestContext testContext) { Reporter.log("foo"); super.onStart(testContext); } @Test public void testMethod() { Reporter.log( "bar"); // This line is required. Else the log that was triggered from onStart() would never // be // persisted at all. } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReportTest.java000066400000000000000000000240311475274123300274350ustar00rootroot00000000000000package test.reports; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.testng.*; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.reporters.FailedReporter; import org.testng.reporters.TestHTMLReporter; import org.testng.reporters.TextReporter; import org.testng.xml.XmlSuite; import org.testng.xml.internal.Parser; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.TestHelper; import test.reports.issue1756.CustomTestNGReporter; import test.reports.issue1756.SampleTestClass; import test.simple.SimpleSample; public class ReportTest extends SimpleBaseTest { @Test public void verifyIndex() throws IOException { Path outputDir = TestHelper.createRandomDirectory(); String suiteName = "VerifyIndexSuite"; String testName = "TmpTest"; XmlSuite suite = createXmlSuite(suiteName, testName, SimpleSample.class); TestNG tng = create(outputDir, suite); tng.addListener(new TestHTMLReporter()); Path f = getHtmlReportFile(outputDir, suiteName, testName); tng.run(); Assert.assertTrue(Files.exists(f), f.toString()); } @Test public void directoryShouldBeSuiteName() throws IOException { Path outputDirectory = TestHelper.createRandomDirectory(); String suiteName = "ReportTestSuite1"; String testName = "Test1"; String testName2 = "Test2"; XmlSuite xmlSuite = createXmlSuite(suiteName); createXmlTest(xmlSuite, testName); createXmlTest(xmlSuite, testName2); TestNG tng = create(outputDirectory, xmlSuite); tng.addListener(new TestHTMLReporter()); Path f = getHtmlReportFile(outputDirectory, suiteName, testName); Path f2 = getHtmlReportFile(outputDirectory, suiteName, testName2); tng.run(); Assert.assertTrue(Files.exists(f)); Assert.assertTrue(Files.exists(f2)); } @Test public void oneDirectoryPerSuite() throws IOException { Path outputDirectory = TestHelper.createRandomDirectory(); String suiteNameA = "ReportSuiteA"; String suiteNameB = "ReportSuiteB"; String testName = "TmpTest"; XmlSuite xmlSuiteA = createXmlSuite(suiteNameA, testName, SampleA.class); XmlSuite xmlSuiteB = createXmlSuite(suiteNameB, testName, SampleB.class); TestNG tng = create(outputDirectory, xmlSuiteA, xmlSuiteB); tng.addListener(new TestHTMLReporter()); Path f1 = getHtmlReportFile(outputDirectory, suiteNameA, testName); Path f2 = getHtmlReportFile(outputDirectory, suiteNameB, testName); tng.run(); Assert.assertTrue(Files.exists(f1)); Assert.assertTrue(Files.exists(f2)); } private static Path getHtmlReportFile(Path outputDir, String suiteName, String testName) throws IOException { Path f = outputDir.resolve(Paths.get(suiteName, testName + ".html")); Files.deleteIfExists(f); return f; } @Test public void shouldHonorSuiteName() throws IOException { Path outputDirectory = TestHelper.createRandomDirectory(); TestNG tng = create(outputDirectory, SampleA.class, SampleB.class); tng.addListener(new TestHTMLReporter()); Path fileA = outputDirectory.resolve("SuiteA-JDK5"); Path fileB = outputDirectory.resolve("SuiteB-JDK5"); Assert.assertTrue(Files.notExists(fileA)); Assert.assertTrue(Files.notExists(fileB)); tng.run(); Assert.assertTrue(Files.exists(fileA)); Assert.assertTrue(Files.exists(fileB)); } private static boolean m_success; @Test public void reportLogShouldBeAvailableEvenWithTimeOut() { m_success = false; TestNG tng = create(ReporterSample.class); ITestListener listener = new TestListenerAdapter() { @Override public void onTestSuccess(ITestResult tr) { super.onTestSuccess(tr); List output = Reporter.getOutput(tr); ReportTest.m_success = (output != null && output.size() > 0); } }; tng.addListener(listener); tng.run(); Assert.assertTrue(m_success); } @Test public void reportLogShouldBeAvailableWithListener() { TestNG tng = create(ListenerReporterSample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); Reporter.clear(); tng.run(); assertThat(listener.getFailedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).containsExactly("testMethod"); assertThat(Reporter.getOutput()).hasSize(2); } @Test(description = "GITHUB-1090") public void github1090() { TestNG tng = create(GitHub447Sample.class); GitHub447Listener reporter = new GitHub447Listener(); tng.addListener(reporter); tng.run(); List parameters = reporter.getParameters(); Assert.assertEquals(parameters.size(), 5); Assert.assertEquals(parameters.get(0)[0].toString(), "[]"); Assert.assertNull(parameters.get(0)[1]); Assert.assertEquals(parameters.get(0)[2].toString(), "[null]"); Assert.assertEquals(parameters.get(1)[0].toString(), "[null]"); Assert.assertEquals(parameters.get(1)[1], "dup"); Assert.assertEquals(parameters.get(1)[2].toString(), "[null, dup]"); Assert.assertEquals(parameters.get(2)[0].toString(), "[null, dup]"); Assert.assertEquals(parameters.get(2)[1], "dup"); Assert.assertEquals(parameters.get(2)[2].toString(), "[null, dup, dup]"); Assert.assertEquals(parameters.get(3)[0].toString(), "[null, dup, dup]"); Assert.assertEquals(parameters.get(3)[1], "str"); Assert.assertEquals(parameters.get(3)[2].toString(), "[null, dup, dup, str]"); Assert.assertEquals(parameters.get(4)[0].toString(), "[null, dup, dup, str]"); Assert.assertNull(parameters.get(4)[1]); Assert.assertEquals(parameters.get(4)[2].toString(), "[null, dup, dup, str, null]"); } @DataProvider public static Object[][] dp() { return new Object[][] { { GitHub1148Sample.class, new String[] {"verifyData(Cedric)"}, new String[] {"verifyData(Anne)"} }, { GitHub148Sample.class, new String[] {"testMethod(1)", "testMethod(2)"}, new String[] {"testMethod(3)"} } }; } @Test(dataProvider = "dp") public void runFailedTestTwiceShouldBeConsistent( Class testClass, String[] succeedMethods, String[] failedMethods) throws IOException { Path outputDirectory = TestHelper.createRandomDirectory(); TestNG tng = create(outputDirectory, testClass); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.addListener(new FailedReporter()); tng.run(); assertThat(listener.getFailedMethodNames()).containsExactly(failedMethods); assertThat(listener.getSucceedMethodNames()).containsExactly(succeedMethods); assertThat(listener.getSkippedMethodNames()).isEmpty(); Path testngFailedXml = outputDirectory.resolve(FailedReporter.TESTNG_FAILED_XML); assertThat(testngFailedXml).exists(); for (int i = 0; i < 5; i++) { testngFailedXml = checkFailed(testngFailedXml, failedMethods); } } @Test(description = "GITHUB-1756") public void testToEnsureSkippedTestsHaveProviderITestNameRetrieved() { TestNG testng = create(SampleTestClass.class); CustomTestNGReporter reporter = new CustomTestNGReporter(); testng.addListener(reporter); testng.run(); assertThat(reporter.getLogs()) .containsExactly(SampleTestClass.getUuid(), SampleTestClass.getUuid()); } private static Path checkFailed(Path testngFailedXml, String... failedMethods) throws IOException { Path outputDirectory = TestHelper.createRandomDirectory(); List suites = new Parser(Files.newInputStream(testngFailedXml)).parseToList(); TestNG tng = create(outputDirectory, suites); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.addListener(new FailedReporter()); tng.run(); assertThat(listener.getSucceedMethodNames()).isEmpty(); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).containsExactly(failedMethods); Path testngFailedXml2 = outputDirectory.resolve(FailedReporter.TESTNG_FAILED_XML); assertThat(testngFailedXml2).exists(); return testngFailedXml2; } public static class DpArrays { public enum Item { ITEM1, ITEM2 } @DataProvider public static Object[][] dpArrays() { return new Object[][] {{new Item[] {Item.ITEM1}}, {new Item[] {Item.ITEM1, Item.ITEM2}}}; } @Test(dataProvider = "dpArrays") public void testMethod(Item[] strings) {} } public static class NullParameter { @DataProvider public static Object[][] nullProvider() { return new Object[][] {{null, "Bazinga!"}}; } @Test(dataProvider = "nullProvider") public void testMethod(Object nullReference, String bazinga) {} } @Test public void reportArraysToString() { TestNG tng = create(DpArrays.class); tng.addListener(new TextReporter("name", 2)); PrintStream previousOut = System.out; ByteArrayOutputStream systemOutCapture = new ByteArrayOutputStream(); System.setOut(new PrintStream(systemOutCapture)); tng.run(); System.setOut(previousOut); Assert.assertTrue(systemOutCapture.toString().contains("testMethod([ITEM1])")); Assert.assertTrue(systemOutCapture.toString().contains("testMethod([ITEM1, ITEM2])")); } @Test public void reportCreatedWithNullParameter() { TestNG tng = create(NullParameter.class); tng.addListener(new TextReporter("name", 2)); PrintStream previousOut = System.out; ByteArrayOutputStream systemOutCapture = new ByteArrayOutputStream(); System.setOut(new PrintStream(systemOutCapture)); tng.run(); System.setOut(previousOut); Assert.assertTrue( systemOutCapture.toString().contains("PASSED: testMethod(null, \"Bazinga!\")")); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReporterLogFailureSample.java000066400000000000000000000005441475274123300322430ustar00rootroot00000000000000package test.reports; import org.testng.Reporter; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ReporterLogListener.class) public class ReporterLogFailureSample { @Test public void test_onFailure() { Reporter.log("Log from test_onFailure"); throw new RuntimeException("Intentionally failed"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReporterLogListener.java000066400000000000000000000012261475274123300312750ustar00rootroot00000000000000package test.reports; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.TestListenerAdapter; /** Listener that calls Reporter.log */ public class ReporterLogListener extends TestListenerAdapter { @Override public void onTestSuccess(ITestResult result) { Reporter.log("Listener: onTestSuccess"); super.onTestSuccess(result); } @Override public void onTestFailure(ITestResult result) { Reporter.log("Listener: onTestFailure"); super.onTestFailure(result); } @Override public void onTestSkipped(ITestResult result) { Reporter.log("Listener: onTestSkipped"); super.onTestSkipped(result); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReporterLogSkippedSample.java000066400000000000000000000006761475274123300322610ustar00rootroot00000000000000package test.reports; import org.testng.Reporter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ReporterLogListener.class) public class ReporterLogSkippedSample { @BeforeMethod public void beforeMethod() { throw new RuntimeException("Intentionally failed"); } @Test public void test_onSkip() { Reporter.log("Log from test_onSkip"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReporterLogSuccessSample.java000066400000000000000000000004541475274123300322640ustar00rootroot00000000000000package test.reports; import org.testng.Reporter; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ReporterLogListener.class) public class ReporterLogSuccessSample { @Test public void test_onSuccess() { Reporter.log("Log from test_onSuccess"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReporterLogTest.java000066400000000000000000000021701475274123300304260ustar00rootroot00000000000000package test.reports; import java.util.List; import org.testng.Assert; import org.testng.Reporter; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.SimpleBaseTest; /** Make sure that Reporter.log() in listeners don't get discarded. */ public class ReporterLogTest extends SimpleBaseTest { @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {ReporterLogSuccessSample.class, "Listener: onTestSuccess"}, new Object[] {ReporterLogSkippedSample.class, "Listener: onTestSkipped"}, new Object[] {ReporterLogFailureSample.class, "Listener: onTestFailure"} }; } @Test(dataProvider = "dp") public void shouldLogFromListener(Class testClass, String value) { TestNG tng = create(testClass); tng.run(); List output = Reporter.getOutput(); Assert.assertTrue(contains(output, value)); } private static boolean contains(List output, String logMessage) { for (String s : output) { if (s.contains(logMessage)) { return true; } } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/ReporterSample.java000066400000000000000000000010241475274123300302630ustar00rootroot00000000000000package test.reports; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** Regression test: if a timeOut is provided, getReporter(testResult) returns null. */ public class ReporterSample { @DataProvider(name = "dp") public Object[][] createParameters() { return new Object[][] {new Object[] {"param1"}, new Object[] {"param2"}}; } @Test(dataProvider = "dp", timeOut = 10000) public void report(String p) { Reporter.log("IN THE REPORTER: " + p); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/SampleA.java000066400000000000000000000002451475274123300266450ustar00rootroot00000000000000package test.reports; import org.testng.annotations.Test; @Test(suiteName = "SuiteA-JDK5", testName = "TestA-JDK5") public class SampleA { public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/SampleB.java000066400000000000000000000002141475274123300266420ustar00rootroot00000000000000package test.reports; import org.testng.annotations.Test; @Test(suiteName = "SuiteB-JDK5") public class SampleB { public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/SimpleFailedSample.java000066400000000000000000000002771475274123300310300ustar00rootroot00000000000000package test.reports; import org.testng.annotations.Test; public class SimpleFailedSample { @Test public void failed() { throw new RuntimeException("Failing intentionally"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/UniqueReporterInjectionSample1.java000066400000000000000000000005001475274123300333740ustar00rootroot00000000000000package test.reports; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(UniqueReporterInjectionTest.ReporterListenerForIssue1227.class) public class UniqueReporterInjectionSample1 { @Test public void testMethod() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/UniqueReporterInjectionSample2.java000066400000000000000000000005001475274123300333750ustar00rootroot00000000000000package test.reports; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(UniqueReporterInjectionTest.ReporterListenerForIssue1227.class) public class UniqueReporterInjectionSample2 { @Test public void testMethod() { Assert.assertTrue(true); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/UniqueReporterInjectionTest.java000066400000000000000000000024621475274123300330220ustar00rootroot00000000000000package test.reports; import java.util.List; import org.testng.*; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class UniqueReporterInjectionTest extends SimpleBaseTest { @Test public void testPruningOfDuplicateReporter() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); createXmlClass(xmlTest, UniqueReporterInjectionSample1.class); createXmlClass(xmlTest, UniqueReporterInjectionSample2.class); TestNG tng = create(xmlSuite); tng.setUseDefaultListeners(false); tng.addListener((ITestNGListener) new ReporterListenerForIssue1227()); tng.run(); // Since we have another reporting listener that is injected via the service loader file // reporting listeners size will now have to be three (because the ExitCodeListener is also a // reporter backed listener). Assert.assertEquals(tng.getReporters().size(), 3); Assert.assertEquals(ReporterListenerForIssue1227.counter, 1); } public static class ReporterListenerForIssue1227 implements IReporter { static int counter = 0; @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { counter++; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/XmlReporterTest.java000066400000000000000000000057051475274123300304540ustar00rootroot00000000000000package test.reports; import static org.assertj.core.api.Assertions.assertThat; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.UUID; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.reporters.RuntimeBehavior; import org.w3c.dom.Document; import test.SimpleBaseTest; import test.reports.issue2171.TestClassExample; public class XmlReporterTest extends SimpleBaseTest { @Test(description = "GITHUB-1566") public void testMethod() throws IOException { File file = runTest(Issue1566Sample.class); boolean flag = false; Pattern pattern = Pattern.compile("\\p{Cc}"); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { if (pattern.matcher(line).find()) { flag = true; } } } assertThat(flag).as("Should not have found a control character").isFalse(); } @Test(description = "GITHUB1659") public void ensureStackTraceHasLineFeedsTest() throws Exception { File file = runTest(Issue1659Sample.class); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "//full-stacktrace/text()"; String data = (String) xPath.compile(expression).evaluate(doc, XPathConstants.STRING); data = data.trim(); assertThat(data.split("\n").length) .as("Line feeds and carriage returns should not have been removed") .isGreaterThan(1); } @Test(description = "GITHUB-2171") public void ensureCustomisationOfReportIsSupported() throws Exception { File file = runTest(TestClassExample.class, "issue_2171.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "//test/class/test-method/file/@path"; String data = (String) xPath.compile(expression).evaluate(doc, XPathConstants.STRING); assertThat(data.trim()).isEqualTo("issue2171.html"); } private static File runTest(Class clazz) { return runTest(clazz, RuntimeBehavior.FILE_NAME); } private static File runTest(Class clazz, String fileName) { String suiteName = UUID.randomUUID().toString(); File fileLocation = createDirInTempDir(suiteName); TestNG testng = create(fileLocation.toPath(), clazz); testng.setUseDefaultListeners(true); testng.run(); return new File(fileLocation, fileName); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue1756/000077500000000000000000000000001475274123300261325ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue1756/CustomTestNGReporter.java000066400000000000000000000023271475274123300330630ustar00rootroot00000000000000package test.reports.issue1756; import java.util.LinkedList; import java.util.List; import org.testng.IReporter; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ITestContext; import org.testng.xml.XmlSuite; public class CustomTestNGReporter implements IReporter { private List logs = new LinkedList<>(); public List getLogs() { return logs; } public void generateReport( List xmlSuites, List suites, String outputDirectory) { getTestMehodSummary(suites); } private void getTestMehodSummary(List suites) { suites.forEach( iSuite -> iSuite .getResults() .values() .forEach( each -> { ITestContext testObj = each.getTestContext(); getTestMethodReport(testObj.getFailedTests()); getTestMethodReport(testObj.getSkippedTests()); getTestMethodReport(testObj.getPassedTests()); })); } private void getTestMethodReport(IResultMap testResultMap) { testResultMap.getAllResults().forEach(iTestResult -> logs.add(iTestResult.getName())); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue1756/SampleTestClass.java000066400000000000000000000011761475274123300320510ustar00rootroot00000000000000package test.reports.issue1756; import java.util.UUID; import org.testng.ITest; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(CustomTestNGReporter.class) public class SampleTestClass implements ITest { private static String uuid = UUID.randomUUID().toString(); public static String getUuid() { return uuid; } private String uri; public SampleTestClass() { this.uri = uuid; } @Test public void test1() { throw new RuntimeException("failed"); } @Test(dependsOnMethods = "test1") public void test2() {} public String getTestName() { return uri; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2069/000077500000000000000000000000001475274123300261305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2069/Dummy1.java000077500000000000000000000004441475274123300301540ustar00rootroot00000000000000package test.reports.issue2069; import junit.framework.Test; import junit.framework.TestSuite; public class Dummy1 extends TestSuite { public static Test suite() { final TestSuite suite = new TestSuite("Failing report"); suite.addTestSuite(Dummy3.class); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2069/Dummy2.java000077500000000000000000000002231475274123300301500ustar00rootroot00000000000000package test.reports.issue2069; import junit.framework.TestCase; public class Dummy2 extends TestCase { public void testScheduleDelete() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2069/Dummy3.java000077500000000000000000000005541475274123300301600ustar00rootroot00000000000000package test.reports.issue2069; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; public class Dummy3 extends TestCase { @Test public void testFails() { Assert.assertEquals("test3 assertion that will fail", "1", "2"); } @Test public void testSucceeds() { Assert.assertEquals("test3 assertion", "1", "1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2069/Dummy4.java000077500000000000000000000002051475274123300301520ustar00rootroot00000000000000package test.reports.issue2069; import org.testng.annotations.Test; public class Dummy4 { @Test public void testngTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2069/IssueTest.java000066400000000000000000000026441475274123300307310ustar00rootroot00000000000000package test.reports.issue2069; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { private PrintStream currentError = System.err; private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @BeforeMethod public void setup() throws UnsupportedEncodingException { PrintStream ps = new PrintStream(baos, true, "UTF-8"); System.setErr(ps); } @AfterMethod(alwaysRun = true) public void teardown() { System.setErr(currentError); } @Test public void ensureNoExceptionsAriseFromReporters() { XmlSuite xmlSuite = createXmlSuite("Not Failing TestSuite"); createXmlTest(xmlSuite, "TestngTest", Dummy4.class); createXmlTest(xmlSuite, "TestSuite", Dummy1.class).setJunit(true); createXmlTest(xmlSuite, "TestCase", Dummy2.class).setJunit(true); TestNG tng = create(xmlSuite); tng.setUseDefaultListeners(true); tng.run(); String data = new String(baos.toByteArray(), StandardCharsets.UTF_8); assertThat(data).doesNotContain("NullPointerException"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2171/000077500000000000000000000000001475274123300261225ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2171/MyExampleListener.java000066400000000000000000000012601475274123300323730ustar00rootroot00000000000000package test.reports.issue2171; import java.util.Properties; import org.testng.ITestResult; import org.testng.reporters.XMLReporter; import org.testng.reporters.XMLStringBuffer; public class MyExampleListener extends XMLReporter { @Override public String fileName() { return "issue_2171.xml"; } @Override public void addCustomTagsFor(XMLStringBuffer xmlBuffer, ITestResult testResult) { Properties props = new Properties(); for (String attributeName : testResult.getAttributeNames()) { props.setProperty("path", testResult.getAttribute(attributeName).toString()); xmlBuffer.push(attributeName, props); xmlBuffer.pop(attributeName); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2171/TestClassExample.java000066400000000000000000000006071475274123300322110ustar00rootroot00000000000000package test.reports.issue2171; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(MyExampleListener.class) public class TestClassExample { @Test public void testMethod() { ITestResult result = Reporter.getCurrentTestResult(); result.setAttribute("file", "issue2171.html"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2445/000077500000000000000000000000001475274123300261265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2445/FailureTestFactory.java000066400000000000000000000004171475274123300325520ustar00rootroot00000000000000package test.reports.issue2445; import org.testng.annotations.Factory; public class FailureTestFactory { @Factory public Object[] getTestClasses() { Object[] tests = new Object[2]; tests[0] = new Test1(); tests[1] = new Test2(); return tests; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2445/Test1.java000066400000000000000000000003001475274123300277620ustar00rootroot00000000000000package test.reports.issue2445; import org.testng.Assert; import org.testng.annotations.Test; public class Test1 { @Test public void test1() { Assert.fail("Simulate failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2445/Test2.java000066400000000000000000000003211475274123300277660ustar00rootroot00000000000000package test.reports.issue2445; import org.junit.Assert; import org.testng.annotations.Test; public class Test2 { @Test public void test2() { Assert.assertEquals("Simulate success", "1", "1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611/000077500000000000000000000000001475274123300261215ustar00rootroot00000000000000TestClassFailsAtBeforeGroupsWithBeforeGroupsSuiteTestSample.java000066400000000000000000000015401475274123300425740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public class TestClassFailsAtBeforeGroupsWithBeforeGroupsSuiteTestSample { @BeforeGroups(groups = {"dragon-warrior"}) public void beforeGroups() { Assert.fail(); } @AfterGroups(groups = {"dragon-warrior"}) public void afterGroups() {} @BeforeSuite(groups = {"dragon-warrior"}) public void beforeSuite() {} @AfterSuite(groups = {"dragon-warrior"}) public void afterSuite() {} @BeforeTest(groups = {"dragon-warrior"}) public void beforeTest() {} @AfterTest(groups = {"dragon-warrior"}) public void afterTest() {} } TestClassFailsAtBeforeSuiteWithBeforeGroupsSuiteTestSample.java000066400000000000000000000015371475274123300424140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public class TestClassFailsAtBeforeSuiteWithBeforeGroupsSuiteTestSample { @BeforeGroups(groups = {"dragon-warrior"}) public void beforeGroups() {} @AfterGroups(groups = {"dragon-warrior"}) public void afterGroups() {} @BeforeSuite(groups = {"dragon-warrior"}) public void beforeSuite() { Assert.fail(); } @AfterSuite(groups = {"dragon-warrior"}) public void afterSuite() {} @BeforeTest(groups = {"dragon-warrior"}) public void beforeTest() {} @AfterTest(groups = {"dragon-warrior"}) public void afterTest() {} } TestClassFailsAtBeforeTestWithBeforeGroupsSuiteTestSample.java000066400000000000000000000015361475274123300422410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; public class TestClassFailsAtBeforeTestWithBeforeGroupsSuiteTestSample { @BeforeGroups(groups = {"dragon-warrior"}) public void beforeGroups() {} @AfterGroups(groups = {"dragon-warrior"}) public void afterGroups() {} @BeforeSuite(groups = {"dragon-warrior"}) public void beforeSuite() {} @AfterSuite(groups = {"dragon-warrior"}) public void afterSuite() {} @BeforeTest(groups = {"dragon-warrior"}) public void beforeTest() { Assert.fail(); } @AfterTest(groups = {"dragon-warrior"}) public void afterTest() {} } TestClassWithBeforeGroupsSample.java000066400000000000000000000005641475274123300351400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.Assert; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; public class TestClassWithBeforeGroupsSample { @BeforeGroups(groups = {"dragon-warrior"}) public void beforeGroups() { Assert.fail(); } @AfterGroups(groups = {"dragon-warrior"}) public void afterGroups() {} } TestClassWithBeforeSuiteSample.java000066400000000000000000000005551475274123300347520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.Assert; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public class TestClassWithBeforeSuiteSample { @BeforeSuite(groups = {"dragon-warrior"}) public void beforeSuite() { Assert.fail(); } @AfterSuite(groups = {"dragon-warrior"}) public void afterSuite() {} } TestClassWithBeforeTestSample.java000066400000000000000000000005461475274123300346000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; public class TestClassWithBeforeTestSample { @BeforeTest(groups = {"dragon-warrior"}) public void beforeTest() { Assert.fail(); } @AfterTest(groups = {"dragon-warrior"}) public void afterTest() {} } TestClassWithJustTestMethodsSample.java000066400000000000000000000002771475274123300356500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/reports/issue2611package test.reports.issue2611; import org.testng.annotations.Test; public class TestClassWithJustTestMethodsSample { @Test(groups = {"dragon-warrior"}) public void test2Method() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/000077500000000000000000000000001475274123300256345ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/EventualSuccess.java000066400000000000000000000005701475274123300316150ustar00rootroot00000000000000package test.retryAnalyzer; import java.util.concurrent.atomic.AtomicBoolean; import org.testng.Assert; import org.testng.annotations.Test; public class EventualSuccess { private static final AtomicBoolean ranYet = new AtomicBoolean(false); @Test(retryAnalyzer = MyRetry.class) public void test() { if (!ranYet.getAndSet(true)) { Assert.fail(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/ExitCodeTest.java000066400000000000000000000023351475274123300310460ustar00rootroot00000000000000package test.retryAnalyzer; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class ExitCodeTest extends SimpleBaseTest { @Test public void exitsWithZeroOnSuccess() { TestNG tng = create(ImmediateSuccess.class); tng.run(); assertEquals(tng.getStatus(), 0); } @Test public void exitsWithNonzeroOnFailure() { TestNG tng = create(PersistentFailure.class); tng.run(); assertTrue(tng.getStatus() != 0); } @Test public void exitsWithZeroAfterSuccessfulRetry() { TestNG tng = create(EventualSuccess.class); tng.addListener((ITestNGListener) new TestResultPruner()); tng.run(); assertEquals(tng.getStatus(), 0); } @Test(description = "GITHUB-217") public void exitWithNonzeroOnSkips() { TestNG tng = create(Issue217TestClassSample.class); tng.run(); assertEquals(tng.getStatus(), 2); } @Test(description = "GITHUB-217") public void exitWithNonzeroOnSkips1() { TestNG tng = create(Issue217TestClassSampleWithOneDataProvider.class); tng.run(); assertEquals(tng.getStatus(), 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/FactoryTest.java000066400000000000000000000012201475274123300307410ustar00rootroot00000000000000package test.retryAnalyzer; import static org.testng.Assert.fail; import org.testng.ITest; import org.testng.annotations.Test; import org.testng.log4testng.Logger; public class FactoryTest implements ITest { private static final Logger log = Logger.getLogger(FactoryTest.class); public static int m_count = 0; private String name; public FactoryTest(String name) { this.name = name; } @Override public String getTestName() { return name; } @Test(retryAnalyzer = MyRetry.class) public void someTest1() { log.debug("Test Called : " + this.name); if (name.contains("5")) { m_count++; fail(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/ImmediateSuccess.java000066400000000000000000000002431475274123300317250ustar00rootroot00000000000000package test.retryAnalyzer; import org.testng.annotations.Test; public class ImmediateSuccess { @Test(retryAnalyzer = MyRetry.class) public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/InvocationCountTest.java000066400000000000000000000112141475274123300324600ustar00rootroot00000000000000package test.retryAnalyzer; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import com.google.common.collect.ConcurrentHashMultiset; import com.google.common.collect.Multiset; import java.util.concurrent.atomic.AtomicInteger; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * retryAnalyzer parameter unit tests. * * @author tocman@gmail.com (Jeremie Lenfant-Engelmann) */ public final class InvocationCountTest implements IRetryAnalyzer { static final Multiset invocations = ConcurrentHashMultiset.create(); private static final AtomicInteger retriesRemaining = new AtomicInteger(100); private static final int MAX_RETRY = 2; static int tcid1 = 0; static int tcid2 = 0; static int tcid3 = 0; private int r1 = 0; private int r2 = 1; private int r3 = 0; private int r7 = 0; private static int value = 42; private int executionNumber = 0; @Test(retryAnalyzer = InvocationCountTest.class) public void testAnnotationWithNoRetries() {} @Test(retryAnalyzer = InvocationCountTest.class) public void testAnnotationWithOneRetry() { if (r1++ < 1) { fail(); } } @Test(retryAnalyzer = InvocationCountTest.class) public void testAnnotationWithSevenRetries() { if (r7++ < 7) { fail(); } } @Test(retryAnalyzer = ThreeRetries.class, successPercentage = 0) public void failAfterThreeRetries() { fail(); } @Test( dependsOnMethods = { "testAnnotationWithNoRetries", "testAnnotationWithOneRetry", "testAnnotationWithSevenRetries", "failAfterThreeRetries" }, alwaysRun = true) public void checkInvocationCounts() { assertEquals(invocations.count("testAnnotationWithNoRetries"), 0); assertEquals(invocations.count("testAnnotationWithOneRetry"), 1); assertEquals(invocations.count("testAnnotationWithSevenRetries"), 7); assertEquals(invocations.count("failAfterThreeRetries"), 4); } @Test(retryAnalyzer = InvocationCountTest.class, dataProvider = "dataProvider3") public void retryWithDataProvider(String tc) { if ("tc1".equals(tc)) { if (tcid1++ < MAX_RETRY) { fail(); } } if ("tc2".equals(tc)) { if (tcid2++ < MAX_RETRY) { fail(); } } if ("tc3".equals(tc)) { if (tcid3++ < MAX_RETRY) { fail(); } } } @Test( dependsOnMethods = {"retryWithDataProvider"}, alwaysRun = true) public void checkRetryCounts() { assertEquals(tcid1, 3); assertEquals(tcid2, 3); assertEquals(tcid3, 3); } @DataProvider(name = "dataProvider") private Object[][] dataProvider() { return new Object[][] {{1, true}, {2, false}, {3, true}, {4, false}}; } @DataProvider(name = "dataProvider2") private Object[][] dataProvider2() { value = 42; return new Object[][] {{true}, {true}}; } @DataProvider(name = "dataProvider3") private Object[][] dataProvider3() { return new Object[][] {{"tc1"}, {"tc2"}, {"tc3"}}; } @Test(retryAnalyzer = InvocationCountTest.class, dataProvider = "dataProvider") public void testAnnotationWithDataProvider(int paf, boolean test) { executionNumber++; if (paf == 2 && test == false) { if (r2 >= 1) { r2--; fail(); } } if (paf == 4) { assertEquals(executionNumber, 5); } } @Test(retryAnalyzer = InvocationCountTest.class, dataProvider = "dataProvider2") public void testAnnotationWithDataProviderAndRecreateParameters(boolean dummy) { if (r3 == 1) { this.value = 0; r3--; fail(); } else if (r3 == 0) { assertEquals(this.value, 42); } } @Test public void withFactory() { TestNG tng = new TestNG(); tng.setTestClasses(new Class[] {MyFactory.class}); FactoryTest.m_count = 0; tng.run(); assertEquals(FactoryTest.m_count, 4); } @Override public boolean retry(ITestResult result) { invocations.add(result.getName()); return retriesRemaining.getAndDecrement() >= 0; } public static class ThreeRetries implements IRetryAnalyzer { private final AtomicInteger remainingRetries = new AtomicInteger(3); @Override public boolean retry(ITestResult result) { invocations.add(result.getName()); return remainingRetries.getAndDecrement() > 0; } } public static class RetryCountTest implements IRetryAnalyzer { private final AtomicInteger remainingRetries = new AtomicInteger(12); @Override public boolean retry(ITestResult result) { return remainingRetries.getAndDecrement() > 0; } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/Issue217TestClassSample.java000066400000000000000000000006521475274123300330140ustar00rootroot00000000000000package test.retryAnalyzer; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Issue217TestClassSample { @Test public void a() {} @Test(dataProvider = "dp") public void testMethod(int i) { Assert.assertTrue(i > 0); } @DataProvider(name = "dp") public Object[][] getData() { throw new RuntimeException("Simulating a failure"); } } Issue217TestClassSampleWithOneDataProvider.java000066400000000000000000000006371475274123300365430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzerpackage test.retryAnalyzer; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Issue217TestClassSampleWithOneDataProvider { @Test(dataProvider = "dp") public void testMethod(int i) { Assert.assertTrue(i > 0); } @DataProvider(name = "dp") public Object[][] getData() { throw new RuntimeException("Simulating a failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/MyFactory.java000066400000000000000000000005231475274123300304140ustar00rootroot00000000000000package test.retryAnalyzer; import org.testng.annotations.Factory; public class MyFactory { @Factory public Object[] createTests() { int num = 10; Object[] result = new Object[num]; for (int i = 0; i < num; i++) { FactoryTest obj = new FactoryTest("Test" + i); result[i] = obj; } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/MyRetry.java000066400000000000000000000005011475274123300301060ustar00rootroot00000000000000package test.retryAnalyzer; import org.testng.ITestResult; import org.testng.util.RetryAnalyzerCount; public class MyRetry extends RetryAnalyzerCount { public MyRetry() { setCount(3); } @Override public boolean retryMethod(ITestResult arg0) { // TODO Auto-generated method stub return true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/PersistentFailure.java000066400000000000000000000003241475274123300321460ustar00rootroot00000000000000package test.retryAnalyzer; import org.testng.Assert; import org.testng.annotations.Test; public class PersistentFailure { @Test(retryAnalyzer = MyRetry.class) public void test() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/RetryAnalyzerTest.java000066400000000000000000000300701475274123300321520ustar00rootroot00000000000000package test.retryAnalyzer; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.retryAnalyzer.dataprovider.issue2163.TestClassPoweredByDataProviderSample; import test.retryAnalyzer.github1519.MyListener; import test.retryAnalyzer.github1519.TestClassSample; import test.retryAnalyzer.github1600.Github1600Listener; import test.retryAnalyzer.github1600.Github1600TestSample; import test.retryAnalyzer.github1706.DataDrivenSample; import test.retryAnalyzer.github1706.NativeInjectionSample; import test.retryAnalyzer.github1706.ParameterInjectionSample; import test.retryAnalyzer.github2669.RetryTestSample; import test.retryAnalyzer.issue1241.GitHub1241Sample; import test.retryAnalyzer.issue1538.TestClassSampleWithTestMethodDependencies; import test.retryAnalyzer.issue1697.DatadrivenSample; import test.retryAnalyzer.issue1697.LocalReporter; import test.retryAnalyzer.issue1697.SampleTestclass; import test.retryAnalyzer.issue1946.RetryAnalyzer; import test.retryAnalyzer.issue1946.TestclassSample1; import test.retryAnalyzer.issue1946.TestclassSample2; import test.retryAnalyzer.issue2684.SampleTestClassWithGroupConfigs; public class RetryAnalyzerTest extends SimpleBaseTest { @Test public void testInvocationCounts() { TestNG tng = create(InvocationCountTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(new TestResultPruner()); tng.addListener(tla); tng.run(); assertThat(tla.getFailedTests()).isEmpty(); List fsp = tla.getFailedButWithinSuccessPercentageTests(); assertThat(fsp).hasSize(1); assertThat(fsp.get(0).getName()).isEqualTo("failAfterThreeRetries"); List skipped = tla.getSkippedTests(); assertThat(skipped).hasSize(InvocationCountTest.invocations.size() - fsp.size()); } @Test public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener(new MyListener()); tng.run(); assertThat(TestClassSample.messages) .containsExactly("afterInvocation", "retry", "afterInvocation"); } @Test(description = "GITHUB-1600") public void testIfRetryIsInvokedBeforeListenerButHasToConsiderFailures() { TestNG tng = create(Github1600TestSample.class); Github1600Listener listener = new Github1600Listener(); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener(tla); tng.addListener(listener); tng.run(); assertThat(tla.getFailedTests()).hasSize(1); assertThat(tla.getSkippedTests()).hasSize(1); } @Test(description = "GITHUB-1706", dataProvider = "1706") public void testIfRetryIsInvokedWhenTestMethodHas( Class clazz, int size, Map parameters) { XmlSuite xmlsuite = createXmlSuite("suite"); XmlTest xmlTest = createXmlTest(xmlsuite, "test", clazz); if (!parameters.isEmpty()) { xmlTest.setParameters(parameters); } TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(xmlsuite)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getSkippedMethodNames().size()).isEqualTo(size); } @DataProvider(name = "1706") public Object[][] getData() { return new Object[][] { {NativeInjectionSample.class, 2, Maps.newHashMap()}, {DataDrivenSample.class, 4, Maps.newHashMap()}, {ParameterInjectionSample.class, 2, constructParameterMap()} }; } @Test(description = "GITHUB-1538") public void testIfDependentMethodsAreInvokedWhenRetrySucceeds() { TestNG testng = create(TestClassSampleWithTestMethodDependencies.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertThat( tla.getPassedTests().stream() .map(RetryAnalyzerTest::methodName) .collect(Collectors.toList())) .containsExactly("a", "b"); assertThat(tla.getFailedTests()).isEmpty(); assertThat( tla.getSkippedTests().stream() .map(RetryAnalyzerTest::methodName) .collect(Collectors.toList())) .containsExactly("a"); } @Test(description = "GITHUB-1241") public void testToEnsureNewRetryAnalyzerInstanceUsedPerTest() { XmlSuite suite = createXmlSuite("Test Suite", "Test One", GitHub1241Sample.class); createXmlTest(suite, "Test Two", GitHub1241Sample.class); TestNG tng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener(listener); tng.run(); assertThat(listener.getInvokedMethodNames()) .containsExactly("test1", "test2", "test2", "test1", "test2", "test2"); } @Test(description = "GITHUB-1697") public void ensureRetriedMethodsAreDistinguishable() { XmlSuite xmlsuite = createXmlSuite("1697_suite"); createXmlTest(xmlsuite, "1697_test", SampleTestclass.class); TestNG testng = create(xmlsuite); LocalReporter reporter = new LocalReporter(); testng.addListener(reporter); testng.run(); runAssertions(reporter.getRetried(), "dataDrivenTest"); runAssertions(reporter.getSkipped(), "child"); } @Test public void ensureRetriedMethodsAreDistinguishableInDataDrivenTests() { XmlSuite xmlsuite = createXmlSuite("1697_suite"); createXmlTest(xmlsuite, "1697_test", DatadrivenSample.class); TestNG testng = create(xmlsuite); LocalReporter reporter = new LocalReporter(); testng.addListener(reporter); testng.run(); ITestResult firstResult = runAssertions(reporter.getRetried(), "testMethod"); assertThat(firstResult.getParameters()).containsAll(Collections.singletonList(1)); } @Test(description = "GITHUB-1946") public void ensureRetriesHappenForDataDrivenTests() { List expected = Arrays.asList( "Attempt #0. Retry :true Test method : " + TestclassSample1.class.getName() + ".test1(), Parameters : [param1, value1]", "Attempt #1. Retry :false Test method : " + TestclassSample1.class.getName() + ".test1(), Parameters : [param1, value1]", "Attempt #0. Retry :true Test method : " + TestclassSample1.class.getName() + ".test1(), Parameters : [param2, value2]", "Attempt #1. Retry :false Test method : " + TestclassSample1.class.getName() + ".test1(), Parameters : [param2, value2]", "Attempt #0. Retry :true Test method : " + TestclassSample1.class.getName() + ".test2(), Parameters : [param1, value1]", "Attempt #1. Retry :false Test method : " + TestclassSample1.class.getName() + ".test2(), Parameters : [param1, value1]", "Attempt #0. Retry :true Test method : " + TestclassSample1.class.getName() + ".test2(), Parameters : [param2, value2]", "Attempt #1. Retry :false Test method : " + TestclassSample1.class.getName() + ".test2(), Parameters : [param2, value2]", "Attempt #0. Retry :true Test method : " + TestclassSample2.class.getName() + ".test1(), Parameters : [param1, value1]", "Attempt #1. Retry :false Test method : " + TestclassSample2.class.getName() + ".test1(), Parameters : [param1, value1]", "Attempt #0. Retry :true Test method : " + TestclassSample2.class.getName() + ".test1(), Parameters : [param2, value2]", "Attempt #1. Retry :false Test method : " + TestclassSample2.class.getName() + ".test1(), Parameters : [param2, value2]", "Attempt #0. Retry :true Test method : " + TestclassSample2.class.getName() + ".test3(), Parameters : [param1, value1]", "Attempt #1. Retry :false Test method : " + TestclassSample2.class.getName() + ".test3(), Parameters : [param1, value1]", "Attempt #0. Retry :true Test method : " + TestclassSample2.class.getName() + ".test3(), Parameters : [param2, value2]", "Attempt #1. Retry :false Test method : " + TestclassSample2.class.getName() + ".test3(), Parameters : [param2, value2]", "Attempt #0. Retry :true Test method : " + TestclassSample2.class.getName() + ".test4(), Parameters : [param1, value1]", "Attempt #1. Retry :false Test method : " + TestclassSample2.class.getName() + ".test4(), Parameters : [param1, value1]", "Attempt #0. Retry :true Test method : " + TestclassSample2.class.getName() + ".test4(), Parameters : [param2, value2]", "Attempt #1. Retry :false Test method : " + TestclassSample2.class.getName() + ".test4(), Parameters : [param2, value2]"); XmlSuite xmlsuite = createXmlSuite("1946_suite"); createXmlTest(xmlsuite, "1946_test", TestclassSample1.class, TestclassSample2.class); TestNG testng = create(xmlsuite); testng.run(); assertThat(RetryAnalyzer.logs).containsExactlyElementsOf(expected); } @Test(description = "GITHUB-2163 & GITHUB-2280", timeOut = 5000) public void ensureRetryDoesntRunEndlesslyForDataDrivenTests() { XmlSuite xmlsuite = createXmlSuite("2163_suite"); createXmlTest(xmlsuite, "2163_test", TestClassPoweredByDataProviderSample.class); TestNG testng = create(xmlsuite); testng.run(); assertThat(test.retryAnalyzer.dataprovider.issue2163.RetryAnalyzer.logs).hasSize(21); } @Test(description = "GITHUB-2669") public void testFailedRetryWithParameters() { Map params = new HashMap<>(); params.put("id", "1111"); params.put("name", "qa"); params.put("age", "30"); XmlSuite suite = createXmlSuite("GITHUB_2669", params); createXmlTest(suite, "2669_Test", RetryTestSample.class); TestNG testng = create(suite); testng.run(); Assert.assertEquals(RetryTestSample.count, 3); } @Test(description = "GITHUB-2684") public void testAfterConfigurationsInvokedAfterRetriedMethod() { XmlSuite xmlSuite = createXmlSuite("2684_suite"); createXmlTest(xmlSuite, "2684_test", SampleTestClassWithGroupConfigs.class); createXmlGroups(xmlSuite, "2684_group"); TestNG testng = create(xmlSuite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); String[] expected = { "beforeSuite", "beforeTest", "beforeClass", "beforeGroups", "beforeMethod", "testMethod", "afterMethod", "beforeMethod", "testMethod", "afterMethod", "afterGroups", "afterClass", "afterTest", "afterSuite" }; assertThat(listener.getInvokedMethodNames()).containsExactly(expected); } private ITestResult runAssertions(Set results, String methodName) { assertThat(results).hasSize(1); ITestResult firstResult = results.iterator().next(); assertThat(firstResult.getMethod().getMethodName()).isEqualToIgnoringCase(methodName); return firstResult; } private static String methodName(ITestResult result) { return result.getMethod().getMethodName(); } private static Map constructParameterMap() { Map map = Maps.newHashMap(); map.put("counter", "3"); return map; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/TestResultPruner.java000066400000000000000000000017671475274123300320240ustar00rootroot00000000000000package test.retryAnalyzer; import java.util.Set; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.TestListenerAdapter; public class TestResultPruner extends TestListenerAdapter { @Override public void onFinish(ITestContext context) { for (ITestNGMethod method : context.getAllTestMethods()) { Set passed = context.getPassedTests().getResults(method); Set skipped = context.getSkippedTests().getResults(method); Set failed = context.getFailedTests().getResults(method); Set failedWithinSuccess = context.getFailedButWithinSuccessPercentageTests().getResults(method); if (!passed.isEmpty() && !skipped.isEmpty()) { context.getSkippedTests().removeResult(method); } if (((!failedWithinSuccess.isEmpty()) || (!failed.isEmpty())) && !skipped.isEmpty()) { context.getSkippedTests().removeResult(method); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataprovider/000077500000000000000000000000001475274123300303205ustar00rootroot00000000000000ComplexDataProviderWithObjectAndArraySample.java000066400000000000000000000017101475274123300415660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ComplexDataProviderWithObjectAndArraySample { private static int countWithObjectAndStringArrayForSuccess = 3; @DataProvider(name = "getObjectData") public Object[][] getObjectData() { return new Object[][] {new Object[] {false, "abc1", "cdf1"}}; } // Test retry-analyzer with complex data-provider end result as passed after 3 successful retry // attempts @Test(dataProvider = "getObjectData", retryAnalyzer = DataProviderRetryAnalyzer.class) public void test(boolean flag, String... values) { Assert.assertTrue( countWithObjectAndStringArrayForSuccess-- == 0, "Test execution is not" + "successful after 3 retry attempts configured in retryAnalyzer for this data " + values + "with boolean flag as " + flag); } } DataProviderRetryAnalyzer.java000066400000000000000000000015361475274123300362310ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class DataProviderRetryAnalyzer implements IRetryAnalyzer { private static final int MAX_RETRY_COUNT = 3; private final Map counts = new HashMap<>(); private AtomicInteger getCount(ITestResult result) { int id = Arrays.hashCode(result.getParameters()); AtomicInteger count = counts.get(id); if (count == null) { count = new AtomicInteger(MAX_RETRY_COUNT); counts.put(id, count); } return count; } @Override public boolean retry(ITestResult result) { int retriesRemaining = getCount(result).getAndDecrement(); return retriesRemaining > 0; } } DataProviderWithRetryAttemptsFailure.java000066400000000000000000000015741475274123300404130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderWithRetryAttemptsFailure { private static int countWithObjectAndStringArrayForFailure = 3; @DataProvider(name = "getObjectData") public Object[][] getObjectData() { return new Object[][] {new Object[] {false, "abc1", "cdf1"}}; } // Test retry-analyzer with end result as failed after 3 successful retry attempts @Test(dataProvider = "getObjectData", retryAnalyzer = DataProviderRetryAnalyzer.class) public void test(boolean flag, String... values) { Assert.assertTrue( flag, "Test execution is not" + "successful after 3 retry attempts configured in retryAnalyzer for this data " + values + "with boolean flag as " + flag); } } DataProviderWithSingleParam.java000066400000000000000000000031671475274123300364560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderWithSingleParam { private static int countWithSingleParam1 = 3; private static int countWithSingleParam2 = 3; @DataProvider(name = "getSingleParam", parallel = true) public Object[][] getSingleParam() { return new Integer[][] {new Integer[] {1}, new Integer[] {2}}; } // Test retry-analyzer with end result as passed after 3 successful retry attempts while passing 2 // integer array of objects individually with parallel as true. Since we have two integer arrays, // the number of // test-cases in this scenario are 2. Verify if tests are passing successfully after 3 successful // attempts each. @Test(dataProvider = "getSingleParam", retryAnalyzer = DataProviderRetryAnalyzer.class) public void test(int param) { // If the param is 1 then decrement the counter countWithSingleParam1 and assert true to check // if it is 0. if (param == 1) { Assert.assertTrue( countWithSingleParam1-- == 0, "Test execution is not" + "successful after 3 retry attempts configured in retryAnalyzer for this data " + param); } // If the param is 2 then decrement the counter countWithSingleParam2 and assert true to check // if it is 0. if (param == 2) { Assert.assertTrue( countWithSingleParam2-- == 0, "Test execution is not" + "successful after 3 retry attempts configured in retryAnalyzer for this data " + param); } } } DataProviderWithStringArraySample.java000066400000000000000000000015131475274123300376540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderWithStringArraySample { private static int countWithStringArray = 3; @DataProvider(name = "getTestData") public Object[][] getTestData() { return new String[][] {new String[] {"abc1", "cdf1"}}; } // Test with string array of objects in data-provider with end result as true after 3 successful // retry attempts @Test(dataProvider = "getTestData", retryAnalyzer = DataProviderRetryAnalyzer.class) public void test(String... values) { Assert.assertTrue( countWithStringArray-- == 0, "Test execution is not" + "successful after 3 retry attempts configured in retryAnalyzer for this data " + values); } } RetryAnalyzerWithComplexDataProviderTest.java000066400000000000000000000057711475274123300412620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import static org.testng.Assert.assertEquals; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class RetryAnalyzerWithComplexDataProviderTest extends SimpleBaseTest { // Test without data-provider with end result as success after 3 retry attempts @Test(description = "GITHUB-2148") public void testWithoutDataProvider() { TestNG testng = create(RetryAnalyzerWithoutDataProvider.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertEquals(tla.getPassedTests().size(), 1); assertEquals(tla.getFailedTests().size(), 0); assertEquals(tla.getSkippedTests().size(), 3); } // Test with string array of objects in data-provider with end result as success after 3 retry // attempts @Test(description = "GITHUB-2148") public void testWithDataProviderStringArray() { TestNG testng = create(DataProviderWithStringArraySample.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertEquals(tla.getPassedTests().size(), 1); assertEquals(tla.getFailedTests().size(), 0); assertEquals(tla.getSkippedTests().size(), 3); } // Test with multiple integer arrays in data-provider when parallel mode on and end result as // success // after 3 retry attempts @Test(description = "GITHUB-2148") public void testWithSingleParam() { TestNG testng = create(DataProviderWithSingleParam.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); // Since 2 integer arrays are passing inside data-provider, number of test cases should be 2 assertEquals(tla.getPassedTests().size(), 2); assertEquals(tla.getFailedTests().size(), 0); assertEquals( tla.getSkippedTests().size(), 6); // Number of total skipped count should be 6, each for a test } // Test with objects in data-provider with result as success after 3 retry attempts @Test(description = "GITHUB-2148") public void testWithDataProviderWithObjectAndArraySample() { TestNG testng = create(ComplexDataProviderWithObjectAndArraySample.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertEquals(tla.getPassedTests().size(), 1); assertEquals(tla.getFailedTests().size(), 0); assertEquals(tla.getSkippedTests().size(), 3); } // Test with objects in data-provider with result as failed after 3 retry attempts @Test(description = "GITHUB-2148") public void testDataProviderWithRetryAttemptsFailure() { TestNG testng = create(DataProviderWithRetryAttemptsFailure.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertEquals(tla.getFailedTests().size(), 1); assertEquals(tla.getPassedTests().size(), 0); assertEquals(tla.getSkippedTests().size(), 3); } } RetryAnalyzerWithDataProviderTest.java000066400000000000000000000014071475274123300377220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import static org.testng.Assert.assertEquals; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class RetryAnalyzerWithDataProviderTest extends SimpleBaseTest { @Test public void testRetryCounts() { TestNG tng = create(RetryCountTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); assertEquals(tla.getPassedTests().size(), 1); assertEquals(tla.getPassedTests().get(0).getParameters(), new String[] {"c"}); assertEquals(tla.getFailedTests().size(), 3); assertEquals(tla.getSkippedTests().size(), 9); } } RetryAnalyzerWithoutDataProvider.java000066400000000000000000000007131475274123300376110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import org.testng.Assert; import org.testng.annotations.Test; public class RetryAnalyzerWithoutDataProvider { private static int countWithoutDataProvider = 3; // Test retry-analyzer without data-provider with end result as passed after 3 successful retry // attempts @Test(retryAnalyzer = DataProviderRetryAnalyzer.class) public void test() { Assert.assertTrue(countWithoutDataProvider-- == 0); } } RetryCountTest.java000066400000000000000000000007311475274123300340630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataproviderpackage test.retryAnalyzer.dataprovider; import static org.testng.Assert.assertEquals; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public final class RetryCountTest { @DataProvider public Object[][] provider() { return new Object[][] {{"a"}, {"b"}, {"c"}, {"d"}}; } @Test(dataProvider = "provider", retryAnalyzer = DataProviderRetryAnalyzer.class) public void test1(String param) { assertEquals(param, "c"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataprovider/issue2163/000077500000000000000000000000001475274123300317645ustar00rootroot00000000000000RetryAnalyzer.java000066400000000000000000000010561475274123300353650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataprovider/issue2163package test.retryAnalyzer.dataprovider.issue2163; import java.util.List; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.collections.Lists; public class RetryAnalyzer implements IRetryAnalyzer { private static final int DEFAULT_MAX_RETRY_COUNT = 3; private int retryCount = 1; public static List logs = Lists.newArrayList(); @Override public boolean retry(ITestResult result) { logs.add("Executing " + result.getMethod().getMethodName()); return retryCount++ < DEFAULT_MAX_RETRY_COUNT; } } TestClassPoweredByDataProviderSample.java000066400000000000000000000013411475274123300417440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/dataprovider/issue2163package test.retryAnalyzer.dataprovider.issue2163; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestClassPoweredByDataProviderSample { @Test(retryAnalyzer = RetryAnalyzer.class, dataProvider = "dpNewObject") public void willNotStopAfter3Failures(Object... newObject) { Assert.fail("Kaboom!"); } @DataProvider public Object[][] dpNewObject() { return new Object[][] { {"String as parameter"}, {"int as parameter", 123}, {"boolean as parameter", true}, {"Boolean as parameter", true}, {"null parameter", null}, {new Object()}, // GITHUB-2163 {"GITHUB-2280", new Object[] {new Object()}}, }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1519/000077500000000000000000000000001475274123300274365ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1519/MyAnalyzer.java000077500000000000000000000005011475274123300323730ustar00rootroot00000000000000package test.retryAnalyzer.github1519; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class MyAnalyzer implements IRetryAnalyzer { @Override public boolean retry(ITestResult iTestResult) { TestClassSample.messages.add("retry"); TestClassSample.retry = true; return true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1519/MyListener.java000077500000000000000000000007261475274123300324040ustar00rootroot00000000000000package test.retryAnalyzer.github1519; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class MyListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {} @Override public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) { TestClassSample.messages.add("afterInvocation"); } } TestClassSample.java000077500000000000000000000006141475274123300332750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1519package test.retryAnalyzer.github1519; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.collections.Lists; public class TestClassSample { static boolean retry = false; public static List messages = Lists.newArrayList(); @Test(retryAnalyzer = MyAnalyzer.class) public void testMethod() { Assert.assertTrue(retry); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1600/000077500000000000000000000000001475274123300274255ustar00rootroot00000000000000Github1600Analyzer.java000077500000000000000000000013041475274123300334510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1600package test.retryAnalyzer.github1600; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class Github1600Analyzer implements IRetryAnalyzer { static final String RETRY = "RETRY"; public static final String NO = "NO"; static final String YES = "YES"; private static int retryCount = 0; private static final int MAX_RETRY_COUNT = 10; @Override public boolean retry(ITestResult iTestResult) { String attribute = (String) iTestResult.getAttribute(RETRY); if (NO.equalsIgnoreCase(attribute)) { return false; } else if (YES.equalsIgnoreCase(attribute) || retryCount < MAX_RETRY_COUNT) { retryCount++; return true; } return false; } } Github1600Listener.java000077500000000000000000000025441475274123300334600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1600package test.retryAnalyzer.github1600; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.ITestAnnotation; import org.testng.internal.annotations.DisabledRetryAnalyzer; public class Github1600Listener implements IInvokedMethodListener, IAnnotationTransformer { @Override public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {} @Override public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) { if (iInvokedMethod.isTestMethod()) { String attribute = Github1600Analyzer.NO; if (iTestResult.getStatus() == ITestResult.SUCCESS) { iTestResult.setStatus(ITestResult.FAILURE); attribute = Github1600Analyzer.YES; } iTestResult.setAttribute(Github1600Analyzer.RETRY, attribute); } } @Override public void transform( ITestAnnotation iTestAnnotation, Class aClass, Constructor constructor, Method method) { Class retry = iTestAnnotation.getRetryAnalyzerClass(); if (retry.equals(DisabledRetryAnalyzer.class)) { iTestAnnotation.setRetryAnalyzer(Github1600Analyzer.class); } } } Github1600TestSample.java000077500000000000000000000003661475274123300337540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1600package test.retryAnalyzer.github1600; import org.testng.Assert; import org.testng.annotations.Test; public class Github1600TestSample { private static int a = 2; @Test public void test1() { Assert.assertEquals(a, 2); a++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1706/000077500000000000000000000000001475274123300274345ustar00rootroot00000000000000DataDrivenSample.java000066400000000000000000000011761475274123300334100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1706package test.retryAnalyzer.github1706; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataDrivenSample { private AtomicInteger counter = new AtomicInteger(0); @Test(retryAnalyzer = LocalRetry.class, dataProvider = "getdata") public void testMethod(int i) { Assert.assertTrue(i > 0); if (counter.incrementAndGet() != 3) { Assert.fail(); } counter = new AtomicInteger(0); } @DataProvider(name = "getdata") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1706/LocalRetry.java000066400000000000000000000003561475274123300323630ustar00rootroot00000000000000package test.retryAnalyzer.github1706; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class LocalRetry implements IRetryAnalyzer { @Override public boolean retry(ITestResult result) { return true; } } NativeInjectionSample.java000066400000000000000000000007311475274123300344540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1706package test.retryAnalyzer.github1706; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.Test; public class NativeInjectionSample { private AtomicInteger counter = new AtomicInteger(0); @Test(retryAnalyzer = LocalRetry.class) public void testMethod(Method method) { Assert.assertNotNull(method); if (counter.incrementAndGet() != 3) { Assert.fail(); } } } ParameterInjectionSample.java000066400000000000000000000010121475274123300351370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github1706package test.retryAnalyzer.github1706; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ParameterInjectionSample { private AtomicInteger counter = new AtomicInteger(0); @Test(retryAnalyzer = LocalRetry.class) @Parameters({"counter"}) public void testMethod(int paramCounter) { Assert.assertTrue(paramCounter > 0); if (counter.incrementAndGet() != 3) { Assert.fail(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github2669/000077500000000000000000000000001475274123300274455ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github2669/FailedRetry.java000066400000000000000000000011341475274123300325210ustar00rootroot00000000000000package test.retryAnalyzer.github2669; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class FailedRetry implements IRetryAnalyzer { public static int retryCount = 1; private static final int maxRetryCount = 3; @Override public boolean retry(ITestResult iTestResult) { // If an exception is thrown, the failure case will be rerun. If it is an assertion error, try // again if (iTestResult.getThrowable() instanceof AssertionError && retryCount % maxRetryCount != 0) { retryCount++; return true; } retryCount = 1; return false; } } RetryTestSample.java000066400000000000000000000006671475274123300333510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/github2669package test.retryAnalyzer.github2669; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class RetryTestSample { public static int count = 0; @Parameters({"id", "name", "age"}) @Test(retryAnalyzer = FailedRetry.class) public void create(String id, String name, String age, ITestContext context) { count++; Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1241/000077500000000000000000000000001475274123300272745ustar00rootroot00000000000000GitHub1241Sample.java000066400000000000000000000004371475274123300327200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1241package test.retryAnalyzer.issue1241; import org.testng.Assert; import org.testng.annotations.Test; public class GitHub1241Sample { @Test(retryAnalyzer = MyRetry.class) public void test1() {} @Test(retryAnalyzer = MyRetry.class) public void test2() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1241/MyRetry.java000066400000000000000000000005771475274123300315630ustar00rootroot00000000000000package test.retryAnalyzer.issue1241; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class MyRetry implements IRetryAnalyzer { private int retryCount = 0; private int maxRetryCount = 1; @Override public boolean retry(ITestResult result) { if (retryCount < maxRetryCount) { retryCount++; return true; } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1538/000077500000000000000000000000001475274123300273055ustar00rootroot00000000000000RetryForIssue1538.java000066400000000000000000000003641475274123300332020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1538package test.retryAnalyzer.issue1538; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryForIssue1538 implements IRetryAnalyzer { @Override public boolean retry(ITestResult result) { return true; } } TestClassSampleWithTestMethodDependencies.java000066400000000000000000000006441475274123300403100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1538package test.retryAnalyzer.issue1538; import org.testng.Assert; import org.testng.annotations.Test; public class TestClassSampleWithTestMethodDependencies { private int i = 0; @Test(retryAnalyzer = RetryForIssue1538.class) public void a() { Assert.assertEquals(i++, 1); } @Test(dependsOnMethods = "a", retryAnalyzer = RetryForIssue1538.class) public void b() { Assert.assertEquals(i++, 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1697/000077500000000000000000000000001475274123300273135ustar00rootroot00000000000000DatadrivenSample.java000066400000000000000000000007741475274123300333320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1697package test.retryAnalyzer.issue1697; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DatadrivenSample { private boolean flag = true; @Test(dataProvider = "dp", retryAnalyzer = RetryForDataDrivenTest.class) public void testMethod(int data) { if (data == 1 && flag) { flag = false; Assert.fail(); } } @DataProvider(name = "dp") public Object[][] getData() { return new Object[][] {{1}, {2}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1697/LocalReporter.java000066400000000000000000000031521475274123300327340ustar00rootroot00000000000000package test.retryAnalyzer.issue1697; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestResult; import org.testng.collections.Maps; import org.testng.collections.Sets; import org.testng.xml.XmlSuite; public class LocalReporter implements IReporter { private Set skipped = Collections.newSetFromMap(Maps.newConcurrentMap()); private Set retried = Collections.newSetFromMap(Maps.newConcurrentMap()); @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { suites.stream() .map( suite -> { Set results = Sets.newHashSet(); Collection values = suite.getResults().values(); for (ISuiteResult value : values) { results.addAll(value.getTestContext().getSkippedTests().getAllResults()); } return results; }) .collect(Collectors.toSet()) .forEach( iTestResults -> { for (ITestResult iTestResult : iTestResults) { if (iTestResult.wasRetried()) { retried.add(iTestResult); } else { skipped.add(iTestResult); } } }); } public Set getRetried() { return retried; } public Set getSkipped() { return skipped; } } RetryForDataDrivenTest.java000066400000000000000000000005101475274123300344510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1697package test.retryAnalyzer.issue1697; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryForDataDrivenTest implements IRetryAnalyzer { private int counter = 0; @Override public boolean retry(ITestResult result) { if (counter++ < 2) { return true; } return false; } } SampleTestclass.java000066400000000000000000000006501475274123300332070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1697package test.retryAnalyzer.issue1697; import org.testng.Assert; import org.testng.annotations.Test; public class SampleTestclass { public static int counter = 0; @Test(retryAnalyzer = SimpleRetrier.class) public void dataDrivenTest() { if (counter++ != 1) { Assert.fail(); } } @Test public void parent() { Assert.fail(); } @Test(dependsOnMethods = "parent") public void child() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1697/SimpleRetrier.java000066400000000000000000000003601475274123300327430ustar00rootroot00000000000000package test.retryAnalyzer.issue1697; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class SimpleRetrier implements IRetryAnalyzer { @Override public boolean retry(ITestResult result) { return true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1946/000077500000000000000000000000001475274123300273105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1946/RetryAnalyzer.java000066400000000000000000000020521475274123300327650ustar00rootroot00000000000000package test.retryAnalyzer.issue1946; import java.util.Arrays; import java.util.List; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.collections.Lists; public class RetryAnalyzer implements IRetryAnalyzer { public static List logs = Lists.newArrayList(); private int retryCount = 0; private static final int MAX_RETRY_COUNT = 1; public boolean retry(ITestResult result) { String prefix = "Attempt #" + retryCount; if (retryCount < MAX_RETRY_COUNT) { if (result.getParameters().length > 0) { logs.add(prefix + ". Retry :true " + prettyMsg(result)); } retryCount++; return true; } logs.add(prefix + ". Retry :false " + prettyMsg(result)); return false; } private static String prettyMsg(ITestResult result) { return "Test method : " + result.getTestClass().getRealClass().getName() + "." + result.getMethod().getMethodName() + "()" + ", Parameters : " + Arrays.toString(result.getParameters()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1946/TestclassBase.java000066400000000000000000000010761475274123300327170ustar00rootroot00000000000000package test.retryAnalyzer.issue1946; import static org.testng.Assert.fail; import org.testng.Reporter; import org.testng.annotations.DataProvider; public class TestclassBase { @DataProvider public Object[][] dp() { return new Object[][] { {"param1", "value1"}, {"param2", "value2"} }; } static void performTest(String username, String password) { String method = Reporter.getCurrentTestResult().getMethod().getMethodName(); String txt = String.format("%s() Assertion for (%s, %s)", method, username, password); fail(txt); } } TestclassSample1.java000066400000000000000000000007141475274123300332660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1946package test.retryAnalyzer.issue1946; import org.testng.annotations.Test; public class TestclassSample1 extends TestclassBase { @Test(dataProvider = "dp", retryAnalyzer = RetryAnalyzer.class) public void test1(String username, String password) { performTest(username, password); } @Test(dataProvider = "dp", retryAnalyzer = RetryAnalyzer.class) public void test2(String username, String password) { performTest(username, password); } } TestclassSample2.java000066400000000000000000000011601475274123300332630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue1946package test.retryAnalyzer.issue1946; import org.testng.annotations.Test; public class TestclassSample2 extends TestclassBase { @Test(dataProvider = "dp", retryAnalyzer = RetryAnalyzer.class) public void test1(String username, String password) { performTest(username, password); } @Test(dataProvider = "dp", retryAnalyzer = RetryAnalyzer.class) public void test3(String username, String password) { performTest(username, password); } @Test(dataProvider = "dp", retryAnalyzer = RetryAnalyzer.class) public void test4(String username, String password) { performTest(username, password); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2148/000077500000000000000000000000001475274123300273035ustar00rootroot00000000000000ExceptionAfterMethodTestSample.java000066400000000000000000000023201475274123300361470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2148package test.retryAnalyzer.issue2148; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ExceptionAfterMethodTestSample { static final AtomicInteger counter = new AtomicInteger(0); static final List logs = new ArrayList<>(); @BeforeMethod(alwaysRun = true) public void beforeMethod(ITestResult method) { logs.add( "Before Method [" + method.getMethod().getMethodName() + "] #" + counter.incrementAndGet()); } @Test(alwaysRun = true, retryAnalyzer = RetryAnalyzer.class) public void testMethod() { ITestResult method = Reporter.getCurrentTestResult(); logs.add("Test Method [" + method.getMethod().getMethodName() + "] #" + counter.get()); Assert.fail(); } @AfterMethod(alwaysRun = true) public void afterMethod(ITestResult method) { logs.add("Before Method [" + method.getMethod().getMethodName() + "] #" + counter.get()); throw new RuntimeException("Simulating a failure in AfterMethod"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2148/IssueTest.java000066400000000000000000000016501475274123300321000ustar00rootroot00000000000000package test.retryAnalyzer.issue2148; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite.FailurePolicy; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(description = "GITHUB-2148") public void ensureTestsAreRetriedWhenConfigFailurePolicySetToContinue() { TestNG testng = create(ExceptionAfterMethodTestSample.class); testng.setConfigFailurePolicy(FailurePolicy.CONTINUE); testng.run(); String[] expected = new String[] { "Before Method [testMethod] #1", "Test Method [testMethod] #1", "Before Method [testMethod] #1", "Before Method [testMethod] #2", "Test Method [testMethod] #2", "Before Method [testMethod] #2" }; assertThat(ExceptionAfterMethodTestSample.logs).containsExactly(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2148/RetryAnalyzer.java000066400000000000000000000005661475274123300327700ustar00rootroot00000000000000package test.retryAnalyzer.issue2148; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryAnalyzer implements IRetryAnalyzer { private int counter = 0; private int retryLimit = 1; @Override public boolean retry(ITestResult result) { if (counter < retryLimit) { counter++; return true; } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2684/000077500000000000000000000000001475274123300273105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2684/RerunAnalyzer.java000066400000000000000000000007041475274123300327550ustar00rootroot00000000000000package test.retryAnalyzer.issue2684; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RerunAnalyzer implements IRetryAnalyzer { public static final int maxRetryCount = 1; public static int secondTestRetryCount = 0; private int retryCount = 0; @Override public boolean retry(ITestResult iTestResult) { if (retryCount < maxRetryCount) { retryCount++; return true; } return false; } } SampleTestClassWithGroupConfigs.java000066400000000000000000000026631475274123300363340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/retryAnalyzer/issue2684package test.retryAnalyzer.issue2684; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class SampleTestClassWithGroupConfigs { @BeforeSuite(alwaysRun = true) public void beforeSuite() {} @BeforeTest(alwaysRun = true) public void beforeTest() {} @BeforeGroups("2684_group") public void beforeGroups() {} @BeforeClass(alwaysRun = true) public void beforeClass() {} @BeforeMethod(alwaysRun = true) public void beforeMethod() {} @Test(groups = "2684_group", retryAnalyzer = RerunAnalyzer.class) public void testMethod() { RerunAnalyzer.secondTestRetryCount++; assertTrue(RerunAnalyzer.secondTestRetryCount > RerunAnalyzer.maxRetryCount); } @AfterMethod(alwaysRun = true) public void afterMethod() {} @AfterClass(alwaysRun = true) public void afterClass() {} @AfterGroups("2684_group") public void afterGroups() {} @AfterTest(alwaysRun = true) public void afterTest() {} @AfterSuite(alwaysRun = true) public void afterSuite() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/000077500000000000000000000000001475274123300242425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/AfterClassCalledAtEnd.java000066400000000000000000000031001475274123300311470ustar00rootroot00000000000000package test.sample; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Check to see that AfterClass is called only at the end and that after methods are called in * reverse order of the before methods. */ public class AfterClassCalledAtEnd extends BaseAfterClassCalledAtEnd { boolean m_before1Class = false; boolean m_test1 = false; boolean m_test2 = false; boolean m_test3 = false; @BeforeClass(groups = {"before1Class"}) public void before1Class() { m_before1Class = true; } @AfterClass(groups = {"someGroup"}) public void afterClass() { m_afterClass = true; assert m_test1 && m_test2 && m_test3 : "One of the test methods was not invoked: " + m_test1 + " " + m_test2 + " " + m_test3; } @Test(description = "Verify that beforeClass and afterClass are called correctly") public void test1() { m_test1 = true; assert m_before1Class : "beforeClass configuration must be called before method"; assert !m_afterClass : "afterClass configuration must not be called before test method"; } @Test public void test2() { m_test2 = true; assert m_before1Class : "beforeClass configuration must be called before method"; assert !m_afterClass : "afterClass configuration must not be called before test method"; } @Test public void test3() { m_test3 = true; assert m_before1Class : "beforeClass configuration must be called before method"; assert !m_afterClass : "afterClass configuration must not be called before test method"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/AllJUnitTests.java000066400000000000000000000006471475274123300276210ustar00rootroot00000000000000package test.sample; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the suite() functionality of TestNG * * @author Cedric Beust, May 5, 2004 */ public class AllJUnitTests { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new JUnitSample1(JUnitSample1.EXPECTED1)); suite.addTest(new JUnitSample2(JUnitSample2.EXPECTED)); return suite; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/BaseAfterClassCalledAtEnd.java000066400000000000000000000004651475274123300317550ustar00rootroot00000000000000package test.sample; import org.testng.annotations.AfterClass; public class BaseAfterClassCalledAtEnd { protected boolean m_afterClass = false; @AfterClass(dependsOnGroups = {".*"}) public void baseAfterClass() { assert m_afterClass : "This afterClass method should have been called last"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/BaseSample1.java000066400000000000000000000002701475274123300272010ustar00rootroot00000000000000package test.sample; import org.testng.annotations.Test; /** @author Cedric Beust, Apr 30, 2004 */ public class BaseSample1 { @Test(groups = {"odd"}) public void method1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/BaseSampleInheritance.java000066400000000000000000000022371475274123300312770ustar00rootroot00000000000000package test.sample; import java.util.ArrayList; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** @author Cedric Beust, Apr 30, 2004 */ public class BaseSampleInheritance { protected List m_configurations = new ArrayList<>(); protected void addConfiguration(String c) { m_configurations.add(c); } protected boolean m_invokedBaseMethod = false; @Test(groups = {"inheritedTestMethod"}) public void baseMethod() { m_invokedBaseMethod = true; } protected boolean m_invokedBaseConfiguration = false; @BeforeClass(alwaysRun = true) public void baseConfiguration() { m_invokedBaseConfiguration = true; } @BeforeClass( groups = {"configuration1"}, dependsOnGroups = {"configuration0"}) public void configuration1() { // System.out.println("CONFIGURATION 1"); addConfiguration("configuration1"); } @Test(dependsOnGroups = {"inheritedTestMethod"}) public void testBooleans() { assert m_invokedBaseMethod : "Didn't invoke test method in base class"; assert m_invokedBaseConfiguration : "Didn't invoke configuration method in base class"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/Basic1.java000066400000000000000000000007311475274123300262100ustar00rootroot00000000000000package test.sample; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Basic1 { private static int m_count = 0; public static void incrementCount() { m_count++; } public static int getCount() { return m_count; } @BeforeMethod public void beforeTestMethod() { incrementCount(); } @Test(groups = {"basic1"}) public void basic1() { assert getCount() > 0 : "COUNT WAS NOT INCREMENTED"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/Basic2.java000066400000000000000000000014201475274123300262050ustar00rootroot00000000000000package test.sample; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; public class Basic2 { private boolean m_basic2WasRun = false; private static int m_afterClass = 0; @Test(dependsOnGroups = {"basic1"}) public void basic2() { m_basic2WasRun = true; assert Basic1.getCount() > 0 : "COUNT WAS NOT INCREMENTED"; } @AfterTest public void cleanUp() { m_basic2WasRun = false; m_afterClass = 0; } @AfterClass public void checkTestAtClassLevelWasRun() { m_afterClass++; assert m_basic2WasRun : "Class annotated with @Test didn't have its methods run."; assert 1 == m_afterClass : "After class should have been called exactly once, not " + m_afterClass; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/ConverterSample3.java000066400000000000000000000035541475274123300303100ustar00rootroot00000000000000package test.sample; /* * Created on 12-Sep-2006 by micheb10 */ /** * Sample file for the Javadoc annotations to Java 5 annotations converter for a non-default package * * @author micheb10 12-Sep-2006 * @testng.test */ public class ConverterSample3 { /** * This comment line should be preserved * * @testng.before-suite alwaysRun = "true" */ public void beforeSuiteAlwaysRun() { // We are just checking appropriate annotations are added so we don't care about body } /** @testng.test */ public void plainTest() { // Empty body } /** * @testng.test * @testng.expected-exceptions value = "java.lang.NullPointerException * java.lang.NumberFormatException" */ public void expectedExceptions() { // Empty body } /** @testng.test groups = "groupA groupB" */ public void testGroups() { // Empty body } /** @testng.after-method */ public void afterMethod() { // Empty body } /** * This key should be preserved * * @author The author is a standard tag and should not be touched * @testng.test groups = "groupA" alwaysRun=true dependsOnMethods = "expectedExceptions" * timeOut="3000" * @version another standard tag should not be changed * @testng.expected-exceptions value = "java.lang.NullPointerException * java.lang.NumberFormatException" * @testng.parameters value="firstParameter secondParameter thirdParameter" */ public void testEverything() { // Lots and lots of stuff } /** @testng.data-provider name="test1" */ public Object[][] dataProvider() { return null; } /** @testng.factory */ public Object[] factory() { return null; } /** @testng.test */ public class TestInnerClass { public void bareInnerMethod() { // Empty body } /** @testng.test */ public void testInnerMethod() { // empty body } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/InvocationCountTest.java000066400000000000000000000035011475274123300310660ustar00rootroot00000000000000package test.sample; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterSuite; import org.testng.annotations.Test; /** * This class is used to test invocationCountTest * * @author cbeust */ public class InvocationCountTest { // // Invocation test // private static int m_count = 0; @AfterSuite(groups = {"invocationOnly"}) public void afterSuite() { m_count = 0; m_count2 = 0; m_count3 = 0; } @Test( groups = {"invocationOnly"}, invocationCount = 10) public void tenTimesShouldSucceed() { m_count++; } // // Invocation + Success percentage test // This method will work the first 8 times and fail after that, but overall // the test should still pass because successPercentage = 80 // private static int m_count2 = 0; @Test( groups = {"successPercentageThatSucceedsOnly"}, invocationCount = 10, successPercentage = 80) public void successPercentageShouldSucceed() { if (m_count2 >= 8) { throw new RuntimeException("Called more than eight times : " + m_count2); } m_count2++; } // // Invocation + Success percentage test // This method will work the first 8 times and fail after that. One of // the failures will fall under the percentage tolerance but the next one // will not. // private static int m_count3 = 0; @Test( groups = {"successPercentageThatFailsOnly"}, invocationCount = 10, successPercentage = 90) public void successPercentageShouldFail() { if (m_count3 >= 8) { throw new RuntimeException("Called more than eight times : " + m_count3); } m_count3++; } @AfterClass(groups = {"invocationOnly"}) public void verify() { assert 10 == m_count : "Method should have been invoked 10 times but was invoked " + m_count + " times"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/JUnitSample1.java000066400000000000000000000011351475274123300273610ustar00rootroot00000000000000package test.sample; import junit.framework.TestCase; /** * This class * * @author Cedric Beust, May 5, 2004 */ public class JUnitSample1 extends TestCase { private String m_field = null; public static final String EXPECTED2 = "testSample1_2"; public static final String EXPECTED1 = "testSample1_1"; public JUnitSample1() { super(); } public JUnitSample1(String n) { super(n); } @Override public void setUp() { m_field = "foo"; } @Override public void tearDown() { m_field = null; } public void testSample1_1() {} public void testSample1_2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/JUnitSample2.java000066400000000000000000000010201475274123300273530ustar00rootroot00000000000000package test.sample; import junit.framework.TestCase; /** * This class * * @author Cedric Beust, May 5, 2004 */ public class JUnitSample2 extends TestCase { public static final String EXPECTED = "testSample2ThatSetUpWasRun"; private String m_field = null; public JUnitSample2() { super(); } public JUnitSample2(String n) { super(n); } @Override public void setUp() { m_field = "foo"; } public void testSample2ThatSetUpWasRun() { assert null != m_field : "setUp() wasn't run"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/JUnitSample3.java000066400000000000000000000006311475274123300273630ustar00rootroot00000000000000package test.sample; import junit.framework.TestCase; import org.testng.Assert; /** * This class verifies that a new instance is used every time * * @author cbeust */ public class JUnitSample3 extends TestCase { private int m_count = 0; public void test1() { Assert.assertEquals(m_count, 0); m_count++; } public void test2() { Assert.assertEquals(m_count, 0); m_count++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/JUnitSample4.java000066400000000000000000000011771475274123300273720ustar00rootroot00000000000000package test.sample; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.Assert; /** @author lukas */ public abstract class JUnitSample4 extends TestCase { private int i = 0; public JUnitSample4(String name, int i) { super(name); this.i = i; } public void testXY() { Assert.assertEquals(1, 1); } public static TestSuite suite() { TestSuite ts = new TestSuite("Sample Suite"); for (int i = 0; i < 3; i++) { ts.addTest(new T(i)); } return ts; } private static class T extends JUnitSample4 { public T(int i) { super("testXY", i); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/PartialGroupTest.java000066400000000000000000000016141475274123300303600ustar00rootroot00000000000000package test.sample; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This class tests groups that are partially defined at the class level and then augmented at the * method level. * * @author cbeust */ @Test(groups = {"classGroup"}) public class PartialGroupTest { public static boolean m_successMethod = false; public static boolean m_successClass = false; @BeforeClass public void init() { m_successMethod = false; m_successClass = false; } @Test(groups = {"methodGroup"}) public void testMethodGroup() { m_successMethod = true; } @Test public void testClassGroupShouldFail() { Assert.assertTrue(false); } @Test(groups = {"methodGroup"}) public void testMethodGroupShouldFail() { Assert.assertTrue(false); } @Test public void testClassGroup() { m_successClass = true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/PartialGroupVerification.java000066400000000000000000000005351475274123300320640ustar00rootroot00000000000000package test.sample; import org.testng.annotations.Test; /** * This class verifies the PartialGroupTest * * @author cbeust */ public class PartialGroupVerification { @Test public void verify() { assert PartialGroupTest.m_successMethod && PartialGroupTest.m_successClass : "test1 and test2 should have been invoked both"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/README.txt000066400000000000000000000002331475274123300257360ustar00rootroot00000000000000This directory contains "samples": TestNG tests that are not invoked directly but invoked programmatically by the real test classes in the main directory. jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/Sample1.java000066400000000000000000000027031475274123300264110ustar00rootroot00000000000000package test.sample; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * This class * * @author Cedric Beust, Apr 26, 2004 */ public class Sample1 extends BaseSample1 { @AfterClass public static void tearDownClass1() {} @AfterClass public void tearDownClass2() {} @BeforeMethod public void beforeTest() {} @AfterMethod public void afterTest() {} @Test(groups = {"even"}) public void method2() {} @Test(groups = {"odd"}) public void method3() {} @Test( groups = {"odd"}, enabled = false) public void oddDisableMethod() {} @Test(groups = {"broken"}) public void broken() {} @Test( groups = {"fail"}, expectedExceptions = {NumberFormatException.class, ArithmeticException.class}) public void throwExpectedException1ShouldPass() { throw new NumberFormatException(); } @Test( groups = {"fail"}, expectedExceptions = {NumberFormatException.class, ArithmeticException.class}) public void throwExpectedException2ShouldPass() { throw new ArithmeticException(); } @Test(groups = {"fail", "bug"}) public void throwExceptionShouldFail() { throw new NumberFormatException(); } @Test(groups = {"assert"}) public void verifyLastNameShouldFail() { Assert.assertEquals("Beust", "", "Expected name Beust, found blah"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/Sample2.java000066400000000000000000000007161475274123300264140ustar00rootroot00000000000000package test.sample; import org.testng.annotations.Test; /** * This class * * @author Cedric Beust, Apr 26, 2004 */ public class Sample2 { @Test(groups = "g1") public void method1() { // System.out.println("@@@@@@@@@@@@@@@@@@@ METHOD1"); } @Test public void method2() { // System.out.println("@@@@@@@@@@@@@@@@@@@ METHOD2"); } @Test public void method3() { // System.out.println("@@@@@@@@@@@@@@@@@@@ METHOD3"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/Scope.java000066400000000000000000000007531475274123300261630ustar00rootroot00000000000000package test.sample; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** This class tests paramete scopes. */ public class Scope { @Parameters({"parameter"}) @Test(groups = {"outer-group"}) public void outerDeprecated(String s) { assert "out".equals(s) : "Expected out got " + s; } @Parameters({"parameter"}) @Test(groups = {"inner-group"}) public void innerDeprecated(String s) { assert "in".equals(s) : "Expected in got " + s; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sample/SetUpWithParameterTest.java000066400000000000000000000005161475274123300315040ustar00rootroot00000000000000package test.sample; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This class fails in setUp and should result in 1 failure, 1 skip * * @author cbeust */ public class SetUpWithParameterTest { @BeforeClass public void setUp(String bogusParameter) {} @Test public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sanitycheck/000077500000000000000000000000001475274123300252665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sanitycheck/CheckSuiteNamesTest.java000066400000000000000000000054431475274123300320120ustar00rootroot00000000000000package test.sanitycheck; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; public class CheckSuiteNamesTest extends SimpleBaseTest { /** Child suites have different names */ @Test public void checkChildSuites() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); String testngXmlPath = getPathToResource("sanitycheck/test-s-b.xml"); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 4); } /** Child suites have same names */ @Test public void checkChildSuitesFails() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); String testngXmlPath = getPathToResource("sanitycheck/test-s-a.xml"); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getTestContexts().get(0).getSuite().getName(), "SanityCheck suites"); Assert.assertEquals(tla.getTestContexts().get(1).getSuite().getName(), "SanityCheck suites"); Assert.assertEquals( tla.getTestContexts().get(2).getSuite().getName(), "SanityCheck suites (0)"); Assert.assertEquals( tla.getTestContexts().get(3).getSuite().getName(), "SanityCheck suites (0)"); } /** Checks that suites created programmatically also works as expected */ @Test public void checkProgrammaticSuitesFails() { XmlSuite xmlSuite1 = new XmlSuite(); xmlSuite1.setName("SanityCheckSuite"); { XmlTest result = new XmlTest(xmlSuite1); result.getXmlClasses().add(new XmlClass(SampleTest1.class.getCanonicalName())); } XmlSuite xmlSuite2 = new XmlSuite(); xmlSuite2.setName("SanityCheckSuite"); { XmlTest result = new XmlTest(xmlSuite2); result.getXmlClasses().add(new XmlClass(SampleTest2.class.getCanonicalName())); } TestNG tng = create(); tng.setXmlSuites(Arrays.asList(xmlSuite1, xmlSuite2)); tng.run(); Assert.assertEquals(xmlSuite1.getName(), "SanityCheckSuite"); Assert.assertEquals(xmlSuite2.getName(), "SanityCheckSuite (0)"); } @Test public void checkXmlSuiteAddition() throws IOException { TestNG tng = create(); String testngXmlPath = getPathToResource("sanitycheck/test-s-b.xml"); Parser parser = new Parser(testngXmlPath); tng.setXmlSuites(parser.parseToList()); tng.initializeSuitesAndJarFile(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sanitycheck/CheckTestNamesTest.java000066400000000000000000000054261475274123300316410ustar00rootroot00000000000000package test.sanitycheck; import java.util.Collections; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class CheckTestNamesTest extends SimpleBaseTest { /** Child suites and same suite has two tests with same name */ @Test public void checkWithChildSuites() { runSuite("sanitycheck/test-a.xml"); } /** Simple suite with two tests with same name */ @Test public void checkWithoutChildSuites() { runSuite("sanitycheck/test1.xml"); } private void runSuite(String suitePath) { TestListenerAdapter tla = new TestListenerAdapter(); boolean exceptionRaised = false; try { TestNG tng = create(); String testngXmlPath = getPathToResource(suitePath); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener((ITestNGListener) tla); tng.run(); } catch (TestNGException ex) { exceptionRaised = true; Assert.assertEquals(tla.getPassedTests().size(), 0); Assert.assertEquals(tla.getFailedTests().size(), 0); } Assert.assertTrue(exceptionRaised); } /** Simple suite with no two tests with same name */ @Test public void checkNoError() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); String testngXmlPath = getPathToResource("sanitycheck/test2.xml"); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 2); } /** Child suites and tests within different suites have same names */ @Test(enabled = false) public void checkNoErrorWtihChildSuites() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); String testngXmlPath = getPathToResource("sanitycheck/test-b.xml"); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 4); } /** Checks that suites created programmatically also run as expected */ @Test public void checkTestNamesForProgrammaticSuites() { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("SanityCheckSuite"); XmlTest result = new XmlTest(xmlSuite); result.getXmlClasses().add(new XmlClass(SampleTest1.class.getCanonicalName())); result = new XmlTest(xmlSuite); result.getXmlClasses().add(new XmlClass(SampleTest2.class.getCanonicalName())); TestNG tng = new TestNG(); tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sanitycheck/SampleTest1.java000066400000000000000000000002001475274123300302630ustar00rootroot00000000000000package test.sanitycheck; import org.testng.annotations.Test; public class SampleTest1 { @Test() public void test1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sanitycheck/SampleTest2.java000066400000000000000000000002001475274123300302640ustar00rootroot00000000000000package test.sanitycheck; import org.testng.annotations.Test; public class SampleTest2 { @Test() public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/sanitycheck/SampleTest3.java000066400000000000000000000002001475274123300302650ustar00rootroot00000000000000package test.sanitycheck; import org.testng.annotations.Test; public class SampleTest3 { @Test() public void test3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/serviceloader/000077500000000000000000000000001475274123300256105ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/serviceloader/MyConfigurationListener.java000066400000000000000000000006011475274123300332730ustar00rootroot00000000000000package test.serviceloader; import org.testng.IConfigurationListener; import org.testng.ITestResult; public class MyConfigurationListener implements IConfigurationListener { @Override public void onConfigurationSuccess(ITestResult itr) {} @Override public void onConfigurationFailure(ITestResult itr) {} @Override public void onConfigurationSkip(ITestResult itr) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/serviceloader/ServiceLoaderSampleTest.java000066400000000000000000000003441475274123300332050ustar00rootroot00000000000000package test.serviceloader; import org.testng.annotations.Test; /** * Dummy class to test ServiceLoader * * @author Cedric Beust */ public class ServiceLoaderSampleTest { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/serviceloader/ServiceLoaderTest.java000066400000000000000000000067151475274123300320530ustar00rootroot00000000000000package test.serviceloader; import static org.assertj.core.api.Assertions.assertThat; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.testng.Assert; import org.testng.CommandLineArgs; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; import test.listeners.ListenerAssert; public class ServiceLoaderTest extends SimpleBaseTest { @Test public void serviceLoaderShouldWork() { TestNG tng = create(ServiceLoaderSampleTest.class); URL url = getClass().getClassLoader().getResource("serviceloader.jar"); URLClassLoader ucl = URLClassLoader.newInstance(new URL[] {url}); tng.setServiceLoaderClassLoader(ucl); tng.run(); ListenerAssert.assertListenerType(tng.getServiceLoaderListeners(), TmpSuiteListener.class); } @Test(description = "GITHUB-2259") public void ensureSpiLoadedListenersCanBeSkipped() { TestNG tng = create(ServiceLoaderSampleTest.class); URL url = getClass().getClassLoader().getResource("serviceloader.jar"); URLClassLoader ucl = URLClassLoader.newInstance(new URL[] {url}); tng.setServiceLoaderClassLoader(ucl); String dontLoad = "test.serviceloader.TmpSuiteListener"; tng.setListenersToSkipFromBeingWiredInViaServiceLoaders(dontLoad); tng.run(); List loaded = tng.getServiceLoaderListeners().stream() .map(l -> l.getClass().getName()) .collect(Collectors.toList()); assertThat(loaded).doesNotContain(dontLoad); } @Test(description = "GITHUB-2259") @SuppressWarnings("deprecation") public void ensureSpiLoadedListenersCanBeSkipped2() { TestNG tng = create(ServiceLoaderSampleTest.class); URL url = getClass().getClassLoader().getResource("serviceloader.jar"); URLClassLoader ucl = URLClassLoader.newInstance(new URL[] {url}); tng.setServiceLoaderClassLoader(ucl); String dontLoad = "test.serviceloader.TmpSuiteListener"; Map cli = new HashMap<>(); cli.put(CommandLineArgs.LISTENERS_TO_SKIP_VIA_SPI, dontLoad); tng.configure(cli); tng.run(); List loaded = tng.getServiceLoaderListeners().stream() .map(l -> l.getClass().getName()) .collect(Collectors.toList()); assertThat(loaded).doesNotContain(dontLoad); } @Test public void serviceLoaderWithNoClassLoader() { // Here ServiceLoader is expected to rely on the current context class loader to load the // service loader file // Since serviceloader.jar doesn't seem to be visible to the current thread's contextual class // loader // resorting to pushing in a class loader into the current thread that can load the resource URL url = getClass().getClassLoader().getResource("serviceloader.jar"); URLClassLoader ucl = URLClassLoader.newInstance(new URL[] {url}); Thread.currentThread().setContextClassLoader(ucl); TestNG tng = create(ServiceLoaderSampleTest.class); tng.run(); ListenerAssert.assertListenerType(tng.getServiceLoaderListeners(), TmpSuiteListener.class); } @Test(description = "GITHUB-491") public void serviceLoaderShouldWorkWithConfigurationListener() { TestNG tng = create(ServiceLoaderSampleTest.class); tng.run(); Assert.assertEquals(2, tng.getServiceLoaderListeners().size()); ListenerAssert.assertListenerType( tng.getServiceLoaderListeners(), MyConfigurationListener.class); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/serviceloader/TmpSuiteListener.java000066400000000000000000000003761475274123300317410ustar00rootroot00000000000000package test.serviceloader; import org.testng.ISuite; import org.testng.ISuiteListener; public class TmpSuiteListener implements ISuiteListener { @Override public void onFinish(ISuite suite) {} @Override public void onStart(ISuite suite) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/simple/000077500000000000000000000000001475274123300242525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/simple/IncludedExcludedSampleTest.java000066400000000000000000000015741475274123300323330ustar00rootroot00000000000000package test.simple; import org.testng.Reporter; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class IncludedExcludedSampleTest { @BeforeSuite public void beforeSuite() { Reporter.log("beforeSuite"); } @BeforeTest public void beforeTest() { Reporter.log("beforeTest"); } @BeforeClass public void beforeTestClass() { Reporter.log("beforeTestClass"); } @BeforeMethod public void beforeTestMethod() { Reporter.log("beforeTestMethod"); } @Test public void test1() { Reporter.log("Child.test1"); } @Test(enabled = false) public void test2() { Reporter.log("Child.test2"); } @Test(groups = "a") public void test3() { Reporter.log("Child.test3"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/simple/IncludedExcludedTest.java000066400000000000000000000056341475274123300311720ustar00rootroot00000000000000package test.simple; import java.util.Collection; import java.util.List; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ITestNGListener; import org.testng.ITestNGMethod; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import testhelper.OutputDirectoryPatch; public class IncludedExcludedTest { private TestNG m_tng; @BeforeMethod public void init() { m_tng = new TestNG(); m_tng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); m_tng.setUseDefaultListeners(false); } @Test(description = "First test method") public void verifyIncludedExcludedCount1() { m_tng.setTestClasses(new Class[] {IncludedExcludedSampleTest.class}); m_tng.setGroups("a"); m_tng.addListener( (ITestNGListener) new MyReporter(new String[] {"test3"}, new String[] {"test1", "test2"})); m_tng.run(); } @Test(description = "Second test method") public void verifyIncludedExcludedCount2() { m_tng.setTestClasses(new Class[] {IncludedExcludedSampleTest.class}); m_tng.addListener( (ITestNGListener) new MyReporter( new String[] { "beforeSuite", "beforeTest", "beforeTestClass", "beforeTestMethod", "test1", "beforeTestMethod", "test3" }, new String[] {"test2"})); m_tng.run(); } } class MyReporter implements IReporter { private String[] m_included; private String[] m_excluded; public MyReporter(String[] included, String[] excluded) { m_included = included; m_excluded = excluded; } @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { Assert.assertEquals(suites.size(), 1); ISuite suite = suites.get(0); List invoked = suite.getAllInvokedMethods(); Assert.assertEquals(invoked.size(), m_included.length); for (String s : m_included) { Assert.assertTrue(containsInvokedMethod(invoked, s)); } Collection excluded = suite.getExcludedMethods(); Assert.assertEquals(excluded.size(), m_excluded.length); for (String s : m_excluded) { Assert.assertTrue(containsMethod(excluded, s)); } } private boolean containsMethod(Collection invoked, String string) { for (ITestNGMethod m : invoked) { if (m.getMethodName().equals(string)) { return true; } } return false; } private static boolean containsInvokedMethod(Collection invoked, String string) { for (IInvokedMethod m : invoked) { if (m.getTestMethod().getMethodName().equals(string)) { return true; } } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/simple/SimpleSample.java000066400000000000000000000001671475274123300275140ustar00rootroot00000000000000package test.simple; import org.testng.annotations.Test; public class SimpleSample { @Test public void f() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/000077500000000000000000000000001475274123300237275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/ReasonForSkipTest.java000066400000000000000000000131541475274123300301630ustar00rootroot00000000000000package test.skip; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import java.util.Arrays; import java.util.Map; import org.testng.CommandLineArgs; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test.skip.github1967.TestClassSample; import test.skip.issue2674.ConfigAwareTestNG; public class ReasonForSkipTest extends SimpleBaseTest { @Test(description = "GITHUB-1878") public void ensureSkipInfoHasFailedConfigDetails() { Map expected = Maps.newHashMap(); expected.put("testMethod", "beforeClass"); runTest(expected, TestClassWithFailedConfig.class); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasFailedTestDetails() { Map expected = Maps.newHashMap(); expected.put("childMethod", "parentMethod"); runTest(expected, TestClassWithFailedMethod.class); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasAllFailedTestDetails() { TestNG testng = create(TestClassWithMultipleFailures.class); ReasonReporter reporter = new ReasonReporter(); testng.addListener(reporter); testng.run(); assertThat(reporter.getSkippedInfo()) .containsAnyOf(entry("child", "father,mother"), entry("child", "mother,father")); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasFailedConfigDetailsInBaseClass() { Map expected = Maps.newHashMap(); expected.put("testMethod", "beforeClass"); expected.put("testMethodInChildClass", "beforeClass"); runTest(expected, TestClassWithFailedConfigInParentClass.class); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasFailedTestDetailsInBaseClass() { Map expected = Maps.newHashMap(); expected.put("childMethod", "parentMethod"); expected.put("anotherChild", "parentMethod"); runTest(expected, TestClassWithFailedMethodInParentClass.class); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasGlobalConfigFailureDetails() { Map expected = Maps.newHashMap(); expected.put("testMethod", "beforeTest"); runTest(expected, TestClassWithOnlyGlobalConfig.class, TestClassWithOnlyTestMethods.class); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasFailedTestDetailsWhenInvolvingGroups() { XmlSuite xmlSuite = createXmlSuite("sample_suite"); createXmlTest(xmlSuite, "sample_test", TestClassWithGroupFailures.class); xmlSuite.getIncludedGroups().addAll(Arrays.asList("unit", "integration")); TestNG testng = create(xmlSuite); ReasonReporter reporter = new ReasonReporter(); testng.addListener(reporter); testng.run(); Map expected = Maps.newHashMap(); expected.put("integrationTests", "unitTests"); assertThat(reporter.getSkippedInfo()).containsAllEntriesOf(expected); } @Test(description = "GITHUB-1878") public void ensureSkipInfoHasFailedTestDetailsWhenInvolvingMultipleGroups() { XmlSuite xmlSuite = createXmlSuite("sample_suite"); createXmlTest(xmlSuite, "sample_test", TestClassWithMultipleGroupFailures.class); xmlSuite.getIncludedGroups().addAll(Arrays.asList("p1", "p2", "all")); TestNG testng = create(xmlSuite); ReasonReporter reporter = new ReasonReporter(); testng.addListener(reporter); testng.run(); assertThat(reporter.getSkippedInfo()) .containsAnyOf(entry("child", "father,mother"), entry("child", "mother,father")); } @Test(description = "GITHUB-1878") public void testEnsureTestStatusIsSetProperlyForSkippedTests() { TestNG testng = create(TestClassSample.class); ReasonReporter reporter = new ReasonReporter(); testng.addListener(reporter); testng.run(); Map actual = reporter.getResults(); Map expected = Maps.newHashMap(); expected.put("test1min", ITestResult.SKIP); expected.put("test2min", ITestResult.SKIP); expected.put("setup", ITestResult.FAILURE); assertThat(actual).containsAllEntriesOf(expected); } @Test(description = "GITHUB-2674") public void ensureUpstreamFailuresTriggerSkipsForAllDataProviderValues() { TestNG testng = create(test.skip.issue2674.TestClassSample.class); testng.setReportAllDataDrivenTestsAsSkipped(true); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); assertThat(listener.getSkippedMethodNames()) .containsExactly("test2(iPhone,13)", "test2(iPhone-Pro,12)"); } @Test(description = "GITHUB-2674") public void ensureUpstreamFailuresTriggerSkipsForAllDataProviderValuesViaCmdLineArgs() { CommandLineArgs cli = new CommandLineArgs(); cli.includeAllDataDrivenTestsWhenSkipping = true; ConfigAwareTestNG testng = new ConfigAwareTestNG(); testng.setTestClasses(new Class[] {test.skip.issue2674.TestClassSample.class}); testng.configure(cli); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); assertThat(listener.getSkippedMethodNames()) .containsExactly("test2(iPhone,13)", "test2(iPhone-Pro,12)"); } private static void runTest(Map expected, Class... clazz) { TestNG testng = create(clazz); ReasonReporter reporter = new ReasonReporter(); testng.addListener(reporter); testng.run(); assertThat(reporter.getSkippedInfo()).containsAllEntriesOf(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/ReasonReporter.java000066400000000000000000000027521475274123300275520ustar00rootroot00000000000000package test.skip; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.testng.IReporter; import org.testng.ISuite; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; public class ReasonReporter implements IReporter { private Map results = Maps.newHashMap(); public Map getResults() { return results; } private Map skippedInfo = Maps.newHashMap(); public Map getSkippedInfo() { return skippedInfo; } @Override public void generateReport(List xmlSuites, List suites, String outDir) { suites.stream() .flatMap(suite -> suite.getResults().values().stream()) .flatMap( suiteResult -> suiteResult.getTestContext().getSkippedTests().getAllResults().stream()) .forEach(this::generateReport); suites.stream() .flatMap(iSuite -> iSuite.getAllInvokedMethods().stream()) .collect(Collectors.toList()) .forEach( im -> { results.put(im.getTestMethod().getMethodName(), im.getTestResult().getStatus()); }); } public void generateReport(ITestResult result) { String text = result.getSkipCausedBy().stream() .map(ITestNGMethod::getMethodName) .collect(Collectors.joining(",")); skippedInfo.put(result.getMethod().getMethodName(), text); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/TestClassWithFailedConfig.java000066400000000000000000000004401475274123300315640ustar00rootroot00000000000000package test.skip; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestClassWithFailedConfig { @BeforeClass public void beforeClass() { throw new RuntimeException("simulating a failure"); } @Test public void testMethod() {} } TestClassWithFailedConfigInParentClass.java000066400000000000000000000003061475274123300341350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skippackage test.skip; import org.testng.annotations.Test; public class TestClassWithFailedConfigInParentClass extends TestClassWithFailedConfig { @Test public void testMethodInChildClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/TestClassWithFailedMethod.java000066400000000000000000000004231475274123300316000ustar00rootroot00000000000000package test.skip; import org.testng.annotations.Test; public class TestClassWithFailedMethod { @Test public void parentMethod() { throw new RuntimeException("simulating a failure"); } @Test(dependsOnMethods = "parentMethod") public void childMethod() {} } TestClassWithFailedMethodInParentClass.java000066400000000000000000000003371475274123300341540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skippackage test.skip; import org.testng.annotations.Test; public class TestClassWithFailedMethodInParentClass extends TestClassWithFailedMethod { @Test(dependsOnMethods = "parentMethod") public void anotherChild() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/TestClassWithGroupFailures.java000066400000000000000000000004661475274123300320510ustar00rootroot00000000000000package test.skip; import org.testng.annotations.Test; public class TestClassWithGroupFailures { @Test(groups = "unit") public void unitTests() { throw new RuntimeException("simulating a failure"); } @Test(groups = "integration", dependsOnGroups = "unit") public void integrationTests() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/TestClassWithMultipleFailures.java000066400000000000000000000005571475274123300325510ustar00rootroot00000000000000package test.skip; import org.testng.annotations.Test; public class TestClassWithMultipleFailures { @Test public void father() { throw new RuntimeException("simulating a failure"); } @Test public void mother() { throw new RuntimeException("simulating a failure"); } @Test(dependsOnMethods = {"father", "mother"}) public void child() {} } TestClassWithMultipleGroupFailures.java000066400000000000000000000006461475274123300335060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skippackage test.skip; import org.testng.annotations.Test; public class TestClassWithMultipleGroupFailures { @Test(groups = "p1") public void father() { throw new RuntimeException("simulating a failure"); } @Test(groups = "p2") public void mother() { throw new RuntimeException("simulating a failure"); } @Test( groups = "all", dependsOnGroups = {"p1", "p2"}) public void child() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/TestClassWithOnlyGlobalConfig.java000066400000000000000000000003251475274123300324440ustar00rootroot00000000000000package test.skip; import org.testng.annotations.BeforeTest; public class TestClassWithOnlyGlobalConfig { @BeforeTest public void beforeTest() { throw new RuntimeException("simulating a failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/TestClassWithOnlyTestMethods.java000066400000000000000000000002151475274123300323570ustar00rootroot00000000000000package test.skip; import org.testng.annotations.Test; public class TestClassWithOnlyTestMethods { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632/000077500000000000000000000000001475274123300255255ustar00rootroot00000000000000AfterListenerSkipSample.java000066400000000000000000000012751475274123300330560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632package test.skip.github1632; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(AfterListenerSkipSample.MySkipTestListener.class) public class AfterListenerSkipSample { @BeforeMethod void beforeMethod() {} @Test void shouldNotBeExecuted() {} public static class MySkipTestListener implements IInvokedMethodListener { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { throw new SkipException("skip"); } } } BeforeListenerSkipSample.java000066400000000000000000000014611475274123300332140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632package test.skip.github1632; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; // Sample from // https://github.com/spring-projects/spring-framework/issues/26387#issuecomment-760326643 @Listeners(BeforeListenerSkipSample.MySkipTestListener.class) public class BeforeListenerSkipSample { @BeforeMethod void beforeMethod() {} @Test void shouldNotBeExecuted() {} public static class MySkipTestListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult testResult) { throw new SkipException("skip"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632/IssueTest.java000066400000000000000000000040371475274123300303240ustar00rootroot00000000000000package test.skip.github1632; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void runTest() { TestNG testng = create(TestClassSample.class); SkipMonitoringListener listener = new SkipMonitoringListener(); testng.addListener(listener); testng.run(); assertThat(listener.getStatus().get("skippingMethod")).isEqualTo(ITestResult.SKIP); assertThat(listener.getStatus().get("passingMethod")).isEqualTo(ITestResult.SUCCESS); assertThat(listener.getStatus().get("failingMethod")).isEqualTo(ITestResult.FAILURE); assertThat(listener.getStatus().get("anotherFailingMethod")).isEqualTo(ITestResult.FAILURE); } @Test public void runBeforeListenerSkipSample() { InvokedMethodNameListener listener = run(BeforeListenerSkipSample.class); assertThat(listener.getResult("shouldNotBeExecuted").getStatus()).isEqualTo(ITestResult.SKIP); } @Test public void runNoConfigBeforeListenerSample() { InvokedMethodNameListener listener = run(NoConfigBeforeListenerSample.class); assertThat(listener.getResult("shouldNotBeExecuted").getStatus()).isEqualTo(ITestResult.SKIP); } @Test public void runAfterListenerSkipSample() { InvokedMethodNameListener listener = run(AfterListenerSkipSample.class); assertThat(listener.getResult("shouldNotBeExecuted").getStatus()).isEqualTo(ITestResult.SKIP); } @Test public void runNoConfigAfterListenerSample() { InvokedMethodNameListener listener = run(NoConfigAfterListenerSample.class); assertThat(listener.getResult("shouldNotBeExecuted").getStatus()).isEqualTo(ITestResult.SKIP); } @Test public void runBeforeListenerSkipSample2() { InvokedMethodNameListener listener = run(ListenerMarksMethodAsSkippedSample.class); assertThat(listener.getResult("shouldNotBeExecuted").getStatus()).isEqualTo(ITestResult.SKIP); } } ListenerMarksMethodAsSkippedSample.java000066400000000000000000000012711475274123300352040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632package test.skip.github1632; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ListenerMarksMethodAsSkippedSample.MySkipTestListener.class) public class ListenerMarksMethodAsSkippedSample { @BeforeMethod void beforeMethod() {} @Test void shouldNotBeExecuted() {} public static class MySkipTestListener implements IInvokedMethodListener { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { testResult.setStatus(ITestResult.SKIP); } } } NoConfigAfterListenerSample.java000066400000000000000000000011571475274123300336510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632package test.skip.github1632; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(NoConfigAfterListenerSample.MySkipTestListener.class) public class NoConfigAfterListenerSample { @Test void shouldNotBeExecuted() {} public static class MySkipTestListener implements IInvokedMethodListener { @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { throw new SkipException("skip"); } } } NoConfigBeforeListenerSample.java000066400000000000000000000013431475274123300340070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632package test.skip.github1632; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.annotations.Listeners; import org.testng.annotations.Test; // Sample from // https://github.com/spring-projects/spring-framework/issues/26387#issuecomment-760326643 @Listeners(NoConfigBeforeListenerSample.MySkipTestListener.class) public class NoConfigBeforeListenerSample { @Test void shouldNotBeExecuted() {} public static class MySkipTestListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult testResult) { throw new SkipException("skip"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632/SkipMonitoringListener.java000066400000000000000000000017041475274123300330540ustar00rootroot00000000000000package test.skip.github1632; import java.util.HashMap; import java.util.Map; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.SkipException; public class SkipMonitoringListener implements IInvokedMethodListener { private final Map status = new HashMap<>(); public Map getStatus() { return status; } @Override public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) { SkipTest skipTest = iInvokedMethod .getTestMethod() .getConstructorOrMethod() .getMethod() .getAnnotation(SkipTest.class); if (skipTest != null) { throw new SkipException("skip"); } } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { status.put(method.getTestMethod().getMethodName(), testResult.getStatus()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632/SkipTest.java000066400000000000000000000005071475274123300301400ustar00rootroot00000000000000package test.skip.github1632; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD, TYPE}) public @interface SkipTest {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1632/TestClassSample.java000066400000000000000000000005771475274123300314500ustar00rootroot00000000000000package test.skip.github1632; import org.testng.Assert; import org.testng.annotations.Test; public class TestClassSample { @Test public void passingMethod() {} @Test @SkipTest public void skippingMethod() {} @Test public void failingMethod() { Assert.fail(); } @Test public void anotherFailingMethod() { throw new RuntimeException("Failure"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1967/000077500000000000000000000000001475274123300255405ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/github1967/TestClassSample.java000066400000000000000000000005371475274123300314570ustar00rootroot00000000000000package test.skip.github1967; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestClassSample { @Test public void test1min() { Assert.fail(); } @Test public void test2min() { Assert.fail(); } @BeforeClass public void setup() { Assert.fail(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/issue2674/000077500000000000000000000000001475274123300254025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/issue2674/ConfigAwareTestNG.java000066400000000000000000000003501475274123300315150ustar00rootroot00000000000000package test.skip.issue2674; import org.testng.CommandLineArgs; import org.testng.TestNG; public class ConfigAwareTestNG extends TestNG { @Override public void configure(CommandLineArgs cla) { super.configure(cla); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skip/issue2674/TestClassSample.java000066400000000000000000000007151475274123300313170ustar00rootroot00000000000000package test.skip.issue2674; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class TestClassSample { @Test void test1() { Assert.fail(); } @Test( dataProvider = "items", dependsOnMethods = {"test1"}) void test2(String model, int variant) {} @DataProvider(name = "items") Object[][] items() { return new Object[][] {{"iPhone", 13}, {"iPhone-Pro", 12}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skipex/000077500000000000000000000000001475274123300242645ustar00rootroot00000000000000ConfigurationSkippedExceptionTest.java000066400000000000000000000005651475274123300337240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skipexpackage test.skipex; import org.testng.SkipException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** This class/interface */ public class ConfigurationSkippedExceptionTest { @BeforeMethod public void configurationLevelSkipException() { throw new SkipException("some skip message"); } @Test public void dummyTest() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skipex/SkipAndExpectedSampleTest.java000066400000000000000000000003761475274123300321520ustar00rootroot00000000000000package test.skipex; import org.testng.SkipException; import org.testng.annotations.Test; public class SkipAndExpectedSampleTest { @Test(expectedExceptions = NullPointerException.class) public void a2() { throw new SkipException("test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skipex/SkipAndExpectedTest.java000066400000000000000000000012261475274123300310030ustar00rootroot00000000000000package test.skipex; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class SkipAndExpectedTest extends SimpleBaseTest { @Test public void shouldSkip() { TestNG tng = create(SkipAndExpectedSampleTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 0); Assert.assertEquals(tla.getSkippedTests().size(), 1); Assert.assertEquals(tla.getFailedTests().size(), 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skipex/SkippedExceptionTest.java000066400000000000000000000035651475274123300312560ustar00rootroot00000000000000package test.skipex; import java.util.List; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; /** This class/interface */ public class SkippedExceptionTest { @Test public void skippedExceptionInConfigurationMethods() { TestListenerAdapter listener = new TestListenerAdapter(); TestNG test = new TestNG(false); test.addListener((ITestNGListener) listener); test.setTestClasses(new Class[] {ConfigurationSkippedExceptionTest.class}); test.run(); List confSkips = listener.getConfigurationSkips(); List testSkips = listener.getSkippedTests(); Assert.assertEquals(testSkips.size(), 1); Assert.assertEquals(testSkips.get(0).getMethod().getMethodName(), "dummyTest"); Assert.assertEquals(confSkips.size(), 1); Assert.assertEquals( confSkips.get(0).getMethod().getMethodName(), "configurationLevelSkipException"); } @Test public void skippedExceptionInTestMethods() { TestListenerAdapter listener = new TestListenerAdapter(); TestNG test = new TestNG(false); test.addListener(listener); test.setTestClasses(new Class[] {TestSkippedExceptionTest.class}); test.run(); List skips = listener.getSkippedTests(); List failures = listener.getFailedTests(); List passed = listener.getPassedTests(); Assert.assertEquals(skips.size(), 1); Assert.assertEquals(failures.size(), 1); Assert.assertEquals(passed.size(), 1); Assert.assertEquals(skips.get(0).getMethod().getMethodName(), "genericSkipException"); Assert.assertEquals(failures.get(0).getMethod().getMethodName(), "timedSkipException"); Assert.assertEquals(passed.get(0).getMethod().getMethodName(), "genericExpectedSkipException"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/skipex/TestSkippedExceptionTest.java000066400000000000000000000012111475274123300321000ustar00rootroot00000000000000package test.skipex; import org.testng.SkipException; import org.testng.TimeBombSkipException; import org.testng.annotations.Test; /** This class/interface */ public class TestSkippedExceptionTest { @Test public void genericSkipException() { throw new SkipException("genericSkipException is skipped for now"); } @Test(expectedExceptions = SkipException.class) public void genericExpectedSkipException() { throw new SkipException("genericExpectedSkipException should not be skipped"); } @Test public void timedSkipException() { throw new TimeBombSkipException("timedSkipException is time bombed", "2007/04/10"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/000077500000000000000000000000001475274123300242755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1533/000077500000000000000000000000001475274123300260735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1533/Github1533Test.java000066400000000000000000000030051475274123300313320ustar00rootroot00000000000000package test.suites.github1533; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.util.List; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; public class Github1533Test extends SimpleBaseTest { @Test public void testScenarioWithChildSuites() { String suiteFile = "src/test/resources/xml/github1533/parent.xml"; runTests(suiteFile, 1, 2, "GitHub1533_Suite", "GitHub1533_Parent_Suite"); } @Test public void testScenarioWithNoChildSuites() { String suiteFile = "src/test/resources/xml/github1533/child.xml"; runTests(suiteFile, 0, 1, "GitHub1533_Suite"); } private static void runTests( String suiteFile, int childSuitesCount, int suiteCounter, String... suiteNames) { List suites; try { suites = new Parser(suiteFile).parseToList(); } catch (IOException e) { throw new TestNGException(e); } assertEquals(suites.size(), 1); assertEquals(suites.get(0).getChildSuites().size(), childSuitesCount); TestNG testng = create(suites); SuiteCounter listener = new SuiteCounter(); testng.addListener((ITestNGListener) listener); testng.run(); assertEquals(listener.getCounter(), suiteCounter); assertThat(listener.getSuiteNames()).containsExactly(suiteNames); } } SampleTestClassSample.java000066400000000000000000000002231475274123300330650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1533package test.suites.github1533; import org.testng.annotations.Test; public class SampleTestClassSample { @Test public void testMethod() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1533/SuiteCounter.java000066400000000000000000000012611475274123300313670ustar00rootroot00000000000000package test.suites.github1533; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.collections.Lists; public class SuiteCounter implements ISuiteListener { private final AtomicInteger counter = new AtomicInteger(0); private final List suiteNames = Lists.newArrayList(); @Override public void onStart(ISuite suite) { counter.incrementAndGet(); suiteNames.add(suite.getName()); } @Override public void onFinish(ISuite suite) {} public int getCounter() { return counter.get(); } public List getSuiteNames() { return suiteNames; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1850/000077500000000000000000000000001475274123300260755ustar00rootroot00000000000000DuplicateChildSuitesInitializationTest.java000066400000000000000000000047571475274123300365210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1850package test.suites.github1850; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.util.List; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; /** * This test checks that TestNG can handle duplicate child suites when we have the following set of * files: * *

- parent-suite-with-duplicate-child -> [child-suite-1, children/child-suite-3, child-suite1, * children/child-suite-3] - children/child-suite-3 -> [../child-suite-2, child-suite-4, * morechildren/child-suite-5] * *

SHOULD return a XmlSuite object with following structure: * *

parent-suite-with-duplicate-child ├───child-suite-1 ├───child-suite-3 │ ├───child-suite-2 │ * ├───child-suite-4 │ └───child-suite-5 ├───child-suite-1(0) └───child-suite-3(0) * ├───child-suite-2(0) ├───child-suite-4(0) └───child-suite-5(0) * *

but NOT like: * *

parent-suite-with-duplicate-child ├───child-suite-1 ├───child-suite-3 ├───child-suite-1(0) * └───child-suite-3(0) ├───child-suite-2 ├───child-suite-4 ├───child-suite-5 ├───child-suite-2(0) * ├───child-suite-4(0) └───child-suite-5(0) * *

Check the checksuitesinitialization folder under test resources */ public class DuplicateChildSuitesInitializationTest extends SimpleBaseTest { @Test public void checkDuplicateChildSuites() throws IOException { String path = getPathToResource("checksuitesinitialization/parent-suite-with-duplicate-child.xml"); Parser parser = new Parser(path); List suites = parser.parseToList(); XmlSuite rootSuite = suites.get(0); assertEquals(rootSuite.getChildSuites().size(), 4); XmlSuite suite3 = rootSuite.getChildSuites().get(1); assertEquals(suite3.getName(), "Child Suite 3"); assertEquals(suite3.getChildSuites().size(), 3); XmlSuite suite3_0 = rootSuite.getChildSuites().get(3); assertEquals(suite3.getName(), "Child Suite 3"); assertEquals(suite3_0.getChildSuites().size(), 3); XmlSuite suite5 = suite3.getChildSuites().get(2); assertEquals(suite5.getName(), "Child Suite 5"); assertEquals(suite5.getTests().size(), 1); XmlSuite suite5_0 = suite3_0.getChildSuites().get(2); assertEquals(suite5_0.getName(), "Child Suite 5"); assertEquals(suite5_0.getTests().size(), 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1874/000077500000000000000000000000001475274123300261035ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1874/IssueTest.java000066400000000000000000000017141475274123300307010ustar00rootroot00000000000000package test.suites.github1874; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test // We are explicitly not including any assertions here because the intent of this test is to // ensure that there are no exceptions triggered related to circular dependency. public void testEnsureNoCyclicDependencyTriggered() { XmlSuite suite = createXmlSuite("sample_suite"); XmlTest test = createXmlTest(suite, "sample_test"); XmlClass entryOne = new XmlClass(TestClassSample.class); createXmlInclude(entryOne, "testMethodTwo"); test.getClasses().add(entryOne); XmlClass entryTwo = new XmlClass(TestClassSample.class); createXmlInclude(entryTwo, "testMethodOne"); test.getClasses().add(entryTwo); TestNG testng = create(suite); testng.run(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/suites/github1874/TestClassSample.java000066400000000000000000000002721475274123300320160ustar00rootroot00000000000000package test.suites.github1874; import org.testng.annotations.Test; public class TestClassSample { @Test public void testMethodOne() {} @Test public void testMethodTwo() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/000077500000000000000000000000001475274123300251455ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/Base1.java000066400000000000000000000004331475274123300267430ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Base1 { @BeforeClass public void bc() {} @BeforeMethod public void bm() {} @Test public void tbase() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/Base2.java000066400000000000000000000004311475274123300267420ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test public class Base2 { @BeforeClass public void bc() {} @BeforeMethod public void bm() {} public void tbase() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/BaseSampleTest3.java000066400000000000000000000002241475274123300307450ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.Test; public class BaseSampleTest3 { @Test public void base() { assert true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/Child1Test.java000066400000000000000000000002631475274123300277550ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.Test; @Test public class Child1Test extends Base1 { public void t1() {} public void t2() {} public void t3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/Child2Test.java000066400000000000000000000002631475274123300277560ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.Test; @Test public class Child2Test extends Base2 { public void t1() {} public void t2() {} public void t3() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/ChildSampleTest3.java000066400000000000000000000004251475274123300311210ustar00rootroot00000000000000package test.superclass; import org.testng.Assert; import org.testng.annotations.Test; public class ChildSampleTest3 extends BaseSampleTest3 { @Test public void pass() { Assert.assertTrue(true); } @Test public void fail() { Assert.assertTrue(false); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/MainTest.java000066400000000000000000000013331475274123300275340ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.Test; import test.BaseTest; public class MainTest extends BaseTest { @Test public void baseMethodIsCalledWithMethodTest() { addClass("test.superclass.Child1Test"); run(); String[] passed = {"tbase", "t1", "t2", "t3"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } @Test public void baseMethodIsCalledWithClassTest() { addClass("test.superclass.Child2Test"); run(); String[] passed = {"tbase", "t1", "t2", "t3"}; String[] failed = {}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/superclass/Test3.java000066400000000000000000000010341475274123300270100ustar00rootroot00000000000000package test.superclass; import org.testng.annotations.Test; import test.BaseTest; public class Test3 extends BaseTest { @Test public void shouldExcludeBaseMethods() { addClass("test.superclass.ChildSampleTest3"); addExcludedMethod("test.superclass.ChildSampleTest3", "pass"); addExcludedMethod("test.superclass.ChildSampleTest3", "base"); run(); String[] passed = {}; String[] failed = {"fail"}; verifyTests("Failed", failed, getFailedTests()); verifyTests("Passed", passed, getPassedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/test111/000077500000000000000000000000001475274123300241635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/test111/AbstractTest.java000066400000000000000000000004131475274123300274270ustar00rootroot00000000000000package test.test111; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; public abstract class AbstractTest { public static int R = 0; @Test public void testAbstract() {} @AfterClass public void afterClass() { R++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/test111/Test1.java000066400000000000000000000003201475274123300260210ustar00rootroot00000000000000package test.test111; import org.junit.Assert; import org.testng.annotations.Test; public class Test1 extends AbstractTest { @Test public void test() { Assert.assertEquals(0, AbstractTest.R); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testnames/000077500000000000000000000000001475274123300247645ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testnames/TestNamesFeature.java000066400000000000000000000002741475274123300310510ustar00rootroot00000000000000package test.testnames; import org.testng.annotations.Test; public class TestNamesFeature { @Test public void sampleOutputTest1() {} @Test public void sampleOutputTest2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testnames/TestNamesTest.java000066400000000000000000000015701475274123300303750ustar00rootroot00000000000000package test.testnames; import java.util.Collections; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class TestNamesTest extends SimpleBaseTest { @Test public void checkWithoutChildSuites() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); tng.setTestNames(Collections.singletonList("testGroup2")); tng.setTestSuites(Collections.singletonList(getPathToResource("testnames/upstream-suite.xml"))); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getFailedTests().size(), 0); Assert.assertEquals(tla.getPassedTests().size(), 1); Assert.assertEquals( tla.getPassedTests().get(0).getMethod().getMethodName(), "sampleOutputTest2"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng106/000077500000000000000000000000001475274123300245145ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng106/FailingSuiteFixture.java000066400000000000000000000004441475274123300313130ustar00rootroot00000000000000package test.testng106; import org.testng.annotations.BeforeSuite; /** TESTNG-106: failing @BeforeSuite doesn't skip all tests */ public class FailingSuiteFixture { static int s_invocations = 0; @BeforeSuite public void failingBeforeSuite() { throw new RuntimeException(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng106/Test1.java000066400000000000000000000003431475274123300263570ustar00rootroot00000000000000package test.testng106; import org.testng.annotations.Test; /** This class/interface */ public class Test1 { @Test public void method1() { System.out.println("method1"); FailingSuiteFixture.s_invocations++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng106/Test2.java000066400000000000000000000005261475274123300263630ustar00rootroot00000000000000package test.testng106; import org.testng.annotations.Test; /** This class/interface */ public class Test2 { @Test public void method2() { System.out.println("method2"); FailingSuiteFixture.s_invocations++; } @Test public void method3() { System.out.println("method3"); FailingSuiteFixture.s_invocations++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng106/TestNG106.java000066400000000000000000000015541475274123300267570ustar00rootroot00000000000000package test.testng106; import java.util.Arrays; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class TestNG106 extends SimpleBaseTest { @Test public void testFailingBeforeSuiteShouldSkipAllTests() throws Exception { TestNG tng = create(); XmlSuite s = createXmlSuite("TESTNG-106"); createXmlTest(s, "myTest1", FailingSuiteFixture.class.getName(), Test1.class.getName()); createXmlTest(s, "myTest2", Test1.class.getName()); createXmlTest(s, "myTest3", Test2.class.getName()); createXmlTest(s, "myTest-last", Test2.class.getName()); tng.setXmlSuites(Arrays.asList(s)); tng.run(); Assert.assertEquals( FailingSuiteFixture.s_invocations, 0, "@BeforeSuite has failed. All tests should be skipped."); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng109/000077500000000000000000000000001475274123300245175ustar00rootroot00000000000000SkippedTestWithExpectedExceptionTest.java000066400000000000000000000006561475274123300346060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng109package test.testng109; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** This class/interface */ public class SkippedTestWithExpectedExceptionTest { @BeforeClass public void setup() { throw new RuntimeException("test-exception"); } @Test public void test1() { // empty } @Test(expectedExceptions = {OutOfMemoryError.class}) public void test2() { // empty } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1231/000077500000000000000000000000001475274123300245745ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1231/ListenerOrderTestSample.java000066400000000000000000000002161475274123300322210ustar00rootroot00000000000000package test.testng1231; import org.testng.annotations.Test; public class ListenerOrderTestSample { @Test public void testMethod() {} } TestExecutionListenerInvocationOrder.java000066400000000000000000000031421475274123300347170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1231package test.testng1231; import com.beust.jcommander.internal.Lists; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.testng.*; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class TestExecutionListenerInvocationOrder extends SimpleBaseTest { @Test public void testListenerOrder() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); createXmlClass(xmlTest, ListenerOrderTestSample.class); TestNG tng = create(xmlSuite); TestListenerFor1231 listener = new TestListenerFor1231(); tng.addListener((ITestNGListener) listener); tng.run(); List expected = Arrays.asList(1, 2, 3, 4, 5, 6); Assert.assertEquals(TestListenerFor1231.order, expected); } public static class TestListenerFor1231 implements IExecutionListener, IAlterSuiteListener, IReporter, ISuiteListener { public static LinkedList order = Lists.newLinkedList(); @Override public void onExecutionStart() { order.add(1); } @Override public void onExecutionFinish() { order.add(6); } @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { order.add(5); } @Override public void alter(List suites) { order.add(2); } @Override public void onStart(ISuite suite) { order.add(3); } @Override public void onFinish(ISuite suite) { order.add(4); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1232/000077500000000000000000000000001475274123300245755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1232/ListenerTemplate.java000066400000000000000000000032761475274123300307310ustar00rootroot00000000000000package test.testng1232; import java.util.List; import org.testng.*; import org.testng.xml.XmlSuite; /** * This class provides "void" implementations for all listener invocations so that one can tweak * behavior of only those methods which need customization. (Mainly to circumvent verbosity in * actual listener implementations) */ public class ListenerTemplate implements IInvokedMethodListener, IClassListener, ITestListener, ISuiteListener, IAlterSuiteListener, IExecutionListener, IReporter { @Override public void onBeforeClass(ITestClass testClass) {} @Override public void onAfterClass(ITestClass testClass) {} @Override public void onStart(ISuite suite) {} @Override public void onFinish(ISuite suite) {} @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) {} @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) {} @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} @Override public void onExecutionStart() {} @Override public void onExecutionFinish() {} @Override public void alter(List suites) {} @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1232/TestClassContainer.java000066400000000000000000000007171475274123300312150ustar00rootroot00000000000000package test.testng1232; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** This Class houses all the test classes that are required by {@link TestListenerInstances} */ public class TestClassContainer { public static class SimpleTestClass { @Test public void testMethod() {} } @Listeners(TestListenerFor1232.class) public static class SimpleTestClassWithListener { @Test public void testMethod() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1232/TestListenerFor1232.java000066400000000000000000000031411475274123300310430ustar00rootroot00000000000000package test.testng1232; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.testng.*; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; public class TestListenerFor1232 extends ListenerTemplate { static Map counters = Maps.newHashMap(); static synchronized void resetCounters() { counters = Maps.newHashMap(); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { incrementCounter(CounterTypes.METHOD); } @Override public void onBeforeClass(ITestClass testClass) { incrementCounter(CounterTypes.CLASS); } @Override public void onStart(ITestContext context) { incrementCounter(CounterTypes.TEST); } @Override public void onStart(ISuite suite) { incrementCounter(CounterTypes.SUITE); } @Override public void alter(List suites) { incrementCounter(CounterTypes.ALTER_SUITE); } @Override public void onExecutionStart() { incrementCounter(CounterTypes.EXECUTION); } @Override public void generateReport( List xmlSuites, List suites, String outputDirectory) { incrementCounter(CounterTypes.REPORTER); } private void incrementCounter(CounterTypes type) { if (!counters.containsKey(type)) { counters.put(type, new AtomicInteger(0)); } AtomicInteger value = counters.get(type); value.incrementAndGet(); counters.put(type, value); } enum CounterTypes { METHOD, CLASS, TEST, SUITE, ALTER_SUITE, EXECUTION, REPORTER } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1232/TestListenerInstances.java000066400000000000000000000035241475274123300317410ustar00rootroot00000000000000package test.testng1232; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import test.testng1232.TestListenerFor1232.CounterTypes; public class TestListenerInstances extends SimpleBaseTest { @Test public void testIfOnlyOneListenerInstanceExists() { runTestForTestClass(TestClassContainer.SimpleTestClass.class); } @Test public void testIfOnlyOneListenerInstanceExistsUsingAnnotations() { runTestForTestClass(TestClassContainer.SimpleTestClassWithListener.class); } @Test public void testIfOnlyOneListenerInstanceExistsUsingListenerTag() { runTestForTestClass(TestClassContainer.SimpleTestClass.class, true); } private static void runTestForTestClass(Class clazz) { runTestForTestClass(clazz, false); } private static void runTestForTestClass(Class clazz, boolean injectListenerViaTag) { TestNG tng = createTestNGInstanceFor(clazz, injectListenerViaTag); TestListenerFor1232.resetCounters(); TestListenerFor1232 listener = new TestListenerFor1232(); tng.addListener((ITestNGListener) listener); TestListenerFor1232 anotherListener = new TestListenerFor1232(); tng.addListener((ITestNGListener) anotherListener); tng.run(); for (CounterTypes type : CounterTypes.values()) { Assert.assertEquals(TestListenerFor1232.counters.get(type).intValue(), 1); } } private static TestNG createTestNGInstanceFor(Class clazz, boolean addListenerTag) { XmlSuite xmlSuite = createXmlSuite("Suite"); if (addListenerTag) { xmlSuite.addListener(TestListenerFor1232.class.getName()); } XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); createXmlClass(xmlTest, clazz); return create(xmlSuite); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1396/000077500000000000000000000000001475274123300246105ustar00rootroot00000000000000ParallelByInstancesInterceptorTest.java000066400000000000000000000067701475274123300343640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1396package test.testng1396; import static org.testng.Assert.fail; import java.util.Comparator; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.ITestNGListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.XmlSuite; public class ParallelByInstancesInterceptorTest { @Test(description = "test for https://github.com/cbeust/testng/issues/1396") public void should_honor_interceptor_order_when_running_parallel_instances() { TestNG tng = new TestNG(); // 10 instances is enough that we see the non-deterministic ordering of hashmaps more often than // not tng.setTestClasses( new Class[] { SampleFor1396.Sample9For1396.class, SampleFor1396.Sample8For1396.class, SampleFor1396.Sample7For1396.class, SampleFor1396.Sample6For1396.class, SampleFor1396.Sample5For1396.class, SampleFor1396.Sample4For1396.class, SampleFor1396.Sample3For1396.class, SampleFor1396.Sample2For1396.class, SampleFor1396.Sample1For1396.class, SampleFor1396.Sample0For1396.class }); // bug only exists when running parallel by instances with this flag set to false tng.setParallel(XmlSuite.ParallelMode.INSTANCES); tng.setPreserveOrder(false); // thread count of 1 forces sequential execution so we can verify ordering tng.setThreadCount(1); TestListenerAdapter adapter = new TestListenerAdapter(); tng.addListener((ITestNGListener) adapter); // Runs tests annotated with @TestNG1396HighPriority before tests without it ReverseOrderTestInterceptor listener = new ReverseOrderTestInterceptor(); tng.addListener(listener); tng.run(); List passedTests = adapter.getPassedTests(); boolean lowPrioritySeen = false; for (ITestResult testResult : passedTests) { if (isHighPriority(testResult.getMethod())) { if (lowPrioritySeen) { fail("high priority should be first"); } } else { lowPrioritySeen = true; } } } private static boolean isHighPriority(IMethodInstance instance) { return instance.getInstance().getClass().getAnnotation(TestNG1396HighPriority.class) != null; } private static boolean isHighPriority(ITestNGMethod method) { return method.getInstance().getClass().getAnnotation(TestNG1396HighPriority.class) != null; } public class ReverseOrderTestInterceptor implements IMethodInterceptor { @Override public List intercept(List methods, ITestContext context) { List sorted = Lists.newArrayList(methods); sorted.sort(new PriorityComparator()); return sorted; } } public class PriorityComparator implements Comparator { @Override public int compare(IMethodInstance o1, IMethodInstance o2) { if (isHighPriority(o1)) { if (isHighPriority(o2)) { return compareMethodNames(o1, o2); } return -1; } if (isHighPriority(o2)) { return 1; } return compareMethodNames(o1, o2); } private int compareMethodNames(IMethodInstance o1, IMethodInstance o2) { return o2.getMethod().getQualifiedName().compareTo(o1.getMethod().getQualifiedName()); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1396/SampleFor1396.java000066400000000000000000000017151475274123300276720ustar00rootroot00000000000000package test.testng1396; import org.testng.annotations.Test; public class SampleFor1396 { public class Sample0For1396 { @Test public void sample() {} } @TestNG1396HighPriority public class Sample1For1396 { @Test public void sample() {} } public class Sample2For1396 { @Test public void sample() {} } @TestNG1396HighPriority public class Sample3For1396 { @Test public void sample() {} } public class Sample4For1396 { @Test public void sample() {} } @TestNG1396HighPriority public class Sample5For1396 { @Test public void sample() {} } public class Sample6For1396 { @Test public void sample() {} } @TestNG1396HighPriority public class Sample7For1396 { @Test public void sample() {} } public class Sample8For1396 { @Test public void sample() {} } @TestNG1396HighPriority public class Sample9For1396 { @Test public void sample() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng1396/TestNG1396HighPriority.java000066400000000000000000000005501475274123300315040ustar00rootroot00000000000000package test.testng1396; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({METHOD, TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TestNG1396HighPriority {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng173/000077500000000000000000000000001475274123300245205ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng173/ClassA.java000066400000000000000000000002661475274123300265350ustar00rootroot00000000000000package test.testng173; import org.testng.annotations.Test; public class ClassA { @Test public void test1() {} @Test(dependsOnMethods = "test1") public void test2() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng173/ClassB.java000066400000000000000000000003601475274123300265310ustar00rootroot00000000000000package test.testng173; import org.testng.annotations.*; public class ClassB { @Test public void testX() {} @Test(dependsOnMethods = "testX") public void test2() {} @Test(dependsOnMethods = "test2") public void test1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng173/TestNG173Test.java000066400000000000000000000037171475274123300276320ustar00rootroot00000000000000package test.testng173; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class TestNG173Test extends SimpleBaseTest { @Test public void orderShouldBePreservedInMethodsWithSameNameAndInDifferentClasses() { TestNG tng = create(); XmlSuite s = createXmlSuite("PreserveOrder"); XmlTest t = new XmlTest(s); t.getXmlClasses().add(new XmlClass("test.testng173.ClassA")); t.getXmlClasses().add(new XmlClass("test.testng173.ClassB")); t.setPreserveOrder(true); tng.setXmlSuites(Arrays.asList(s)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); // bug // verifyPassedTests(tla, "test1", "test2", "testX", "test1", "test2"); // Proposed fix assertThat(listener.getSucceedMethodNames()) .containsExactly("test1", "test2", "testX", "test2", "test1"); } @Test public void orderShouldBePreservedInMethodsWithSameNameAndInDifferentClassesAndDifferentPackage() { TestNG tng = create(); XmlSuite s = createXmlSuite("PreserveOrder"); XmlTest t = new XmlTest(s); t.getXmlClasses().add(new XmlClass("test.testng173.ClassA")); t.getXmlClasses().add(new XmlClass("test.testng173.anotherpackage.ClassC")); t.setPreserveOrder(true); tng.setXmlSuites(Arrays.asList(s)); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); // bug // verifyPassedTests(tla, "test1", "test2", "testX", "test1", "test2"); assertThat(listener.getSucceedMethodNames()) .containsExactly("test1", "test2", "testX", "test2", "test1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng173/anotherpackage/000077500000000000000000000000001475274123300274745ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng173/anotherpackage/ClassC.java000066400000000000000000000004031475274123300315040ustar00rootroot00000000000000package test.testng173.anotherpackage; import org.testng.annotations.Test; public class ClassC { @Test public void testX() {} @Test(dependsOnMethods = "testX") public void test2() {} @Test(dependsOnMethods = "test2") public void test1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng195/000077500000000000000000000000001475274123300245245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng195/AfterMethodSampleTest.java000066400000000000000000000010551475274123300315740ustar00rootroot00000000000000package test.testng195; import java.lang.reflect.Method; import org.testng.IResultMap; import org.testng.ITestContext; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class AfterMethodSampleTest { static boolean m_success; @Test public void pass() {} @BeforeClass public void init() { m_success = false; } @AfterMethod public void afterMethod(ITestContext c, Method m) { IResultMap map = c.getPassedTests(); m_success = map.size() == 1; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng195/AfterMethodTest.java000066400000000000000000000006011475274123300304260ustar00rootroot00000000000000package test.testng195; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class AfterMethodTest extends SimpleBaseTest { @Test public void testContextShouldBeInitialized() { TestNG tng = create(AfterMethodSampleTest.class); tng.run(); Assert.assertTrue(AfterMethodSampleTest.m_success); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng249/000077500000000000000000000000001475274123300245245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng249/B.java000066400000000000000000000002071475274123300255470ustar00rootroot00000000000000package test.testng249; import org.testng.annotations.Test; public class B extends Base { @Override @Test public void b() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng249/Base.java000066400000000000000000000001611475274123300262370ustar00rootroot00000000000000package test.testng249; import org.testng.annotations.Test; public class Base { @Test public void b() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng249/VerifyTest.java000066400000000000000000000022141475274123300274720ustar00rootroot00000000000000package test.testng249; import java.util.Arrays; import java.util.Collections; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class VerifyTest extends SimpleBaseTest { @Test public void verify() { XmlSuite suite = new XmlSuite(); suite.setName("Suite"); XmlTest test = new XmlTest(suite); test.setName("Test"); XmlClass c1 = new XmlClass(B.class); c1.setIncludedMethods(Collections.singletonList(new XmlInclude("b"))); XmlClass c2 = new XmlClass(Base.class); c2.setIncludedMethods(Collections.singletonList(new XmlInclude("b"))); test.setXmlClasses(Arrays.asList(c1, c2)); TestNG tng = new TestNG(); tng.setXmlSuites(Collections.singletonList(suite)); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng285/000077500000000000000000000000001475274123300245245ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng285/BugBase.java000066400000000000000000000007041475274123300267000ustar00rootroot00000000000000package test.testng285; import java.util.HashSet; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(singleThreaded = true) public class BugBase { static Set m_threadIds; @BeforeClass public void setup() { m_threadIds = new HashSet<>(); } void log(long threadId) { m_threadIds.add(threadId); } public void fbase() { log(Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng285/Derived.java000066400000000000000000000003751475274123300267560ustar00rootroot00000000000000package test.testng285; import org.testng.annotations.Test; public class Derived extends BugBase { @Test public void f1() { log(Thread.currentThread().getId()); } @Test public void f2() { log(Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng285/TestNG285Test.java000066400000000000000000000006331475274123300276340ustar00rootroot00000000000000package test.testng285; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.BaseTest; public class TestNG285Test extends BaseTest { @Test public void verifyBug() { addClass("test.testng285.Derived"); setParallel(XmlSuite.ParallelMode.METHODS); setThreadCount(5); run(); Assert.assertEquals(BugBase.m_threadIds.size(), 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng317/000077500000000000000000000000001475274123300245205ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng317/ClassA.java000066400000000000000000000022611475274123300265320ustar00rootroot00000000000000package test.testng317; import org.testng.annotations.Test; public class ClassA { @Test public void sameNameA() { printMethod(); } @Test(dependsOnMethods = "sameNameA") public void uniqueNameB() { printMethod(); } @Test(dependsOnMethods = "uniqueNameB") public void uniqueNameC() { printMethod(); } @Test(dependsOnMethods = "uniqueNameC") public void uniqueNameD() { printMethod(); } @Test(dependsOnMethods = "uniqueNameD") public void sameNameE() { printMethod(); } @Test(dependsOnMethods = "sameNameE") public void sameNameF() { printMethod(); } @Test(dependsOnMethods = "sameNameF") public void sameNameG() { printMethod(); } @Test(dependsOnMethods = "sameNameG") public void sameNameH() { printMethod(); } public void nullTest() { printMethod(); } protected void printMethod() { StackTraceElement[] sTrace = new Exception().getStackTrace(); String className = sTrace[0].getClassName(); String methodName = sTrace[1].getMethodName(); System.out.printf("*********** executing --- %s %s\n", className, methodName); VerifyTest.m_methods.add(className + "." + methodName); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng317/ClassB.java000066400000000000000000000016451475274123300265400ustar00rootroot00000000000000package test.testng317; import org.testng.annotations.Test; public class ClassB { @Test public void sameNameAA() { printMethod(); } @Test(dependsOnMethods = "sameNameAA") public void uniqueNameBB() { printMethod(); } @Test(dependsOnMethods = "uniqueNameBB") public void uniqueNameCC() { printMethod(); } @Test(dependsOnMethods = "uniqueNameCC") public void uniqueNameDD() { printMethod(); } @Test(dependsOnMethods = "uniqueNameDD") public void sameNameE() { printMethod(); } public void nullTest() { printMethod(); } protected void printMethod() { StackTraceElement[] sTrace = new Exception().getStackTrace(); String className = sTrace[0].getClassName(); String methodName = sTrace[1].getMethodName(); System.out.printf("*********** executing --- %s %s\n", className, methodName); VerifyTest.m_methods.add(className + "." + methodName); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng317/VerifyTest.java000066400000000000000000000011641475274123300274710ustar00rootroot00000000000000package test.testng317; import java.util.ArrayList; import java.util.List; import org.testng.TestNG; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import test.SimpleBaseTest; public class VerifyTest extends SimpleBaseTest { static List m_methods = new ArrayList<>(); @BeforeMethod public void before() { m_methods = new ArrayList<>(); } @Test public void verify() { TestNG tng = create(); tng.setTestClasses(new Class[] {test.testng317.ClassB.class, test.testng317.ClassA.class}); tng.run(); System.out.println("Methods:" + m_methods.size()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng37/000077500000000000000000000000001475274123300244375ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng37/NullParameterTest.java000066400000000000000000000006621475274123300307210ustar00rootroot00000000000000package test.testng37; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** This class/interface */ public class NullParameterTest { @Test @Parameters({"notnull", "nullvalue"}) public void nullParameter(String notNull, int mustBeNull) { Assert.assertNotNull(notNull, "not null parameter expected"); Assert.assertNull(mustBeNull, "null parameter expected"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng37/testng-37.xml000066400000000000000000000005501475274123300267140ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng387/000077500000000000000000000000001475274123300245275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng387/FailedDPTest.java000066400000000000000000000022531475274123300276440ustar00rootroot00000000000000package test.testng387; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * test for https://jira.opensymphony.com/browse/TESTNG-387 The invocation-numbers logic in * failed.xml is wrong for dataprovider and parallel=true * *

The test will throw exception when numbers are prime, so getFailedInvocationNumbers() should * be a list of prime numbers. * * @author freynaud */ public class FailedDPTest { static final List primes = Arrays.asList(2, 3, 5, 7); /** DP generating all number from 0 to 9. */ @DataProvider(name = "DP", parallel = true) public Iterator getData() { List list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(new Integer[] {i}); } return list.iterator(); } /** * Throws an exception for a prime number. * * @throws Exception */ @Test( dataProvider = "DP", groups = {"DPTest"}) public void isNotPrime(Integer i) throws Exception { if (primes.contains(i)) { throw new Exception(i + " is prime"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng387/TestNG387.java000066400000000000000000000015601475274123300270020ustar00rootroot00000000000000package test.testng387; import static org.testng.Assert.assertEqualsNoOrder; import java.util.List; import org.testng.*; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class TestNG387 extends SimpleBaseTest { @Test(invocationCount = 500) public void testInvocationCounterIsCorrectForMethodWithDataProvider() { final TestNG tng = create(FailedDPTest.class); tng.setThreadCount(1); tng.setParallel(XmlSuite.ParallelMode.NONE); tng.setPreserveOrder(true); final TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); ITestNGMethod method = tla.getTestContexts().get(0).getAllTestMethods()[0]; List failed = method.getFailedInvocationNumbers(); assertEqualsNoOrder(failed.toArray(), FailedDPTest.primes.toArray()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng56/000077500000000000000000000000001475274123300244405ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng56/ParallelTest.java000066400000000000000000000017621475274123300277050ustar00rootroot00000000000000package test.testng56; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** This class/interface */ public class ParallelTest { @BeforeClass public void setup() { System.out.println(Thread.currentThread().getId() + ":setup"); } @AfterClass public void teardown() { System.out.println(Thread.currentThread().getId() + ":teardown"); } @Test public void test1() { System.out.println(Thread.currentThread().getId() + ":test1"); } @Test(dependsOnMethods = {"test1"}) public void test2() { System.out.println(Thread.currentThread().getId() + ":test2"); } @Test public void test3() { System.out.println(Thread.currentThread().getId() + ":test3"); } @Test(dependsOnMethods = {"test3"}) public void test4() { System.out.println(Thread.currentThread().getId() + ":test4"); } @Test public void test5() { System.out.println(Thread.currentThread().getId() + ":test5"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng56/testng-56.xml000066400000000000000000000004511475274123300267160ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng59/000077500000000000000000000000001475274123300244435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng59/Test1.java000066400000000000000000000006261475274123300263120ustar00rootroot00000000000000package test.testng59; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** This class/interface */ public class Test1 { private boolean m_run = false; @Test public void test1() { m_run = true; } @AfterClass public void checkWasRun() { Assert.assertTrue(m_run, "test1() should have been run according to testng-59.xml"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng59/Test2.java000066400000000000000000000006261475274123300263130ustar00rootroot00000000000000package test.testng59; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** This class/interface */ public class Test2 { private boolean m_run = false; @Test public void test2() { m_run = true; } @AfterClass public void checkWasRun() { Assert.assertTrue(m_run, "test2() should have been run according to testng-59.xml"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng59/testng-59.xml000066400000000000000000000010221475274123300267170ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng674/000077500000000000000000000000001475274123300245265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng674/BeforeClassSkipExceptionTest.java000066400000000000000000000077301475274123300331360ustar00rootroot00000000000000package test.testng674; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class BeforeClassSkipExceptionTest extends SimpleBaseTest { @Test public void testIfTestMethodHasException() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); createTestNGInstanceAndRun( reporter, TestClassSampleContainer.SampleClassWithFailingBeforeClassMethod.class); } @Test public void testIfTestMethodHasExceptionInInheritance() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); createTestNGInstanceAndRun(reporter, TestClassSampleContainer.ChildClass.class); } @Test public void testExceptionDetailsWhenClassHasMultipleFailures() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); createTestNGInstanceAndRun( reporter, TestClassSampleContainer.SampleClassWithMultipleFailures.class); } @Test public void testExceptionDetailsWhenClassHasExplicitSkipInConfiguration() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); createTestNGInstanceAndRun( reporter, TestClassSampleContainer.SampleClassWithExplicitConfigSkip.class); } @Test public void testExceptionDetailsWhenConfigHasAlwaysRun() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); createTestNGInstanceAndRun( reporter, TestClassSampleContainer.SampleClassWithMultipleFailuresAndAlwaysRun.class); } @Test public void testExceptionDetailsUsingGroupsWithFailures() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); Class[] classes = { TestClassSampleContainer.GroupsContainer.GroupA.class, TestClassSampleContainer.GroupsContainer.GroupB.class }; createTestNGInstanceAndRun(reporter, 2, true, classes); } @Test public void testExceptionDetailsWhenFailuresExistInSuiteConfigs() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest1 = createXmlTest(xmlSuite, "Test1"); createXmlClass(xmlTest1, TestClassSampleContainer.SuiteFailureTestClass.class); XmlTest xmlTest2 = createXmlTest(xmlSuite, "Test2"); createXmlClass(xmlTest2, TestClassSampleContainer.RegularTestClass.class); TestNG tng = create(xmlSuite); ReportingListenerFor674 reporter = new ReportingListenerFor674(); tng.addListener((ITestNGListener) reporter); tng.run(); Assert.assertEquals(reporter.getErrors().size(), 2); for (Throwable error : reporter.getErrors()) { Assert.assertEquals(error.getMessage(), TestClassSampleContainer.ERROR_MSG); Assert.assertTrue(error instanceof RuntimeException); } } @Test public void testExceptionDetailsWhenFailuresExistInABaseClass() { ReportingListenerFor674 reporter = new ReportingListenerFor674(); Class[] classes = {TestClassSampleContainer.A.class, TestClassSampleContainer.B.class}; createTestNGInstanceAndRun(reporter, 2, false, classes); } private static void createTestNGInstanceAndRun( ReportingListenerFor674 reporter, Class... clazz) { createTestNGInstanceAndRun(reporter, 1, false, clazz); } private static void createTestNGInstanceAndRun( ReportingListenerFor674 reporter, int expectedCount, boolean useGroups, Class... clazzes) { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); if (useGroups) { xmlTest.addIncludedGroup("foo"); } for (Class clazz : clazzes) { createXmlClass(xmlTest, clazz); } TestNG tng = create(xmlSuite); tng.addListener((ITestNGListener) reporter); tng.run(); Assert.assertEquals(reporter.getErrors().size(), expectedCount); for (Throwable error : reporter.getErrors()) { Assert.assertEquals(error.getMessage(), TestClassSampleContainer.ERROR_MSG); Assert.assertTrue(error instanceof RuntimeException); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng674/ReportingListenerFor674.java000066400000000000000000000014521475274123300317620ustar00rootroot00000000000000package test.testng674; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.testng.*; import org.testng.xml.XmlSuite; public class ReportingListenerFor674 implements IReporter { private List errors = new ArrayList<>(); public void generateReport(List list, List suites, String s) { for (ISuite suite : suites) { for (ISuiteResult suiteResult : suite.getResults().values()) { ITestContext ctx = suiteResult.getTestContext(); Set results = ctx.getSkippedTests().getAllResults(); for (ITestResult result : results) { Throwable throwable = result.getThrowable(); errors.add(throwable); } } } } public List getErrors() { return errors; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng674/TestClassSampleContainer.java000066400000000000000000000044251475274123300323100ustar00rootroot00000000000000package test.testng674; import org.testng.SkipException; import org.testng.annotations.*; public class TestClassSampleContainer { public static final String ERROR_MSG = "GITHUB-674 Exception"; public static class SampleClassWithFailingBeforeClassMethod { @BeforeClass public void beforeClass() { throw new RuntimeException(ERROR_MSG); } @Test public void testMethod() {} } public static class ChildClass extends SampleClassWithFailingBeforeClassMethod {} public static class SampleClassWithMultipleFailures { @BeforeClass public void beforeClass() { throw new RuntimeException(ERROR_MSG); } @BeforeMethod public void beforeMethod() { throw new RuntimeException(ERROR_MSG); } @Test public void testMethod() {} } public static class SampleClassWithMultipleFailuresAndAlwaysRun { @BeforeClass public void beforeClass() { throw new RuntimeException(ERROR_MSG); } @BeforeMethod(alwaysRun = true) public void beforeMethod() { throw new RuntimeException(ERROR_MSG); } @Test public void testMethod() {} } public static class SampleClassWithExplicitConfigSkip { @BeforeClass public void beforeClass() { throw new SkipException(ERROR_MSG); } @Test public void testMethod() {} } public static class SuiteFailureTestClass { @BeforeSuite public void beforeSuite() { throw new SkipException(ERROR_MSG); } @Test public void testMethod() {} } public static class RegularTestClass { @Test public void testMethod() {} } public static class GroupsContainer { public static class GroupA { @BeforeGroups(groups = "foo") public void beforeGroups() { throw new RuntimeException(ERROR_MSG); } @Test(groups = "foo") public void testMethod() {} } public static class GroupB { @Test(groups = "foo") public void testMethod() {} } } public static class BaseSample { @BeforeSuite public void beforeSuite() { throw new RuntimeException(ERROR_MSG); } } public static class A extends BaseSample { @Test public void testMethod() {} } public static class B extends BaseSample { @Test public void testMethod() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng93/000077500000000000000000000000001475274123300244415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng93/SingleTestTest.java000066400000000000000000000007641475274123300302340ustar00rootroot00000000000000package test.testng93; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** This class/interface */ public class SingleTestTest { @BeforeMethod(groups = {"group1"}) public void shouldRunBefore() { System.out.println("Runs before"); } @Test(groups = {"group1"}) public void theFirstActualTest() { System.out.println("The first actual test"); } @Test public void theSecondActualTest() { System.out.println("The second actual test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/testng93/testng-93.xml000066400000000000000000000010111475274123300267110ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/000077500000000000000000000000001475274123300242305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/B.java000066400000000000000000000006131475274123300252540ustar00rootroot00000000000000package test.thread; import java.util.Map; import org.testng.annotations.Test; import org.testng.collections.Maps; public class B { public static Map m_threadIds = Maps.newConcurrentMap(); public static void setUp() { m_threadIds = Maps.newConcurrentMap(); } @Test public void f2() { Long id = Thread.currentThread().getId(); m_threadIds.put(id, id); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/BaseSequentialSample.java000066400000000000000000000010561475274123300311440ustar00rootroot00000000000000package test.thread; import java.util.Map; import org.testng.log4testng.Logger; public class BaseSequentialSample { protected void addId(String method, long id) { debug(method + " ID:" + id); getMap().put(id, id); } Map getMap() { Map result = Helper.getMap(getClass().getName()); debug("RETURNING MAP " + result + " THIS:" + this); return result; } protected void debug(String s) { Logger.getLogger(getClass()) .debug("[" + getClass().getName() + " " + Thread.currentThread().getId() + " " + "] " + s); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/BaseThreadTest.java000066400000000000000000000035571475274123300277470ustar00rootroot00000000000000package test.thread; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.Assert; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.collections.Sets; import test.SimpleBaseTest; public class BaseThreadTest extends SimpleBaseTest { private static Set m_threadIds; private static Map m_suitesMap; private static List m_strings; static void initThreadLog() { m_threadIds = Sets.newHashSet(); m_suitesMap = Maps.newHashMap(); m_strings = Lists.newArrayList(); } protected void logString(String s) { synchronized (m_strings) { log("BaseThreadTest", "Logging string:" + s); m_strings.add(s); } } public static List getStrings() { return m_strings; } protected void logCurrentThread() { logThread(Thread.currentThread().getId()); } protected void logThread(long threadId) { synchronized (m_threadIds) { log("BaseThreadTest", "Logging thread:" + threadId); m_threadIds.add(threadId); } } protected void logSuite(String suiteName, long time) { synchronized (m_suitesMap) { m_suitesMap.put(suiteName, time); } } static int getThreadCount() { synchronized (m_threadIds) { return m_threadIds.size(); } } static Map getSuitesMap() { return m_suitesMap; } protected void log(String cls, String s) { if (false) { System.out.println( "[" + cls + "] thread:" + Thread.currentThread().getId() + " hash:" + hashCode() + " " + s); } } protected void verifyThreads(int expected) { Assert.assertEquals( getThreadCount(), expected, "Ran on " + getThreadCount() + " threads instead of " + expected); } } DataProviderThreadPoolSizeSampleTest.java000066400000000000000000000035051475274123300342220ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/threadpackage test.thread; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderThreadPoolSizeSampleTest extends BaseThreadTest { @BeforeClass(alwaysRun = true) public void setUp() { log(getClass().getName(), "Init log ids"); initThreadLog(); } @DataProvider(parallel = true) public Object[][] parallelDataProvider() { return createArray(); } @DataProvider public Object[][] sequentialDataProvider() { return createArray(); } private Object[][] createArray() { int i = 0; return new Object[][] { new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, new Object[] {i++}, }; } @Test(dataProvider = "sequentialDataProvider", groups = "sequential") public void fSequential(Integer p) { long n = Thread.currentThread().getId(); log(getClass().getName(), "Sequential"); logThread(n); } @Test(dataProvider = "parallelDataProvider", groups = "parallel") public void fParallel(Integer p) { long n = Thread.currentThread().getId(); log(getClass().getName(), "Parallel"); logThread(n); } // @Test(dependsOnMethods = {"f1"}) // public void verify() { // int expected = 3; // Assert.assertEquals(m_threadIds.size(), expected, // "Should have run on " + expected + " threads but ran on " + m_threadIds.size()); // } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/DataProviderThreadPoolSizeTest.java000066400000000000000000000020431475274123300331330ustar00rootroot00000000000000package test.thread; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class DataProviderThreadPoolSizeTest extends SimpleBaseTest { @Test public void shouldUseDefaultDataProviderThreadCount() { TestNG tng = create(DataProviderThreadPoolSizeSampleTest.class); tng.setGroups("parallel"); tng.run(); Assert.assertEquals(DataProviderThreadPoolSizeSampleTest.getThreadCount(), 10); } @Test public void shouldNotUseThreadsIfNotUsingParallel() { TestNG tng = create(DataProviderThreadPoolSizeSampleTest.class); tng.setGroups("sequential"); tng.run(); Assert.assertEquals(DataProviderThreadPoolSizeSampleTest.getThreadCount(), 1); } @Test public void shouldUseSpecifiedDataProviderThreadCount() { TestNG tng = create(DataProviderThreadPoolSizeSampleTest.class); tng.setGroups("parallel"); tng.setDataProviderThreadCount(3); tng.run(); Assert.assertEquals(DataProviderThreadPoolSizeSampleTest.getThreadCount(), 3); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/FactorySampleTest.java000066400000000000000000000003571475274123300305110ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test public class FactorySampleTest { @Factory public Object[] init() { return new Object[] { new B(), new B(), }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/FactoryTest.java000066400000000000000000000024411475274123300273430ustar00rootroot00000000000000package test.thread; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; public class FactoryTest { @Test( description = "In non-parallel mode, we should only have one thread id for the two methods invoked on B") public void verifyFactoryNotParallel() { runTest(null, 1); } @Test( description = "In parallel mode 'methods', we should have as many thread id's as there are test methods on B (2).") public void verifyFactoryParallelMethods() { runTest(XmlSuite.ParallelMode.METHODS, 2); } @Test public void verifyFactoryParallelTests() { runTest(XmlSuite.ParallelMode.TESTS, 1); } private void runTest(XmlSuite.ParallelMode parallelMode, int expectedThreadIdCount) { TestNG tng = new TestNG(); tng.setTestClasses(new Class[] {FactorySampleTest.class}); if (parallelMode != null) { tng.setParallel(parallelMode); } TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); B.setUp(); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 2); Assert.assertEquals(B.m_threadIds.size(), expectedThreadIdCount); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/Github1636Sample.java000066400000000000000000000011321475274123300277740ustar00rootroot00000000000000package test.thread; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.testng.annotations.Test; public class Github1636Sample { private static Map map = new ConcurrentHashMap<>(); static Set threads = Collections.newSetFromMap(map); @Test public void test1() { threads.add(Thread.currentThread().getId()); } @Test public void test2() { threads.add(Thread.currentThread().getId()); } @Test public void test3() { threads.add(Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/Helper.java000066400000000000000000000006231475274123300263130ustar00rootroot00000000000000package test.thread; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Helper { private static final Map> m_maps = new ConcurrentHashMap<>(); public static Map getMap(String className) { return m_maps.computeIfAbsent(className, cn -> new ConcurrentHashMap<>()); } public static void reset() { m_maps.clear(); } } MultiThreadedDependentSampleTest.java000066400000000000000000000037771475274123300334160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/threadpackage test.thread; import java.util.List; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.collections.Lists; public class MultiThreadedDependentSampleTest { public static List m_methods = Lists.newArrayList(); @BeforeClass public void bc() {} @AfterClass public void ac() {} @BeforeMethod public void bm() {} @AfterMethod public void am() {} @Test(groups = "1") public void a1() { logThread(); log("a1"); } @Test(groups = "1") public void a2() { logThread(); log("a2"); } @Test(groups = "1") public void a3() { logThread(); log("a3"); } @Test(groups = "2", dependsOnGroups = "1") public void b1() { logThread(); log("b1"); } @Test(groups = "2", dependsOnGroups = "1") public void b2() { logThread(); log("b2"); } @Test(groups = "2", dependsOnGroups = "1") public void b3() { logThread(); log("b3"); } @Test(groups = "2", dependsOnGroups = "1") public void b4() { logThread(); log("b4"); } @Test(groups = "2", dependsOnGroups = "1") public void b5() { logThread(); log("b5"); } @Test(dependsOnGroups = "2") public void c1() { logThread(); log("c1"); } @Test(dependsOnGroups = {"1"}) public void d() { logThread(); log("d"); } @Test public void x() { log("x"); } @Test public void y() { log("y"); } @Test public void z() { log("z"); } @Test public void t() { log("t"); } private void logThread() { try { // With a lower value, tests fail sometimes Thread.sleep(40); } catch (InterruptedException e) { } long id = Thread.currentThread().getId(); Helper.getMap(getClass().getName()).put(id, id); } private void log(String string) { synchronized (m_methods) { m_methods.add(string); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/MultiThreadedDependentTest.java000066400000000000000000000047241475274123300323240ustar00rootroot00000000000000package test.thread; import java.util.Arrays; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; /** * Test that classes with dependent methods are still run in different threads and in the correct * order. */ public class MultiThreadedDependentTest extends SimpleBaseTest { /** * Make sure that the topological order is preserved and that if the TestNG runner is configured * to run n threads, the dependent methods are using these n threads. */ private void assertOrder(List methods) { List expectedMethods = Arrays.asList( new String[] { "a1", "a2", "a3", "b1", "b2", "b3", "b4", "b5", "c1", "d", "x", "y", "z", "t" }); int size = expectedMethods.size(); Assert.assertEquals(methods.size(), size); for (String em : expectedMethods) { Assert.assertTrue(methods.contains(em)); } Map map = Maps.newHashMap(); for (String m : methods) { map.put(m, Boolean.TRUE); if ("b1".equals(m) || "b2".equals(m) || "b3".equals(m) || "b4".equals(m) || "b5".equals(m)) { Assert.assertTrue(map.get("a1")); Assert.assertTrue(map.get("a2")); Assert.assertTrue(map.get("a3")); } if ("d".equals(m)) { Assert.assertTrue(map.get("a1")); Assert.assertTrue(map.get("a2")); } if ("c1".equals(m)) { Assert.assertTrue(map.get("b1")); Assert.assertTrue(map.get("b2")); } } Assert.assertEquals(map.size(), size); for (Boolean val : map.values()) { Assert.assertTrue(val); } } @Test public void test2Threads() { test(2); } @Test public void test3Threads() { test(3); } private void test(int threadCount) { Helper.reset(); MultiThreadedDependentSampleTest.m_methods = Lists.newArrayList(); TestNG tng = create(MultiThreadedDependentSampleTest.class); tng.setThreadCount(threadCount); tng.setParallel(XmlSuite.ParallelMode.METHODS); Map map = Helper.getMap(MultiThreadedDependentSampleTest.class.getName()); synchronized (map) { tng.run(); Assert.assertTrue(map.size() > 1, "Map size:" + map.size() + " expected more than 1"); assertOrder(MultiThreadedDependentSampleTest.m_methods); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ParallelSuiteTest.java000066400000000000000000000136041475274123300305050ustar00rootroot00000000000000package test.thread; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class ParallelSuiteTest extends SimpleBaseTest { @Test public void suitesShouldRunInParallel1() { runTest( 5, 2, 2, null, Arrays.asList( getPathToParallelResource("simple-suite-parallel-1.xml"), getPathToParallelResource("simple-suite-parallel-2.xml"))); } @Test public void suitesShouldRunInParallel2() { runTest( 5, 3, 3, null, Collections.singletonList(getPathToParallelResource("simple-suite-parallel-0.xml"))); } @Test(description = "Number of threads (2) is less than number of suites (3)") public void suitesShouldRunInParallel3() { final int SUITE_THREAD_POOL_SIZE = 2; TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); tng.setSuiteThreadPoolSize(SUITE_THREAD_POOL_SIZE); tng.setTestSuites( Collections.singletonList(getPathToParallelResource("simple-suite-parallel-0.xml"))); tng.addListener((ITestNGListener) tla); BaseThreadTest.initThreadLog(); tng.run(); // Shouldn't not deadlock Assert.assertEquals(BaseThreadTest.getThreadCount(), SUITE_THREAD_POOL_SIZE); } @Test public void suitesShouldRunInParallel4() { final int TOTAL_SUITE_COUNT_INCLUDING_DUPLICATES = 8; runTest( 10, TOTAL_SUITE_COUNT_INCLUDING_DUPLICATES, TOTAL_SUITE_COUNT_INCLUDING_DUPLICATES, null, Arrays.asList( getPathToParallelResource("suite-parallel-1.xml"), getPathToParallelResource("suite-parallel-2.xml"), getPathToParallelResource("suite-parallel-2-1.xml"), getPathToParallelResource("suite-parallel-2-2.xml"))); } @Test public void suitesShouldRunInParallel5() { runTest( 5, 5, 7, null, Collections.singletonList(getPathToParallelResource("suite-parallel-0.xml"))); } @Test(description = "Number of threads (2) is less than level of suites (3)") public void suitesShouldRunInParallel6() { runTest( 2, 2, 7, null, Collections.singletonList(getPathToParallelResource("suite-parallel-0.xml"))); } @Test( description = "If suiteThreadPoolSize and randomizeSuites are not specified" + " suites should run in order specified in XML") public void suitesShouldRunInOrder() { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); tng.setTestSuites( Collections.singletonList(getPathToParallelResource("simple-suite-parallel-0.xml"))); tng.addListener((ITestNGListener) tla); BaseThreadTest.initThreadLog(); tng.run(); Map suitesMap = BaseThreadTest.getSuitesMap(); Assert.assertEquals(BaseThreadTest.getThreadCount(), 1); Assert.assertEquals(suitesMap.keySet().size(), 3); final String SUITE_NAME_PREFIX = "Suite Parallel "; if (suitesMap.get(SUITE_NAME_PREFIX + 1) > suitesMap.get(SUITE_NAME_PREFIX + 2)) { Assert.fail( "Suite " + (SUITE_NAME_PREFIX + 1) + " should have run before " + (SUITE_NAME_PREFIX + 2)); } Assert.assertTrue(suitesMap.get(SUITE_NAME_PREFIX + 2) <= suitesMap.get(SUITE_NAME_PREFIX + 0)); } @Test(description = "Number of threads (1) is less than number of levels of suites (2)") public void suitesShouldRun1() { runTest( 1, 1, 3, true, Collections.singletonList(getPathToParallelResource("simple-suite-parallel-0.xml"))); } @Test(description = "Child suite should obey threadCount parameter") public void childSuiteObeyParentThreadCount() { /* parent suite has no tests, so only child suite counts */ final int EXPECTED_SUITE_COUNT = 1; runTest( 1, 2, XmlSuite.ParallelMode.CLASSES, 2, EXPECTED_SUITE_COUNT, null, Arrays.asList(getPathToParallelResource("inherit-thread-count-parent.yaml"))); } private void runTest( int suiteThreadPoolSize, int expectedThreadCount, int expectedSuiteCount, Boolean randomizeSuites, List paths) { runTest( suiteThreadPoolSize, null, null, expectedThreadCount, expectedSuiteCount, randomizeSuites, paths); } private void runTest( int suiteThreadPoolSize, Integer threadCount, XmlSuite.ParallelMode parallelMode, int expectedThreadCount, int expectedSuiteCount, Boolean randomizeSuites, List paths) { TestListenerAdapter tla = new TestListenerAdapter(); TestNG tng = create(); tng.setSuiteThreadPoolSize(suiteThreadPoolSize); if (threadCount != null) { tng.setThreadCount(threadCount); } if (parallelMode != null) { tng.setParallel(parallelMode); } tng.setTestSuites(paths); tng.addListener((ITestNGListener) tla); if (null != randomizeSuites) { tng.setRandomizeSuites(randomizeSuites); } BaseThreadTest.initThreadLog(); tng.run(); Assert.assertEquals( BaseThreadTest.getThreadCount(), expectedThreadCount, "Thread count expected:" + expectedThreadCount + " actual:" + BaseThreadTest.getThreadCount()); Assert.assertEquals( BaseThreadTest.getSuitesMap().keySet().size(), expectedSuiteCount, "Suite count is incorrect"); } private static String getPathToParallelResource(String resourceName) { return getPathToResource(String.format("parallel-suites/%s", resourceName)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ParallelTestTest.java000066400000000000000000000133651475274123300303370ustar00rootroot00000000000000package test.thread; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; import org.testng.SkipException; import org.testng.TestNG; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Lists; import org.testng.xml.SuiteXmlParser; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.BaseTest; public class ParallelTestTest extends BaseTest { @DataProvider private static Object[][] verifyParallelDp() { return new Object[][] { // isCommandLine, parallelMode, expectedThreadCount {true, XmlSuite.ParallelMode.NONE, 1}, {false, XmlSuite.ParallelMode.NONE, 1}, {true, XmlSuite.ParallelMode.TESTS, 2}, {false, XmlSuite.ParallelMode.TESTS, 2}, {true, XmlSuite.ParallelMode.METHODS, 4}, {false, XmlSuite.ParallelMode.METHODS, 4}, {true, XmlSuite.ParallelMode.CLASSES, 2}, {false, XmlSuite.ParallelMode.CLASSES, 2}, {true, XmlSuite.ParallelMode.INSTANCES, 4}, {false, XmlSuite.ParallelMode.INSTANCES, 4} }; } @Test(dataProvider = "verifyParallelDp") public void verifyParallel( boolean isCommandLine, XmlSuite.ParallelMode parallelMode, int expectedThreadCount) { verifyExpected( isCommandLine, parallelMode, expectedThreadCount, Test1Test.class, Test2Test.class); } @DataProvider private static Object[][] verifyParallelWithFactoryDp() { return new Object[][] { // isCommandLine, parallelMode, expectedThreadCount {true, XmlSuite.ParallelMode.NONE, 1}, {false, XmlSuite.ParallelMode.NONE, 1}, {true, XmlSuite.ParallelMode.INSTANCES, 4}, {false, XmlSuite.ParallelMode.INSTANCES, 4} }; } @Test(dataProvider = "verifyParallelWithFactoryDp") // TODO use "verifyParallelDp" public void verifyParallelWithFactory( boolean isCommandLine, XmlSuite.ParallelMode parallelMode, int expectedThreadCount) { verifyExpected( isCommandLine, parallelMode, expectedThreadCount, ParallelWithFactorySampleTest.class); } @Test public void testParallelModeInheritanceInCommandlineMode() throws FileNotFoundException { SuiteXmlParser parser = new SuiteXmlParser(); String file = "src/test/resources/1636.xml"; XmlSuite xmlSuite = parser.parse(file, new FileInputStream(file), true); TestNG tng = new TestNG(); tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); assertThat(Github1636Sample.threads).hasSize(3); } @Test public void testJarXmlSuiteObeyCommandLine() { final String file = "build/resources/test/2532.zip"; final String suiteFileName = "2532.xml"; final int threadCount = 3; zipResource(suiteFileName, file); TestNG tng = new TestNG(); tng.setXmlPathInJar(suiteFileName); tng.setTestJar(file); tng.setThreadCount(threadCount); tng.setParallel(XmlSuite.ParallelMode.METHODS); tng.run(); assertThat(Github1636Sample.threads).hasSize(threadCount); } @Test public void testXmlSuiteObeyCommandLine() { final String file = "build/resources/test/2532.xml"; final int threadCount = 3; TestNG tng = new TestNG(); tng.setTestSuites(Collections.singletonList(file)); tng.setThreadCount(threadCount); tng.setParallel(XmlSuite.ParallelMode.METHODS); tng.run(); assertThat(Github1636Sample.threads).hasSize(threadCount); } private void createTest(XmlSuite xmlSuite, Class clazz) { XmlTest result = new XmlTest(xmlSuite); List classes = result.getXmlClasses(); XmlClass xmlClass = new XmlClass(clazz); classes.add(xmlClass); } private void verifyExpected( boolean isCommandLine, XmlSuite.ParallelMode parallelMode, int expectedThreadCount, Class... classes) { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("ParallelTestTest"); xmlSuite.setParallel(parallelMode); for (Class clazz : classes) { createTest(xmlSuite, clazz); } TestNG tng = new TestNG(); if (isCommandLine) { tng.setCommandLineSuite(xmlSuite); } else { tng.setXmlSuites(Collections.singletonList(xmlSuite)); } Helper.reset(); tng.run(); List> maps = Lists.newArrayList(); for (Class clazz : classes) { maps.add(Helper.getMap(clazz.getName())); } Map mergedMap = new HashMap<>(); for (Map m : maps) { mergedMap.putAll(m); } assertThat(mergedMap).hasSize(expectedThreadCount); } private void zipResource(String resourceName, String targetFilePath) { InputStream suiteStream = this.getClass().getClassLoader().getResourceAsStream(resourceName); try { File targetFile = new File(targetFilePath); FileOutputStream targetFileStream = new FileOutputStream(targetFile); ZipOutputStream zipSuiteStream = new ZipOutputStream(targetFileStream); zipSuiteStream.putNextEntry(new ZipEntry(resourceName)); byte[] suiteByteData = IOUtils.toByteArray(suiteStream); zipSuiteStream.write(suiteByteData, 0, suiteByteData.length); zipSuiteStream.closeEntry(); zipSuiteStream.close(); } catch (IOException e) { throw new SkipException(String.format("Error writing zip to %s", targetFilePath), e); } } @AfterMethod private void clearThreadCount() { Github1636Sample.threads.clear(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ParallelWithFactorySampleTest.java000066400000000000000000000012461475274123300330200ustar00rootroot00000000000000package test.thread; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class ParallelWithFactorySampleTest extends BaseSequentialSample { private int m_n; @DataProvider public static Object[][] dp() { return new Object[][] {new Object[] {42}, new Object[] {43}}; } @Factory(dataProvider = "dp") public ParallelWithFactorySampleTest(int n) { m_n = n; } protected int getN() { return m_n; } @Test public void f1() { addId("f1 " + getN(), Thread.currentThread().getId()); } @Test public void f2() { addId("f2", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/PriorityInSingleThreadTest.java000066400000000000000000000010071475274123300323330ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class PriorityInSingleThreadTest extends BaseThreadTest { @Test(priority = -10) public void f1() { logCurrentThread(); } @Test(priority = -5) public void f2() { logCurrentThread(); } @Test(priority = 0) public void f3() { logCurrentThread(); } @Test(priority = 5) public void f4() { logCurrentThread(); } @Test(priority = 10) public void f5() { logCurrentThread(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/Sample1.java000066400000000000000000000002741475274123300264000ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; public class Sample1 extends BaseThreadTest { @Test public void s1() { logThread(Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/Sample2.java000066400000000000000000000006121475274123300263750ustar00rootroot00000000000000package test.thread; import org.testng.ITestContext; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Sample2 extends BaseThreadTest { @BeforeMethod public void before(ITestContext ctx) { logSuite(ctx.getSuite().getName(), System.currentTimeMillis()); } @Test public void s1() { logThread(Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SequentialSample2Test.java000066400000000000000000000007051475274123300312730ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class SequentialSample2Test extends BaseSequentialSample { public void f1() { addId("SequentialSample2Test.f1()", Thread.currentThread().getId()); } public void f2() { addId("SequentialSample2Test.f2()", Thread.currentThread().getId()); } public void f3() { addId("SequentialSample2Test.f3()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SequentialSample3Test.java000066400000000000000000000007051475274123300312740ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class SequentialSample3Test extends BaseSequentialSample { public void f1() { addId("SequentialSample3Test.f1()", Thread.currentThread().getId()); } public void f2() { addId("SequentialSample3Test.f2()", Thread.currentThread().getId()); } public void f3() { addId("SequentialSample3Test.f3()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SequentialSampleTest.java000066400000000000000000000007011475274123300312050ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class SequentialSampleTest extends BaseSequentialSample { public void f1() { addId("SequentialSampleTest.f1()", Thread.currentThread().getId()); } public void f2() { addId("SequentialSampleTest.f2()", Thread.currentThread().getId()); } public void f3() { addId("SequentialSampleTest.f3()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SequentialTest.java000066400000000000000000000042651475274123300300540ustar00rootroot00000000000000package test.thread; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.BaseTest; public class SequentialTest extends BaseTest { @Test public void verifySequential1() { verifySequential(1); } @Test public void verifySequential2() { verifySequential(2); } @Test public void verifySequential3() { verifySequential(3); } @Test public void verifySingleThreaded1() { verifySingleThreaded(1); } @Test public void verifySingleThreaded2() { verifySingleThreaded(2); } @Test public void verifySingleThreaded3() { verifySingleThreaded(3); } public void verifySequential(int threadCount) { runTest( threadCount, SequentialSampleTest.class.getName(), SequentialSample2Test.class.getName(), SequentialSample3Test.class.getName()); } public void verifySingleThreaded(int threadCount) { runTest( threadCount, SingleThreadedSampleTest.class.getName(), SingleThreadedSample2Test.class.getName(), SingleThreadedSample3Test.class.getName()); } private void runTest(int threadCount, String... classes) { Helper.reset(); for (String c : classes) { addClass(c); } setParallel(XmlSuite.ParallelMode.METHODS); setThreadCount(threadCount); run(); Map[] maps = new Map[] { Helper.getMap(classes[0]), Helper.getMap(classes[1]), Helper.getMap(classes[2]), }; for (Map m : maps) { Assert.assertEquals(m.size(), 1); } long[] ids = new long[] { maps[0].keySet().iterator().next(), maps[1].keySet().iterator().next(), maps[2].keySet().iterator().next(), }; Map verifyMap = new HashMap<>(); for (long id : ids) { verifyMap.put(id, id); } Assert.assertEquals(verifyMap.size(), threadCount); debug("COUNT:" + threadCount + " THREAD ID'S:" + ids[0] + " " + ids[1] + " " + ids[2]); } private void debug(String s) { Logger.getLogger(getClass()).debug("[SequentialTest] " + s); } } SingleThreadForParallelMethodsTest.java000066400000000000000000000011761475274123300337020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/threadpackage test.thread; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.BaseTest; public class SingleThreadForParallelMethodsTest extends BaseTest { @Test(description = "GITHUB #1066: Regression is in priority. It broke parallel mode") public void testPriorityDoesNotAffectSingleThreadOrder() { PriorityInSingleThreadTest.initThreadLog(); Helper.reset(); addClass(PriorityInSingleThreadTest.class); setParallel(XmlSuite.ParallelMode.METHODS); setThreadCount(10); run(); Assert.assertEquals(PriorityInSingleThreadTest.getThreadCount(), 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SingleThreadedSample2Test.java000066400000000000000000000007551475274123300320500ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class SingleThreadedSample2Test extends BaseSequentialSample { @Test public void f1() { addId("SingleThreadedSample2Test.f1()", Thread.currentThread().getId()); } @Test public void f2() { addId("SingleThreadedSample2Test.f2()", Thread.currentThread().getId()); } @Test public void f3() { addId("SingleThreadedSample2Test.f3()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SingleThreadedSample3Test.java000066400000000000000000000010471475274123300320440ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class SingleThreadedSample3Test extends BaseSequentialSample { @Test public void f1() { addId("SingleThreadedSample3Test.f1()", Thread.currentThread().getId()); } @Test // (dependsOnMethods = "f1") public void f2() { addId("SingleThreadedSample3Test.f2()", Thread.currentThread().getId()); } @Test // (dependsOnMethods = "f2") public void f3() { addId("SingleThreadedSample3Test.f3()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SingleThreadedSampleTest.java000066400000000000000000000007511475274123300317620ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; @Test(singleThreaded = true) public class SingleThreadedSampleTest extends BaseSequentialSample { @Test public void f1() { addId("SingleThreadedSampleTest.f1()", Thread.currentThread().getId()); } @Test public void f2() { addId("SingleThreadedSampleTest.f2()", Thread.currentThread().getId()); } @Test public void f3() { addId("SingleThreadedSampleTest.f3()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/SuiteThreadCountTest.java000066400000000000000000000014511475274123300311660ustar00rootroot00000000000000package test.thread; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import org.testng.internal.thread.ThreadUtil; /** * Test for test level thread-count. * * @author Alex Popescu */ public class SuiteThreadCountTest { private Set m_threads = Collections.synchronizedSet(new HashSet()); @Test public void test1() { m_threads.add(ThreadUtil.currentThreadInfo()); } @Test public void test2() { m_threads.add(ThreadUtil.currentThreadInfo()); } @AfterClass public void checkThreading() { Assert.assertEquals(m_threads.size(), 2, "Test should use 2 threads (suite level)"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/Test1Test.java000066400000000000000000000005311475274123300267320ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; public class Test1Test extends BaseSequentialSample { @Test public void f11() { debug("f11"); addId("Test1Test.f11()", Thread.currentThread().getId()); } @Test public void f12() { debug("f12"); addId("Test1Test.f12()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/Test2Test.java000066400000000000000000000005311475274123300267330ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; public class Test2Test extends BaseSequentialSample { @Test public void f21() { debug("f21"); addId("Test2Test.f21()", Thread.currentThread().getId()); } @Test public void f22() { debug("f22"); addId("Test2Test.f22()", Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/TestThreadCountTest.java000066400000000000000000000015621475274123300310170ustar00rootroot00000000000000package test.thread; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import org.testng.internal.thread.ThreadUtil; /** * Test for test level thread-count. * * @author Alex Popescu */ public class TestThreadCountTest { private Set m_threads = Collections.synchronizedSet(new HashSet()); @Test public void test1() { m_threads.add(ThreadUtil.currentThreadInfo()); } @Test public void test2() { m_threads.add(ThreadUtil.currentThreadInfo()); } @Test public void test3() { m_threads.add(ThreadUtil.currentThreadInfo()); } @AfterClass public void checkThreading() { Assert.assertEquals(m_threads.size(), 3, "Test should use 3 threads"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ThreadPoolSampleBugTest.java000066400000000000000000000013271475274123300315770ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; public class ThreadPoolSampleBugTest { private static final long TIMEOUT = 500; @Test(invocationCount = 1, threadPoolSize = 5) public void shouldPass1() throws InterruptedException { Thread.sleep(TIMEOUT); } @Test(invocationCount = 2, threadPoolSize = 5) public void shouldPass2() throws InterruptedException { Thread.sleep(TIMEOUT); } @Test(timeOut = 10, invocationCount = 1, threadPoolSize = 5) public void shouldFail1() throws InterruptedException { Thread.sleep(TIMEOUT); } @Test(timeOut = 10, invocationCount = 2, threadPoolSize = 5) public void shouldFail2() throws InterruptedException { Thread.sleep(TIMEOUT); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ThreadPoolSizeBase.java000066400000000000000000000005621475274123300305650ustar00rootroot00000000000000package test.thread; import org.testng.annotations.BeforeClass; public class ThreadPoolSizeBase extends BaseThreadTest { @BeforeClass public void setUp() { log(getClass().getName(), "Init log ids"); initThreadLog(); } protected void logThread() { long n = Thread.currentThread().getId(); log(getClass().getName(), ""); logThread(n); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ThreadPoolSizeSampleTest.java000066400000000000000000000003451475274123300317730ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; public class ThreadPoolSizeSampleTest { @Test(threadPoolSize = 2, timeOut = 100) public void willPassBug() throws InterruptedException { Thread.sleep(500); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ThreadPoolSizeTest.java000066400000000000000000000004541475274123300306320ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; public class ThreadPoolSizeTest extends ThreadPoolSizeBase { @Test(invocationCount = 5, threadPoolSize = 3) public void f1() { logThread(); } @Test(dependsOnMethods = {"f1"}) public void verify() { verifyThreads(3); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ThreadPoolSizeWithTimeOutTest.java000066400000000000000000000014641475274123300327770ustar00rootroot00000000000000package test.thread; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; public class ThreadPoolSizeWithTimeOutTest extends ThreadPoolSizeBase { @Test(invocationCount = 5, threadPoolSize = 3, timeOut = 1000) public void f1() { logThread(); } @Test(dependsOnMethods = {"f1"}) public void verify() { verifyThreads(3); } @Test public void threadPoolAndTimeOutShouldFail() { TestNG tng = create(ThreadPoolSizeSampleTest.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); assertThat(tla.getPassedTests()).isEmpty(); assertThat(tla.getFailedTests()).hasSize(1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/ThreadTest.java000066400000000000000000000011641475274123300271440ustar00rootroot00000000000000package test.thread; import org.testng.annotations.Test; import test.BaseTest; public class ThreadTest extends BaseTest { @Test( groups = "broken", description = "This can be fixed by using sets instead of lists in DynamicGraph, but more failures happen then") public void timeoutAndInvocationCountShouldFail() { addClass(ThreadPoolSampleBugTest.class.getName()); run(); String[] passed = {"shouldPass1", "shouldPass2"}; String[] failed = {"shouldFail1", "shouldFail2"}; verifyTests("Passed", passed, getPassedTests()); verifyTests("Failed", failed, getFailedTests()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/TrueParallelSampleTest.java000066400000000000000000000011751475274123300314750ustar00rootroot00000000000000package test.thread; import java.util.Random; import org.testng.annotations.Test; @Test public class TrueParallelSampleTest extends BaseThreadTest { static Random random = new Random(System.currentTimeMillis()); private void log(String s) { logString(s); try { Thread.sleep(random.nextInt(10)); } catch (InterruptedException ex) { Thread.yield(); } logString(s); logCurrentThread(); } public void m1() { log("m1"); } public void m2() { log("m2"); } public void m3() { log("m3"); } public void m4() { log("m4"); } public void m5() { log("m5"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/TrueParallelTest.java000066400000000000000000000032061475274123300303300ustar00rootroot00000000000000package test.thread; import java.util.Arrays; import java.util.List; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; /** * Attempt to make sure that we are truly running methods in parallel. The best I can think of right * now is to run the tests a few times in a row and verify the ordering is never the same. */ public class TrueParallelTest extends SimpleBaseTest { @Test public void shouldRunInParallel() { boolean success = false; for (int i = 0, count = Runtime.getRuntime().availableProcessors() * 4; i < count; i++) { XmlSuite s = createXmlSuite("TrueParallel"); createXmlTest(s, "Test", TrueParallelSampleTest.class.getName()); TestNG tng = create(); s.setParallel(XmlSuite.ParallelMode.METHODS); tng.setXmlSuites(Arrays.asList(s)); BaseThreadTest.initThreadLog(); tng.run(); // A sequential result will look like "m1 m1 m3 m3 m2 m2 m4 m4 m5 m5". A properly // multithreaded result will have at least one non-consecutive different pair: // "m1 m1 m3 m2 m4 m4 m2 m3 m5 m5" List strings = TrueParallelSampleTest.getStrings(); boolean ii = isInterleaved(strings); success = success || ii; // System.out.println(strings + " -> " + ii); } Assert.assertTrue(success, "Couldn't find any interleaved test method run"); } private boolean isInterleaved(List strings) { for (int i = 0; i < strings.size(); i += 2) { if (!strings.get(i).equals(strings.get(i + 1))) { return true; } } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue188/000077500000000000000000000000001475274123300256215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue188/Issue188TestSample.java000066400000000000000000000022151475274123300320170ustar00rootroot00000000000000package test.thread.issue188; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Issue188TestSample { public static final Map> timestamps = new ConcurrentHashMap<>(); private static final Random random = new Random(); @BeforeMethod public void logTime(ITestResult itr) { String txt = Reporter.getCurrentTestResult().getTestContext().getName() + "_" + itr.getMethod().getQualifiedName(); timestamps .computeIfAbsent(System.currentTimeMillis(), k -> ConcurrentHashMap.newKeySet()) .add(txt); } @Test public void sampleTest() { sleepSilently(); } @Test public void anotherSampleTest() { sleepSilently(); } private void sleepSilently() { try { TimeUnit.MILLISECONDS.sleep(500 * random.nextInt(10)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue188/IssueTest.java000066400000000000000000000044201475274123300304140ustar00rootroot00000000000000package test.thread.issue188; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.assertj.core.api.Assertions; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.internal.RuntimeBehavior; import org.testng.xml.XmlSuite; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test public void testSuiteLevelParallelMode() { System.setProperty(RuntimeBehavior.STRICTLY_HONOUR_PARALLEL_MODE, "true"); try { TestNG testng = new TestNG(); XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setParallel(XmlSuite.ParallelMode.METHODS); xmlSuite.setThreadCount(10); xmlSuite.setName("Parallel Issue Suite"); createXmlTest(xmlSuite, "Test1", Issue188TestSample.class); createXmlTest(xmlSuite, "Test2", Issue188TestSample.class); createXmlTest(xmlSuite, "Test3", Issue188TestSample.class); testng.setXmlSuites(Collections.singletonList(xmlSuite)); testng.run(); Set timestamps = Issue188TestSample.timestamps.keySet(); if (timestamps.size() == 1) { Assertions.assertThat(Issue188TestSample.timestamps.values().iterator().next()) .withFailMessage( "Since all tests were started simultaneously,test method count should have been 6") .hasSize(6); } else { List keyset = Issue188TestSample.timestamps.keySet().stream().sorted().collect(Collectors.toList()); String allTimeStamps = keyset.stream().map(Objects::toString).collect(Collectors.joining(",")); long prev = keyset.get(0); for (int i = 1; i < keyset.size(); i++) { long current = keyset.get(i); long diff = current - prev; Assertions.assertThat(diff) .withFailMessage( "Test methods should have started within a lag of max 40 ms but it was " + diff + " ms [" + allTimeStamps + "]") .isLessThanOrEqualTo(40); prev = current; } } } finally { System.setProperty(RuntimeBehavior.STRICTLY_HONOUR_PARALLEL_MODE, "false"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue2361/000077500000000000000000000000001475274123300256745ustar00rootroot00000000000000AnotherChildClassExample.java000066400000000000000000000002501475274123300333230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue2361package test.thread.issue2361; import org.testng.annotations.Test; @Test(singleThreaded = true) public class AnotherChildClassExample extends BaseTestClassExample {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue2361/BaseTestClassExample.java000066400000000000000000000015371475274123300325610ustar00rootroot00000000000000package test.thread.issue2361; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.testng.Assert.assertEquals; import java.util.concurrent.atomic.AtomicInteger; import org.testng.annotations.Test; @Test(singleThreaded = true) public class BaseTestClassExample { private final AtomicInteger currentTests = new AtomicInteger(); protected void test() { int currentTests = this.currentTests.incrementAndGet(); try { assertEquals(currentTests, 1); MILLISECONDS.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { this.currentTests.decrementAndGet(); } } @Test public void test1() { test(); } @Test public void test2() { test(); } @Test public void test3() { test(); } @Test public void test4() { test(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue2361/ChildClassExample.java000066400000000000000000000002411475274123300320610ustar00rootroot00000000000000package test.thread.issue2361; import org.testng.annotations.Test; @Test(singleThreaded = true) public class ChildClassExample extends BaseTestClassExample {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue2361/FactorySample.java000066400000000000000000000003641475274123300313130ustar00rootroot00000000000000package test.thread.issue2361; import org.testng.annotations.Factory; public class FactorySample { @Factory public static Object[] newInstances() { return new Object[] {new ChildClassExample(), new AnotherChildClassExample()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/issue2361/IssueTest.java000066400000000000000000000016641475274123300304760ustar00rootroot00000000000000package test.thread.issue2361; import org.assertj.core.api.Assertions; import org.testng.TestNG; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class IssueTest extends SimpleBaseTest { @Test(dataProvider = "dp") public void ensureClassLevelSingleThreadedNatureGetsHonoured(Class cls) { XmlSuite suite = createXmlSuite("Sample_Suite"); suite.setParallel(ParallelMode.METHODS); XmlTest xmlTest = createXmlTest(suite, "Sample_Test", cls); xmlTest.setParallel(ParallelMode.METHODS); TestNG testng = create(suite); testng.run(); Assertions.assertThat(testng.getStatus()).isEqualTo(0); } @DataProvider(name = "dp") public Object[][] getTestData() { return new Object[][] {{ChildClassExample.class}, {FactorySample.class}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/000077500000000000000000000000001475274123300274225ustar00rootroot00000000000000BaseParallelizationTest.java000066400000000000000000001335411475274123300350020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_SUITE_FINISH; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_SUITE_START; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_FINISH; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_PASS; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_START; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_START; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodEventLogsForMethod; import com.google.common.collect.Multimap; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import org.testng.annotations.Test; import org.testng.internal.collections.Pair; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent; public class BaseParallelizationTest extends SimpleBaseTest { private static final Logger log = Logger.getLogger(BaseParallelizationTest.class); // Get a list of the names of declared methods with the @Test annotation from the specified class public static List getDeclaredTestMethods(Class clazz) { List methodNames = new ArrayList<>(); for (Method method : clazz.getMethods()) { List declaredAnnotations = Arrays.asList(method.getDeclaredAnnotations()); for (Annotation a : declaredAnnotations) { if (a.annotationType().isAssignableFrom(org.testng.annotations.Test.class)) { methodNames.add(method.getName()); } } } return methodNames; } // Send the name of the suite and the name of the test as parameters so that the methods can // associate their // execution event logs with them. Specified the delay in seconds to apply for the method // execution. This delay // helps in determining the parallelism or lack thereof for method executions. public static void addParams(XmlSuite suite, String suiteName, String testName, String sleepFor) { Map parameters = new HashMap<>(); parameters.put("suiteName", suiteName); parameters.put("testName", testName); parameters.put("sleepFor", sleepFor); for (XmlTest test : suite.getTests()) { if (test.getName().equals(testName)) { test.setParameters(parameters); } } } public static void addParams( XmlSuite suite, String suiteName, String testName, String sleepFor, String dataProviderParam) { Map parameters = new HashMap<>(); parameters.put("suiteName", suiteName); parameters.put("testName", testName); parameters.put("sleepFor", sleepFor); parameters.put("dataProviderParam", dataProviderParam); for (XmlTest test : suite.getTests()) { if (test.getName().equals(testName)) { test.setParameters(parameters); } } } // Verify that the list of event logs have the specified event type. Print the specified failure // message if the // assertion on the event type fails. public static void verifyEventTypeForEventsLogs( List eventLogs, TestNgRunEvent event, String failMessage) { for (EventLog eventLog : eventLogs) { assertTrue(eventLog.getEvent() == event, failMessage); } } // Verify that the list of event logs all have different thread IDS. Print the specified failure // message if the // assertion on the thread IDs fails. public static void verifyDifferentThreadIdsForEvents( List eventLogs, String failMessage) { List threadIds = new ArrayList<>(); for (EventLog eventLog : eventLogs) { assertFalse(threadIds.contains(eventLog.getThreadId()), failMessage); threadIds.add(eventLog.getThreadId()); } } // Verify that the event logs in the first list all have different thread IDs from the event logs // in the second // list. Print the specified failure message if the assertion on the thread IDs fails. public static void verifyDifferentThreadIdsForEvents( List eventLogsOne, List eventLogsTwo, String failMessage) { List threadIds = new ArrayList<>(); for (EventLog eventLog : eventLogsOne) { threadIds.add(eventLog.getThreadId()); } for (EventLog eventLog : eventLogsTwo) { assertFalse(threadIds.contains(eventLog.getThreadId()), failMessage); } } // Verify that the list of event logs all have the same thread ID. Print the specified failure // message if the // assertion on the event type fails. public static void verifySameThreadIdForAllEvents(List eventLogs, String failMessage) { long threadId = -1; for (EventLog eventLog : eventLogs) { if (threadId == -1) { threadId = eventLog.getThreadId(); } else { assertEquals(eventLog.getThreadId(), threadId, failMessage); } } } // Verify that the threads from the specified list of event logs are all greater than the // specified thread ID. Print // the specified failure message if the assertion on the thread IDs fails. public static void verifyEventThreadsSpawnedAfter( Long earlierThreadId, List eventsFromLaterThread, String failMessage) { for (EventLog eventLog : eventsFromLaterThread) { assertTrue(eventLog.getThreadId() > earlierThreadId, failMessage); } } // //Verify that the timestamps of the list of event logs are all within the specified range of // each other. Print // //the specified failure message if the assertion on the timing range fails. // public static void verifyTimingOfEvents(List eventLogs, long timingRange, String // failMessage) { // if(!eventLogs.isEmpty()) { // Pair timestamps = getEarliestAndLatestTimestamps(eventLogs); // verifyTimestampDifference(timestamps.second(), timestamps.first(), timingRange, // failMessage); // } // } // public static void verifyTimingOfEvents(EventLog eventLogOne, EventLog eventLogTwo, long // timingRange, String // failMessage) { // verifyTimestampDifference(eventLogOne.getTimeOfEvent(), eventLogTwo.getTimeOfEvent(), // timingRange, failMessage); // } // // //Verify that the timestamps of the first list of events are all within the specified range // from the timestamps // //of the second list of events. Print the specified failure message if the assertion on the // timing range fails. // public static void verifyTimingOfEvents(List firstEventLogs, List // secondEventLogs, // long lowerTimingRange, long upperTimingRange, String failMessage) { // // if(!firstEventLogs.isEmpty() && !secondEventLogs.isEmpty()) { // Pair timestampsListOne = getEarliestAndLatestTimestamps(firstEventLogs); // Pair timestampsListTwo = // getEarliestAndLatestTimestamps(secondEventLogs); // // verifyTimestampDifference(timestampsListTwo.first(), timestampsListOne.first(), // lowerTimingRange, // upperTimingRange, failMessage); // verifyTimestampDifference(timestampsListTwo.first(), timestampsListOne.second(), // lowerTimingRange, // upperTimingRange, failMessage); // verifyTimestampDifference(timestampsListTwo.second(), timestampsListOne.first(), // lowerTimingRange, // upperTimingRange, failMessage); // verifyTimestampDifference(timestampsListTwo.second(), timestampsListOne.second(), // lowerTimingRange, // upperTimingRange, failMessage); // } // } // //Verify that the difference between the two specified timestamps is within the specfied // upper and lower bound. The // //difference is calculated as an absolute value. // public static void verifyTimestampDifference(long timestampOne, long timestampTwo, long // lowerTimingRange, // long upperTimingRange, String failMessage) { // assertTrue(Math.abs(timestampOne - timestampTwo) <= upperTimingRange && // Math.abs(timestampOne - timestampTwo) >= lowerTimingRange, failMessage + ". // Difference: " + // Math.abs(timestampOne - timestampTwo)); // } // // public static void verifyTimestampDifference(long timestampOne, long timestampTwo, long // timingRange, String // failMessage) { // assertTrue(Math.abs(timestampOne - timestampTwo) <= timingRange, failMessage + ". // Difference: " + // Math.abs(timestampOne - timestampTwo)); // } // Verify that the specified event logs all have timestamps between the specified earlier and // later event logs. // Print the specified failure message if the assertion on the timestamps fails. public static void verifyEventsOccurBetween( EventLog earlierEventLog, List inBetweenEventLogs, EventLog laterEventLog, String failMessage) { for (EventLog eventLog : inBetweenEventLogs) { assertTrue( eventLog.getTimeOfEvent() >= earlierEventLog.getTimeOfEvent() && eventLog.getTimeOfEvent() <= laterEventLog.getTimeOfEvent(), failMessage); } } // Verify that the timestamps for the events if the specified list are all increasing. That each // the timestamps of // a given event logger is later than the event logger immediately preceding it. Print the // specified failure message if // the assertion on the timestamps fails public static void verifySequentialTimingOfEvents(List eventLogs, String failMessage) { for (int i = 0; i + 1 < eventLogs.size(); i++) { assertTrue( eventLogs.get(i).getTimeOfEvent() < eventLogs.get(i + 1).getTimeOfEvent(), failMessage); } } // Verify that the first list of event logs all have timestamps earlier than all the events in the // second list of // event logs. Print the specified failure message if the assertion on the timestamps fails. public static void verifySequentialTimingOfEvents( List firstEventLogs, List secondEventLogs, String failMessage) { if (!firstEventLogs.isEmpty() && !secondEventLogs.isEmpty()) { Pair timestampsListOne = getEarliestAndLatestTimestamps(firstEventLogs); Pair timestampsListTwo = getEarliestAndLatestTimestamps(secondEventLogs); assertTrue(timestampsListTwo.first() > timestampsListOne.second(), failMessage); } } // Verify that the test methods declared in the specified list of classes have the specified // number of class // instances associated with them for the specified suite and test. public static void verifyNumberOfInstancesOfTestClassesForMethods( String suiteName, String testName, List> classes, int numInstances) { for (Class clazz : classes) { verifyNumberOfInstancesOfTestClassForMethods(suiteName, testName, clazz, numInstances); } } // Verify that the test methods declared in the specified list of classes have the specified // number of class // instances associated with them for the specified suite and test. public static void verifyNumberOfInstancesOfTestClassesForMethods( String suiteName, String testName, List> classes, int... numInstances) { for (int i = 0; i < numInstances.length; i++) { verifyNumberOfInstancesOfTestClassForMethods( suiteName, testName, classes.get(i), numInstances[i]); } } // Verify that the test methods declared in the specified class have the specified number of class // instances // associated with them for the specified suite and test. public static void verifyNumberOfInstancesOfTestClassForMethods( String suiteName, String testName, Class clazz, int numInstances) { for (String methodName : getDeclaredTestMethods(clazz)) { verifyNumberOfInstancesOfTestClassForMethod( suiteName, testName, clazz, methodName, numInstances); } } // Verify that the specified test method has the specified number of class instances associated // with it for the // specified suite and test. public static void verifyNumberOfInstancesOfTestClassForMethod( String suiteName, String testName, Class clazz, String methodName, int numInstances) { Multimap eventLogMap = getTestMethodEventLogsForMethod(suiteName, testName, clazz.getCanonicalName(), methodName); assertEquals( eventLogMap.keySet().size(), numInstances, "There should be " + numInstances + " instances " + "associated with the class " + clazz.getCanonicalName() + " for method " + methodName + " in the " + "test " + testName + " in the suite " + suiteName + ": " + eventLogMap); } // Verify that all the test methods declared in the specified list of classes have the same // instances of the classes // associated with them for the specified suite and test. public static void verifySameInstancesOfTestClassesAssociatedWithMethods( String suiteName, String testName, List> classes) { for (Class clazz : classes) { verifySameInstancesOfTestClassAssociatedWithMethods(suiteName, testName, clazz); } } // Verify that all the test methods declared in the specified class have the same instances of the // class associated / // with them for the specified suite and test. public static void verifySameInstancesOfTestClassAssociatedWithMethods( String suiteName, String testName, Class clazz) { Set instanceKeys = null; for (String methodName : getDeclaredTestMethods(clazz)) { Multimap eventLogMap = getTestMethodEventLogsForMethod( suiteName, testName, clazz.getCanonicalName(), methodName); if (instanceKeys == null) { instanceKeys = eventLogMap.keySet(); } else { assertTrue( instanceKeys.containsAll(eventLogMap.keySet()) && eventLogMap.keySet().containsAll(instanceKeys), "The same instances of " + clazz.getCanonicalName() + " should be associated with its methods for the test " + testName + " in the suite " + suiteName); } } } // Verify that methods associated with the specified event logs execute simultaneously in parallel // fashion, in // accordance with the thread count. This verification is for blocks of parallel methods, none of // which use // data providers. This verification is for blocks of parallel methods that have the same sleep // delays for their // execution bodies and which do not have any BeforeMethod AfterMethod, BeforeGroup or AfterGroup // configuration methods. public static void verifySimultaneousTestMethods( List testMethodEventLogs, String testName, int threadCount) { if (log.isDebugEnabled()) { log.debug( "Verifying parallel execution of test methods for test named " + testName + " with " + "thread count " + threadCount); log.debug( testMethodEventLogs.size() + " test method event logs for " + testMethodEventLogs.size() / 3 + " test methods"); } // Keep track of the methods that have started, but not completed execution. Map methodsExecuting = new HashMap<>(); // Keep track of the methods whose start, execute and test method pass events have all been // found in the list // of logs Map methodsCompleted = new HashMap<>(); // Keep track of the thread IDs for all the methods that are executing and check that all a // method's events // run in the same thread. List executingMethodThreadIds = new ArrayList<>(); // Make a list of the all the thread IDs of the first batch of start method events and check // that no other // thread IDs are found in the rest of the event logs. List allThreadIds = new ArrayList<>(); // If number of test methods is more than the thread count, then the first block of methods will // be equal to // the thread count. If not, it will be equal to the total number of methods. int blockSize = testMethodEventLogs.size() / 3 >= threadCount ? threadCount : testMethodEventLogs.size() / 3; // Get the start events for the first batch of methods. List eventLogTestMethodListenerStartEvents = testMethodEventLogs.subList(0, blockSize); if (log.isDebugEnabled()) { log.debug( "First " + blockSize + " test method event logs should all be test method start events: " + getStringForEventLogList(eventLogTestMethodListenerStartEvents)); } // Verify that all the events in the sublist extracted for the start events of the block of // methods expected // to execute in parallel all have the test method start event type and that they all executed // in different // threads. verifySimultaneousTestMethodListenerStartEvents( eventLogTestMethodListenerStartEvents, testName, blockSize); // Keep track of the current methods that are executing and their thread IDs for (EventLog eventLog : eventLogTestMethodListenerStartEvents) { ClassInstanceMethodKey classAndMethodNameAndInstanceHash = new ClassInstanceMethodKey(eventLog); assertNull( methodsExecuting.get(classAndMethodNameAndInstanceHash), "There should only be one start " + "event logged for a method in the first block of test method events"); assertFalse( executingMethodThreadIds.contains(eventLog.getThreadId()), "The first block of test method " + "events should all have different thread IDs"); methodsExecuting.put(classAndMethodNameAndInstanceHash, eventLog); executingMethodThreadIds.add(eventLog.getThreadId()); allThreadIds.add(eventLog.getThreadId()); } for (int i = blockSize; i < testMethodEventLogs.size(); i++) { EventLog eventLog = testMethodEventLogs.get(i); log.debug("Processing test method event log at index " + i + ": " + eventLog); ClassInstanceMethodKey classAndMethodNameAndInstanceHash = new ClassInstanceMethodKey(eventLog); if (eventLog.getEvent() == LISTENER_TEST_METHOD_START) { assertTrue( methodsExecuting.get(classAndMethodNameAndInstanceHash) == null && methodsCompleted.get(classAndMethodNameAndInstanceHash) == null, "There should only be one " + "execution of any given method"); assertFalse( executingMethodThreadIds.contains(eventLog.getThreadId()), "Event logs for currently " + "executing test methods should have different thread IDs"); assertTrue( allThreadIds.contains(eventLog.getThreadId()), "All of the test method event logs should " + "have the same " + threadCount + " thread IDs: " + allThreadIds.toString()); assertTrue( methodsExecuting.size() < threadCount, "The current event log is a test method start " + "event. The list of currently executing methods should be less than the thread count. " + "Thread count: " + threadCount + ". Currently executing methods: " + getStringForEventLogList(methodsExecuting.values())); methodsExecuting.put(classAndMethodNameAndInstanceHash, eventLog); executingMethodThreadIds.add(eventLog.getThreadId()); } if (eventLog.getEvent() == TEST_METHOD_EXECUTION) { assertTrue( methodsExecuting.get(classAndMethodNameAndInstanceHash) != null, "Found a test method " + "execution event log that does not have a corresponding test method start event log"); assertTrue( methodsExecuting.get(classAndMethodNameAndInstanceHash).getThreadId() == eventLog.getThreadId(), "All the event logs for a given method should have the same thread ID"); } if (eventLog.getEvent() == LISTENER_TEST_METHOD_PASS) { assertTrue( methodsExecuting.get(classAndMethodNameAndInstanceHash) != null, "Found a test method " + "pass event log that does not have a corresponding test method start event log"); assertTrue( methodsExecuting.get(classAndMethodNameAndInstanceHash).getThreadId() == eventLog.getThreadId(), "All the event logs for a given method should have the same thread ID"); methodsExecuting.remove(classAndMethodNameAndInstanceHash); executingMethodThreadIds.remove(eventLog.getThreadId()); methodsCompleted.put(classAndMethodNameAndInstanceHash, eventLog); } } } // Verify that methods associated with the specified event logs execute simultaneously in parallel // fashion, in // accordance with the thread count. This verification is for blocks of parallel methods, some of // which use // non-parallel data providers without factories, so all the invocations of the methods run on the // same class // instances. This verification is for blocks of parallel methods that have the same sleep delays // for their // execution bodies and which do not have any BeforeMethod AfterMethod, BeforeGroup or AfterGroup // configuration methods. // // Some of the test methods use non-parallel data providers without factories. All the invocations // of those // test methods will occur serially within the same thread on the same class instances. There are // three test // method events expected per test method: a start event, an execution event, and a test method // pass event. public static void verifyParallelTestMethodsWithNonParallelDataProvider( List testMethodEventLogs, String testName, Map expectedInvocationCounts, int numUniqueMethods, int threadCount) { log.debug( "Verifying parallel execution of test methods using non-parallel data providers for " + "test named " + testName + " with thread count " + threadCount); log.debug( testMethodEventLogs.size() + " test method event logs for " + numUniqueMethods + " unique methods"); Map methodsExecuting = new HashMap<>(); Map methodsCompleted = new HashMap<>(); // Because this method verifies combination of parallel-by-methods mode and the use of // non-parallel data // providers without factories, it is necessary to track the number of times that test methods // are invoked in // order to check that this is consistent with the number of times they are expected to be // invoked based on // their use of non-parallel data providers. Map methodInvocationsCounts = new HashMap<>(); // In order to verify that all invocations of test methods which use non-parallel data providers // occur in the // same thread, it is necessary to keep track of the thread IDs of methods that are executing // within a // block of simultaneously executing methods. Map executingMethodThreadIds = new HashMap<>(); // Make a list of the all the thread IDs of the first batch of start method events and check // that no other // thread IDs are found in the rest of the event logs. List allThreadIds = new ArrayList<>(); // The logic for determining the block size of simultaneously executing parallel methods is // initially determined // by whether the total number of unique methods less than the thread count. If it is less than // the thread count, // then the block size is equal to the number of unique methods. Those methods will execute in // parallel // until all invocations of all the methods completes. Otherwise, there are more methods queued // up than the // thread count, so the block size is equal to the thread count. int blockSize = numUniqueMethods >= threadCount ? threadCount : numUniqueMethods; // Get the start events for the first batch of methods. List eventLogTestMethodListenerStartEvents = testMethodEventLogs.subList(0, blockSize); log.debug( "First " + blockSize + " test method event logs should all be test method start events: " + "\n" + getStringForEventLogList(eventLogTestMethodListenerStartEvents)); log.debug(getStringForEventLogList(eventLogTestMethodListenerStartEvents)); // Keep track of the current methods that are executing and their thread IDs for (EventLog eventLog : eventLogTestMethodListenerStartEvents) { String classAndMethodName = (String) eventLog.getData(CLASS_NAME) + "." + (String) eventLog.getData(METHOD_NAME); assertNull( methodsExecuting.get(classAndMethodName), "There should only be one start event logged for a " + "method in the first block of test method events"); assertNull( executingMethodThreadIds.get(classAndMethodName), "The first block of test method events " + "should all have different thread IDs"); methodsExecuting.put(classAndMethodName, eventLog); executingMethodThreadIds.put(classAndMethodName, eventLog.getThreadId()); allThreadIds.add(eventLog.getThreadId()); methodInvocationsCounts.put(classAndMethodName, 1); } // Verify that all the events in the sublist extracted for the test method execution events of // the block of // methods expected to execute in parallel all have the test method execution event type and // that they all // executed in different threads. verifySimultaneousTestMethodListenerStartEvents( eventLogTestMethodListenerStartEvents, testName, blockSize); for (int i = blockSize; i < testMethodEventLogs.size(); i++) { EventLog eventLog = testMethodEventLogs.get(i); log.debug("Processing test method event log at index " + i + ": " + eventLog); String classAndMethodName = (String) eventLog.getData(CLASS_NAME) + "." + (String) eventLog.getData(METHOD_NAME); if (i != blockSize) { // All methods that are in the list of currently executing methods should still have // invocations left. // Otherwise, they would have been removed from that list and added to the completed methods // list. allExecutingMethodsHaveMoreInvocations( methodsExecuting, methodInvocationsCounts, expectedInvocationCounts); } if (eventLog.getEvent() == LISTENER_TEST_METHOD_START) { assertTrue( executingMethodThreadIds.get(classAndMethodName) == null || executingMethodThreadIds.get(classAndMethodName) == eventLog.getThreadId(), "Event logs for all invocations of a method on a give class instance should have the same " + "thread ID "); for (String key : executingMethodThreadIds.keySet()) { if (!key.equals(classAndMethodName)) { assertFalse( executingMethodThreadIds.get(key) == eventLog.getThreadId(), "Events for " + "different methods should have different thread IDs"); } } assertTrue( allThreadIds.contains(eventLog.getThreadId()), "All of the test method event logs should " + "have the same " + threadCount + " thread IDs: " + allThreadIds.toString()); if (methodsExecuting.get(classAndMethodName) == null) { assertTrue( methodsExecuting.size() < threadCount, "The current event log is a test method start " + "event for a method that has not yet been invoked. The list of currently executing " + "methods should be less than the thread count. Thread count: " + threadCount + ". Currently executing methods: " + getStringForEventLogList(methodsExecuting.values())); methodsExecuting.put(classAndMethodName, eventLog); executingMethodThreadIds.put(classAndMethodName, eventLog.getThreadId()); methodInvocationsCounts.put(classAndMethodName, 1); } else { methodInvocationsCounts.put( classAndMethodName, methodInvocationsCounts.get(classAndMethodName) + 1); assertTrue( methodInvocationsCounts.get(classAndMethodName) <= expectedInvocationCounts.get(classAndMethodName), "Method '" + classAndMethodName + "' is expected to execute only " + expectedInvocationCounts.get(classAndMethodName) + " times, but event logs show " + "that it was execute at least " + methodInvocationsCounts.get(classAndMethodName) + " times"); } } if (eventLog.getEvent() == TEST_METHOD_EXECUTION) { assertTrue( methodsExecuting.get(classAndMethodName) != null, "Found a test method execution event " + "log that does not have a corresponding test method start event log"); assertTrue( methodsExecuting.get(classAndMethodName).getThreadId() == eventLog.getThreadId(), "All the event logs for a given method should have the same thread ID"); } if (eventLog.getEvent() == LISTENER_TEST_METHOD_PASS) { assertTrue( methodsExecuting.get(classAndMethodName) != null, "Found a test method pass event log " + "that does not have a corresponding test method start event log"); assertTrue( methodsExecuting.get(classAndMethodName).getThreadId() == eventLog.getThreadId(), "All the event logs for a given method should have the same thread ID"); if (methodInvocationsCounts .get(classAndMethodName) .equals(expectedInvocationCounts.get(classAndMethodName))) { methodsExecuting.remove(classAndMethodName); executingMethodThreadIds.remove(classAndMethodName); methodsCompleted.put(classAndMethodName, eventLog); } log.debug( classAndMethodName + " has executed " + methodInvocationsCounts.get(classAndMethodName) + " times. Expected to execute " + (expectedInvocationCounts.get(classAndMethodName) - methodInvocationsCounts.get(classAndMethodName)) + " more times"); } } } // Verify that the specified test method listener onTestStart event logs execute simultaneously in // parallel fashion // according to the expected maximum number of simultaneous executions. Verifies that each of them // has the same // event type and all have different thread IDs. public static void verifySimultaneousTestMethodListenerStartEvents( List listenerStartEventLogs, String testName, int blockSize) { verifyEventTypeForEventsLogs( listenerStartEventLogs, LISTENER_TEST_METHOD_START, "Expected " + blockSize + " test method start event logs to be in a block of methods executing in parallel. Found an event log " + "of a different type in the block being processed: " + listenerStartEventLogs); verifyDifferentThreadIdsForEvents( listenerStartEventLogs, "Expected " + blockSize + " test method start " + "event logs to be in a block of methods executing in parallel. Each one of these event logs should " + "be associated with a different thread ID, but found that at two event logs share the same thread " + "ID: " + listenerStartEventLogs); } // Verify that the test method level events for the test methods declared in the specified class // run in the same // thread for each instance of the test class for the specified suite and test public static void verifyEventsForTestMethodsRunInTheSameThread( Class testClass, String suiteName, String testName) { for (Method method : testClass.getMethods()) { boolean isTestMethod = false; Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation a : annotations) { if (Test.class.isAssignableFrom(a.getClass())) { isTestMethod = true; } } if (method.getDeclaringClass().equals(testClass) && isTestMethod) { Multimap testMethodEventLogs = getTestMethodEventLogsForMethod( suiteName, testName, testClass.getCanonicalName(), method.getName()); for (Object instanceKey : testMethodEventLogs.keySet()) { long threadId = -1; for (EventLog eventLog : testMethodEventLogs.get(instanceKey)) { if (threadId == -1) { threadId = eventLog.getThreadId(); } else { assertEquals( eventLog.getThreadId(), threadId, "All of the method level events for the test " + "method " + method.getName() + " in the test class " + testClass.getCanonicalName() + " for the test " + suiteName + " should be run in the same thread"); } } } } } } public static void verifySequentialSuites( List suiteLevelEventLogs, Map> suiteEventLogsMap) { verifySameThreadIdForAllEvents( suiteLevelEventLogs, "Because the suites execute sequentially, the event logs " + "suite level events should have the same thread ID: " + suiteLevelEventLogs); List suiteListenerStartEventLogs = new ArrayList<>(); for (int i = 0; i < suiteLevelEventLogs.size(); i = i + 2) { assertTrue( suiteLevelEventLogs.get(i).getEvent() == LISTENER_SUITE_START && suiteLevelEventLogs.get(i + 1).getEvent() == LISTENER_SUITE_FINISH, "Because the suites are " + "expected to execute sequentially, the suite level event logs should consist of a series of " + "pairs of a suite listener onStart event logger followed by a suite listener onFinish event logger: " + suiteLevelEventLogs); suiteListenerStartEventLogs.add((suiteLevelEventLogs.get(i))); } for (int i = 0; i < suiteListenerStartEventLogs.size() - 1; i++) { String firstSuite = (String) suiteListenerStartEventLogs.get(i).getData(SUITE_NAME); String secondSuite = (String) suiteListenerStartEventLogs.get(i + 1).getData(SUITE_NAME); List firstSuiteEventLogs = suiteEventLogsMap.get(firstSuite); List secondSuiteEventLogs = suiteEventLogsMap.get(secondSuite); verifySequentialTimingOfEvents( firstSuiteEventLogs, secondSuiteEventLogs, "The first suite listener " + "onStart event logger is for " + firstSuite + " and the second suite listener onStart event logger is " + "for " + secondSuite + ". Because the suites are supposed to execute sequentially, all of the " + "event logs for " + firstSuite + " should have timestamps earlier than all of the event logs for " + secondSuite + ". First suite event logs: " + firstSuiteEventLogs + ". Second suite event logs: " + secondSuiteEventLogs); } } public static void verifySequentialTests( List suiteAndTestLevelEventLogs, List testLevelEventLogs, EventLog suiteListenerOnStartEventLog, EventLog suiteListenerOnFinishEventLog) { verifySameThreadIdForAllEvents( suiteAndTestLevelEventLogs, "All suite level and test level event logs " + "should have the same thread ID because there is no parallelism specified at the suite or test " + "level: " + suiteAndTestLevelEventLogs); verifySequentialTimingOfEvents( suiteAndTestLevelEventLogs, "The timestamps of suite and test level events " + "logged first should be earlier than those which are logged afterwards because there is no " + "parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifyEventsOccurBetween( suiteListenerOnStartEventLog, testLevelEventLogs, suiteListenerOnFinishEventLog, "All of the test level event logs should have timestamps between the suite listener's onStart and " + "onFinish event logs. Suite listener onStart event logger: " + suiteListenerOnStartEventLog + ". Suite listener onFinish event logger: " + suiteListenerOnFinishEventLog + ". Test level " + "event logs: " + testLevelEventLogs); for (int i = 0; i < testLevelEventLogs.size(); i = i + 2) { assertTrue( testLevelEventLogs.get(i).getEvent() == LISTENER_TEST_START && testLevelEventLogs.get(i + 1).getEvent() == LISTENER_TEST_FINISH, "Because the tests are " + "expected to execute sequentially, the test level event logs should consist of a series of " + "pairs of a test listener onStart event logger followed by a test listener onFinish event logger: " + testLevelEventLogs); } } public static void verifyParallelSuitesWithUnequalExecutionTimes( List suiteLevelEventLogs, int threadPoolSize) { Map suitesExecuting = new HashMap<>(); Map suitesCompleted = new HashMap<>(); List executingSuiteThreadIds = new ArrayList<>(); if (suiteLevelEventLogs.size() > 2) { int offset = suiteLevelEventLogs.size() >= 2 * threadPoolSize ? threadPoolSize : suiteLevelEventLogs.size() / 2; List suiteListenerStartEventLogs = suiteLevelEventLogs.subList(0, offset); verifyFirstBlockOfSimultaneouslyExecutingSuites(suiteListenerStartEventLogs, threadPoolSize); for (EventLog eventLog : suiteListenerStartEventLogs) { suitesExecuting.put((String) eventLog.getData(SUITE_NAME), eventLog); executingSuiteThreadIds.add(eventLog.getThreadId()); } for (int i = offset; i < suiteLevelEventLogs.size(); i++) { EventLog eventLog = suiteLevelEventLogs.get(i); String suiteName = (String) eventLog.getData(SUITE_NAME); if (eventLog.getEvent() == LISTENER_SUITE_START) { if (suitesExecuting.keySet().size() == threadPoolSize) { fail( "The thread pool size is " + threadPoolSize + ", so there should be no more than " + threadPoolSize + " suites executing at the same time: " + suiteLevelEventLogs); } assertFalse( suitesExecuting.get(suiteName) != null || suitesCompleted.get(suiteName) != null, "There should only be one execution of any given suite"); assertFalse( executingSuiteThreadIds.contains(eventLog.getThreadId()), "Event logs for currently " + "executing suites should have different thread IDs"); suitesExecuting.put(suiteName, eventLog); executingSuiteThreadIds.add(eventLog.getThreadId()); if (suitesCompleted.size() > 0) { EventLog priorEventLog = suiteLevelEventLogs.get(i - 1); assertEquals( priorEventLog.getEvent(), LISTENER_SUITE_FINISH, "When suites are executing in " + "parallel and a new suite begins execution when the active thread count was last " + "known to be equal to the maximum thread pool size, the previously logged suite " + "level event should be a suite listener onFinish event."); } } if (suitesExecuting.keySet().size() < threadPoolSize && suiteLevelEventLogs.size() - i + 1 > threadPoolSize) { fail( "The thread pool size is " + threadPoolSize + ", so there should be at least " + threadPoolSize + " suites executing at the same time unless there are no suites left to " + "queue and the final block of suites is currently in execution: " + suiteLevelEventLogs); } if (eventLog.getEvent() == LISTENER_SUITE_FINISH) { assertTrue( suitesExecuting.get(suiteName) != null, "Found an event logger for a suite listener " + "onFinish event that does not have a corresponding event logger for a suite listener " + "onStart event"); assertTrue( suitesExecuting.get(suiteName).getThreadId() == eventLog.getThreadId(), "All the " + "suite level event logs for a given suite should have the same thread ID"); suitesExecuting.remove(suiteName); executingSuiteThreadIds.remove(eventLog.getThreadId()); suitesCompleted.put((String) eventLog.getData(SUITE_NAME), eventLog); } } } } public static void verifySimultaneousSuiteListenerStartEvents( List listenerStartEventLogs, int threadPoolSize) { verifyEventTypeForEventsLogs( listenerStartEventLogs, LISTENER_SUITE_START, "The suite thread pool size is " + threadPoolSize + ", so no more than " + threadPoolSize + " suites should start running at the " + "same time if there are more than " + threadPoolSize + " suites remaining to execute."); verifyDifferentThreadIdsForEvents( listenerStartEventLogs, "The suite thread pool size is " + threadPoolSize + ", so the thread IDs for all the suite listener's onStart method for the " + threadPoolSize + " currently executing suites should be different"); } private static void verifyFirstBlockOfSimultaneouslyExecutingSuites( List suiteListenerStartEventLogs, int threadPoolSize) { verifySimultaneousSuiteListenerStartEvents(suiteListenerStartEventLogs, threadPoolSize); verifyDifferentThreadIdsForEvents( suiteListenerStartEventLogs, "The thread count is " + threadPoolSize + " so the thread IDs for the suite listener onStart events for simultaneously executing suites " + "should be different. Event logs: " + suiteListenerStartEventLogs); } // Helper method that retrieves the earliest and latest timestamps for the specified list of event // logs private static Pair getEarliestAndLatestTimestamps(List eventLogs) { if (eventLogs.isEmpty()) { return null; } long earliestTimestamp = eventLogs.get(0).getTimeOfEvent(); long latestTimestamp = eventLogs.get(0).getTimeOfEvent(); for (int i = 1; i < eventLogs.size(); i++) { long timestamp = eventLogs.get(i).getTimeOfEvent(); if (timestamp < earliestTimestamp) { earliestTimestamp = timestamp; } if (timestamp > latestTimestamp) { latestTimestamp = timestamp; } } return new Pair<>(earliestTimestamp, latestTimestamp); } private static boolean allExecutingMethodsHaveMoreInvocations( Map methodsExecuting, Map methodInvocationsCounts, Map expectedInvocationCounts) { for (String methodAndClassName : methodsExecuting.keySet()) { if (Objects.equals( methodInvocationsCounts.get(methodAndClassName), expectedInvocationCounts.get(methodAndClassName))) { return false; } } return true; } private static String getStringForEventLogList(Collection list) { StringBuilder sb = new StringBuilder(); ArrayList eventLogs = new ArrayList<>(list); for (int i = 0; i < eventLogs.size(); i++) { sb.append(eventLogs.get(i)); if (i != eventLogs.size() - 1) { sb.append("\n"); } } return sb.toString(); } } ClassInstanceMethodKey.java000066400000000000000000000017761475274123300345650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.*; import java.util.Objects; public class ClassInstanceMethodKey { private final String className; private final String methodName; private final Object classInstance; public ClassInstanceMethodKey(TestNgRunStateTracker.EventLog eventLog) { className = (String) eventLog.getData(CLASS_NAME); methodName = (String) eventLog.getData(METHOD_NAME); classInstance = eventLog.getData(CLASS_INSTANCE); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassInstanceMethodKey that = (ClassInstanceMethodKey) o; return Objects.equals(className, that.className) && Objects.equals(methodName, that.methodName) && Objects.equals(classInstance, that.classInstance); } @Override public int hashCode() { return Objects.hash(className, methodName, classInstance); } } ParallelByMethodsTestCase1Scenario1.java000066400000000000000000000225351475274123300370520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteAndTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartThreadId; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.List; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; /** * This class covers PTP_TC_1, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites, no dependencies and * no factories or data providers. * *

Scenario Description: Single suite with a single test consisting of a single test class with * five methods * *

1) Thread count and parallel mode are specified at the suite level 2) The thread count is * equal to the number of test methods, ensuring that no method should have to wait for any other * method to complete execution 3) There are NO configuration methods 4) All test methods pass 5) NO * ordering is specified 6) group-by-instances is NOT set 7) There are no method exclusions */ public class ParallelByMethodsTestCase1Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase1Scenario1.class); private static final String SUITE = "SingleTestSuite"; private static final String TEST = "SingleTestClassTest"; private List suiteLevelEventLogs; private List testLevelEventLogs; private List suiteAndTestLevelEventLogs; private List testMethodLevelEventLogs; private EventLog suiteListenerOnStartEventLog; private EventLog suiteListenerOnFinishEventLog; private EventLog testListenerOnStartEventLog; private EventLog testListenerOnFinishEventLog; private Long testListenerOnStartThreadId; @BeforeClass public void setUp() { reset(); XmlSuite suite = createXmlSuite(SUITE); suite.setParallel(XmlSuite.ParallelMode.METHODS); suite.setThreadCount(5); createXmlTest(suite, TEST, TestClassAFiveMethodsWithNoDepsSample.class); addParams(suite, SUITE, TEST, "100"); TestNG tng = create(suite); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase1Scenario1. This test scenario consists of a " + "single suite with a single test which consists of one test class with five test methods. There " + "are no dependencies, data providers or factories."); log.debug( "Suite: " + SUITE + ", Test: " + TEST + ", Test class: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 5"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); suiteAndTestLevelEventLogs = getAllSuiteAndTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE); suiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE); testListenerOnStartEventLog = getTestListenerStartEventLog(SUITE, TEST); testListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE, TEST); testListenerOnStartThreadId = getTestListenerStartThreadId(SUITE, TEST); } // Verifies that the expected number of suite, test and test method level events were logged. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 15, "There should be 15 test method level event logged for " + SUITE + ": " + testMethodLevelEventLogs); } // Verify that the suite listener and test listener events have timestamps in the following order: // suite start, // test start, test finish, suite finish. Verify that all of these events run in the same thread // because the // parallelization mode is by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderInSameThread() { verifySameThreadIdForAllEvents( suiteAndTestLevelEventLogs, "The thread ID for all the suite and test level " + "event logs should be the same because there is no parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifySequentialTimingOfEvents( suiteAndTestLevelEventLogs, "The timestamps of suite and test level events " + "logged first should be earlier than those which are logged afterwards because there is no " + "parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifyEventsOccurBetween( suiteListenerOnStartEventLog, testLevelEventLogs, suiteListenerOnFinishEventLog, "All of the test level event logs should have timestamps between the suite listener's onStart and " + "onFinish event logs. Suite listener onStart event log: " + suiteListenerOnStartEventLog + ". Suite listener onFinish event log: " + suiteListenerOnFinishEventLog + ". Test level " + "event logs: " + testLevelEventLogs); } // Verify that there is only a single test class instance associated with each of the test methods // from the // sample test class // Verify that the same test class instance is associated with each of the test methods from the // sample test class @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethods() { verifyNumberOfInstancesOfTestClassForMethods( SUITE, TEST, TestClassAFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE, TEST, TestClassAFiveMethodsWithNoDepsSample.class); } // Verifies that all the test method level events execute between the test listener onStart and // onFinish methods @Test public void verifyTestMethodLevelEventsAllOccurBetweenTestListenerStartAndFinish() { verifyEventsOccurBetween( testListenerOnStartEventLog, testMethodLevelEventLogs, testListenerOnFinishEventLog, "All of the test method level event logs should have timestamps between the test listener's onStart " + "and onFinish event logs. Test Listener onStart event log: " + testListenerOnStartEventLog + ". Test Listener onFinish event log: " + testListenerOnFinishEventLog + ". Test method level " + "event logs: " + testMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( testListenerOnStartThreadId, testMethodLevelEventLogs, "All the thread IDs " + "for the test method level events should be greater than the thread ID for the suite and test level " + "events. The expectation is that since the suite and test level events are running sequentially, and " + "all the test methods are running in parallel, new threads will be spawned after the thread " + "executing the suite and test level events when new methods begin executing. Suite and test level " + "events thread ID: " + testListenerOnStartThreadId + ". Test method level event logs: " + testMethodLevelEventLogs); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods(testMethodLevelEventLogs, TEST, 5); } // Verifies that all the test method level events for any given test method run in the same // thread. @Test public void verifyThatAllEventsForATestMethodExecuteInSameThread() { verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE, TEST); } } ParallelByMethodsTestCase1Scenario2.java000066400000000000000000001027051475274123300370510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassGThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassHFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassIFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassJFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassKFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassLThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassMFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassNFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassOSixMethodsWithNoDepsSample; /** * This class covers PTP_TC_1, Scenario 2 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites, no dependencies and * no factories or data providers. * *

Scenario Description: Three suites with 1, 2 and 3 tests respectively. One test for a suite * shall consist of a single test class while the rest shall consist of more than one test class. * *

1) For one of the suites, the thread count and parallel mode are specified at the suite level * 2) For one of the suites, the thread count and parallel mode are specified at the test level 3) * For one of the suites, the parallel mode is specified at the suite level, and the thread counts * are specified at the test level (thread counts for each test differ) 4) The thread count is less * than the number of test methods for the tests in two of the suites, so some methods will have to * wait the active thread count to drop below the maximum thread count before they can begin * execution. 5) The thread count is more than the number of test methods for the tests in one of * the suites, ensuring that none of the methods in that suite should have to wait for any other * method to complete execution 6) There are NO configuration methods 7) All test methods pass 8) NO * ordering is specified 9) group-by-instances is NOT set 10) There are no method exclusions */ public class ParallelByMethodsTestCase1Scenario2 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase1Scenario2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_C = "TestSuiteC"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private static final String SUITE_C_TEST_A = "TestSuiteC-ThreeTestClassTest"; private static final String SUITE_C_TEST_B = "TestSuiteC-TwoTestClassTest"; private static final String SUITE_C_TEST_C = "TestSuiteC-FourTestClassTest"; private Map> suiteEventLogsMap = new HashMap<>(); private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteThreeSuiteAndTestLevelEventLogs; private List suiteThreeSuiteLevelEventLogs; private List suiteThreeTestLevelEventLogs; private List suiteThreeTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private List suiteThreeTestOneTestMethodLevelEventLogs; private List suiteThreeTestTwoTestMethodLevelEventLogs; private List suiteThreeTestThreeTestMethodLevelEventLogs; private EventLog suiteOneSuiteListenerOnStartEventLog; private EventLog suiteOneSuiteListenerOnFinishEventLog; private EventLog suiteTwoSuiteListenerOnStartEventLog; private EventLog suiteTwoSuiteListenerOnFinishEventLog; private EventLog suiteThreeSuiteListenerOnStartEventLog; private EventLog suiteThreeSuiteListenerOnFinishEventLog; private EventLog suiteOneTestOneListenerOnStartEventLog; private EventLog suiteOneTestOneListenerOnFinishEventLog; private EventLog suiteTwoTestOneListenerOnStartEventLog; private EventLog suiteTwoTestOneListenerOnFinishEventLog; private EventLog suiteTwoTestTwoListenerOnStartEventLog; private EventLog suiteTwoTestTwoListenerOnFinishEventLog; private EventLog suiteThreeTestOneListenerOnStartEventLog; private EventLog suiteThreeTestOneListenerOnFinishEventLog; private EventLog suiteThreeTestTwoListenerOnStartEventLog; private EventLog suiteThreeTestTwoListenerOnFinishEventLog; private EventLog suiteThreeTestThreeListenerOnStartEventLog; private EventLog suiteThreeTestThreeListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); XmlSuite suiteThree = createXmlSuite(SUITE_C); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(3); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(6); } else { test.setThreadCount(20); } } createXmlTest( suiteThree, SUITE_C_TEST_A, TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_B, TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_C, TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class); for (XmlTest test : suiteThree.getTests()) { test.setParallel(XmlSuite.ParallelMode.METHODS); switch (test.getName()) { case SUITE_C_TEST_A: test.setThreadCount(10); break; case SUITE_C_TEST_B: test.setThreadCount(5); break; default: test.setThreadCount(12); break; } } addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_A, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_C, "100"); TestNG tng = create(suiteOne, suiteTwo, suiteThree); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase1Scenario2. This test scenario consists of three " + "sequentially executed suites with 1, 2 and 3 tests respectively. One test for a suite consists of a " + "single test class while the rest shall consist of more than one test class. There are no " + "dependencies, data providers or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassCSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 6"); log.debug( "Suite " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithNoDepsSample.class + ", " + TestClassBFourMethodsWithNoDepsSample.class + ", " + TestClassFSixMethodsWithNoDepsSample.class + ". Thread count: 20"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_A + ", Test classes: " + TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassIFiveMethodsWithNoDepsSample.class + ". Thread count: 10"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_B + ", Test classes: " + TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassKFiveMethodsWithNoDepsSample.class + ". Thread count: 5"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_C + ", Test classes: " + TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 12."); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteThreeSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_C); suiteThreeSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_C); suiteThreeTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_C); suiteEventLogsMap.put(SUITE_A, getAllEventLogsForSuite(SUITE_A)); suiteEventLogsMap.put(SUITE_B, getAllEventLogsForSuite(SUITE_B)); suiteEventLogsMap.put(SUITE_C, getAllEventLogsForSuite(SUITE_C)); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_C); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_A, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A)); testEventLogsMap.put(SUITE_C_TEST_B, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_C, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteThreeSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_C); suiteThreeSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_C); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_C); suiteThreeTestThreeListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_C); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 6, "There should be 6 suite level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 12, "There should be 12 test level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 204, "There should 204 test method level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 33, "There should be 33 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 54, "There should be 54 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); assertEquals( suiteThreeSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_C + ": " + suiteThreeSuiteLevelEventLogs); assertEquals( suiteThreeTestLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_C + ": " + suiteThreeTestLevelEventLogs); assertEquals( suiteThreeTestMethodLevelEventLogs.size(), 117, "There should be 87 test method level events " + "logged for " + SUITE_C + ": " + suiteThreeTestMethodLevelEventLogs); } // Verify that all the events in the second suite and third suites run have timestamps later than // the suite // listener's onFinish event for the first suite run. // Verify that all the events in the third suite run have timestamps later than the suite // listener's onFinish // event for the second suite run. // Verify that all suite level events run in the same thread @Test public void verifySuitesRunSequentiallyInSameThread() { verifySequentialSuites(suiteLevelEventLogs, suiteEventLogsMap); } // For all suites, verify that the test level events run sequentially because the parallel mode is // by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); verifySequentialTests( suiteThreeSuiteAndTestLevelEventLogs, suiteThreeTestLevelEventLogs, suiteThreeSuiteListenerOnStartEventLog, suiteThreeSuiteListenerOnFinishEventLog); } // Verify that there is only a single test class instance associated with each of the test methods // from the sample // classes for every test in all the suites. // Verify that the same test class instance is associated with each of the test methods from the // sample test class @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestOneListenerOnStartEventLog, suiteThreeTestOneTestMethodLevelEventLogs, suiteThreeTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_A + ". Test listener onStart event log: " + suiteThreeTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestTwoListenerOnStartEventLog, suiteThreeTestTwoTestMethodLevelEventLogs, suiteThreeTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_B + ". Test listener onStart event log: " + suiteThreeTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestThreeListenerOnStartEventLog, suiteThreeTestThreeTestMethodLevelEventLogs, suiteThreeTestThreeListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_C + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_C + ". Test listener onStart event log: " + suiteThreeTestThreeListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestThreeListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestThreeTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassGThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassHFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassIFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassJFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassKFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassLThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassMFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassNFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassOSixMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); } // Verify that the methods are run in separate threads. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 6); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 20); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A), SUITE_C_TEST_A, 10); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B), SUITE_C_TEST_B, 5); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C), SUITE_C_TEST_C, 12); } } ParallelByMethodsTestCase2Scenario1.java000066400000000000000000000476571475274123300370670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithNoDepsSample; /** * This class covers PTP_TC_2, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with parallel test suites, no dependencies and no * factories or data providers. * *

Scenario Description: Two suites with 1 and 2 tests respectively. One test for a suite shall * consist of a single test class while the rest shall consist of more than one test class. * *

1) The suite thread pool is 2, so neither suite should have to wait for the other to complete * execution 2) For both suites, the thread count and parallel mode are specified at the suite level * 3) The thread count is less than the number of test methods in a test for one of the suites, so * some methods will have to wait the active thread count to drop below the maximum thread count * before they can begin execution. 4) The thread count is more than the number of test methods for * the rest of the tests, ensuring that none of their test methods should have to wait for any other * method to complete execution 5) There are NO configuration methods 6) All test methods pass 7) NO * ordering is specified 8) group-by-instances is NOT set 9) There are no method exclusions */ public class ParallelByMethodsTestCase2Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase2Scenario1.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private EventLog suiteOneSuiteListenerOnStartEventLog; private EventLog suiteOneSuiteListenerOnFinishEventLog; private EventLog suiteTwoSuiteListenerOnStartEventLog; private EventLog suiteTwoSuiteListenerOnFinishEventLog; private EventLog suiteOneTestOneListenerOnStartEventLog; private EventLog suiteOneTestOneListenerOnFinishEventLog; private EventLog suiteTwoTestOneListenerOnStartEventLog; private EventLog suiteTwoTestOneListenerOnFinishEventLog; private EventLog suiteTwoTestTwoListenerOnStartEventLog; private EventLog suiteTwoTestTwoListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(3); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); suiteTwo.setThreadCount(14); addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100"); TestNG tng = create(suiteOne, suiteTwo); tng.setSuiteThreadPoolSize(2); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase2Scenario1. This test scenario consists of two " + "suites with 1 and 2 tests respectively. The suites run in parallel and the thread pool size is 2. " + "One test for a suite shall consist of a single test class while the rest shall consist of more than " + "one test class. There are no dependencies, data providers or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassCSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 14"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithNoDepsSample.class + ", " + TestClassBFourMethodsWithNoDepsSample.class + ", " + TestClassFSixMethodsWithNoDepsSample.class + ". Thread count: 14"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 4, "There should be 4 suite level events logged for " + SUITE_A + ", " + SUITE_B + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_A + ", " + SUITE_B + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 87, "There should 87 test method level events logged for " + SUITE_A + ", " + SUITE_B + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 33, "There should be 33 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 54, "There should be 54 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); } @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); } // Verify that the methods are run in separate threads in true parallel fashion by checking that // the start and run // times of events that should be run simultaneously start basically at the same time using the // timestamps and the // known values of the wait time specified for the event. Verify that the thread IDs of parallel // events are // different. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 14); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 14); } } ParallelByMethodsTestCase2Scenario2.java000066400000000000000000001045301475274123300370500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassGThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassHFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassIFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassJFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassKFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassLThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassMFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassNFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassOSixMethodsWithNoDepsSample; /** * This class covers PTP_TC_2, Scenario 2 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with parallel test suites, no dependencies and no * factories or data providers. * *

Scenario Description: Three suites with 1, 2 and 3 tests respectively. One test for a suite * shall consist of a single test class while the rest shall consist of more than one test class. * *

1) The suite thread pool is 2, so one suite will have to wait for one of the others to * complete execution before it can begin execution 2) For one of the suites, the thread count and * parallel mode are specified at the suite level 3) For one of the suites, the thread count and * parallel mode are specified at the test level 4) For one of the suites, the parallel mode is * specified at the suite level, and the thread counts are specified at the test level (thread * counts for each test differ) 5) The thread count is less than the number of test methods for the * tests in two of the suites, so some methods will have to wait the active thread count to drop * below the maximum thread count before they can begin execution. 6) The thread count is more than * the number of test methods for the tests in one of the suites, ensuring that none of the methods * in that suite should have to wait for any other method to complete execution 7) There are NO * configuration methods 8) All test methods pass 9) NO ordering is specified 10) group-by-instances * is NOT set 11) There are no method exclusions */ public class ParallelByMethodsTestCase2Scenario2 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase2Scenario2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_C = "TestSuiteC"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private static final String SUITE_C_TEST_A = "TestSuiteC-ThreeTestClassTest"; private static final String SUITE_C_TEST_B = "TestSuiteC-TwoTestClassTest"; private static final String SUITE_C_TEST_C = "TestSuiteC-FourTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteThreeSuiteAndTestLevelEventLogs; private List suiteThreeSuiteLevelEventLogs; private List suiteThreeTestLevelEventLogs; private List suiteThreeTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private List suiteThreeTestOneTestMethodLevelEventLogs; private List suiteThreeTestTwoTestMethodLevelEventLogs; private List suiteThreeTestThreeTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); XmlSuite suiteThree = createXmlSuite(SUITE_C); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(3); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(6); } else { test.setThreadCount(20); } } createXmlTest( suiteThree, SUITE_C_TEST_A, TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_B, TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_C, TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class); for (XmlTest test : suiteThree.getTests()) { test.setParallel(XmlSuite.ParallelMode.METHODS); switch (test.getName()) { case SUITE_C_TEST_A: test.setThreadCount(10); break; case SUITE_C_TEST_B: test.setThreadCount(5); break; default: test.setThreadCount(12); break; } } addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_A, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_C, "100"); TestNG tng = create(suiteOne, suiteTwo, suiteThree); tng.setSuiteThreadPoolSize(2); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase2Scenario2. This test scenario consists of three " + "suites with 1, 2 and 3 tests respectively. The suites run in parallel and the thread pool size is 3 " + "One test for a suite shall consist of a single test class while the rest shall consist of more than " + "one test class. There are no dependencies, data providers or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassCSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 6"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithNoDepsSample.class + ", " + TestClassBFourMethodsWithNoDepsSample.class + ", " + TestClassFSixMethodsWithNoDepsSample.class + ". Thread count: 20"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_A + ", Test classes: " + TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassIFiveMethodsWithNoDepsSample.class + ". Thread count: 10"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_B + ", Test classes: " + TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassKFiveMethodsWithNoDepsSample.class + ". Thread count: 5"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_C + ", Test classes: " + TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 12."); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteThreeSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_C); suiteThreeSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_C); suiteThreeTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_C); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_C); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_A, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A)); testEventLogsMap.put(SUITE_C_TEST_B, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_C, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteThreeSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_C); suiteThreeSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_C); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_C); suiteThreeTestThreeListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_C); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 6, "There should be 6 suite level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 12, "There should be 12 test level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 204, "There should 204 test method level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 33, "There should be 33 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 54, "There should be 54 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); assertEquals( suiteThreeSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_C + ": " + suiteThreeSuiteLevelEventLogs); assertEquals( suiteThreeTestLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_C + ": " + suiteThreeTestLevelEventLogs); assertEquals( suiteThreeTestMethodLevelEventLogs.size(), 117, "There should be 87 test method level events " + "logged for " + SUITE_C + ": " + suiteThreeTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); verifySequentialTests( suiteThreeSuiteAndTestLevelEventLogs, suiteThreeTestLevelEventLogs, suiteThreeSuiteListenerOnStartEventLog, suiteThreeSuiteListenerOnFinishEventLog); } // Verify that there is only a single test class instance associated with each of the test methods // from the sample // classes for every test in all the suites. // Verify that the same test class instance is associated with each of the test methods from the // sample test class @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestOneListenerOnStartEventLog, suiteThreeTestOneTestMethodLevelEventLogs, suiteThreeTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_A + ". Test listener onStart event log: " + suiteThreeTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestTwoListenerOnStartEventLog, suiteThreeTestTwoTestMethodLevelEventLogs, suiteThreeTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_B + ". Test listener onStart event log: " + suiteThreeTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestThreeListenerOnStartEventLog, suiteThreeTestThreeTestMethodLevelEventLogs, suiteThreeTestThreeListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_C + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_C + ". Test listener onStart event log: " + suiteThreeTestThreeListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestThreeListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestThreeTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassGThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassHFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassIFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassJFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassKFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassLThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassMFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassNFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassOSixMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); } // Verify that the methods are run in separate threads in true parallel fashion by checking that // the start and run // times of events that should be run simultaneously start basically at the same time using the // timestamps and the // known values of the wait time specified for the event. Verify that the thread IDs of parallel // events are // different. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 6); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 20); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A), SUITE_C_TEST_A, 10); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B), SUITE_C_TEST_B, 5); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C), SUITE_C_TEST_C, 12); } } ParallelByMethodsTestCase3Scenario1.java000066400000000000000000000260141475274123300370500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteAndTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartThreadId; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.sample.TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample; /** * This class covers PTP_TC_3, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites using a non-parallel * data provider but no dependencies and no factories. * *

Scenario Description: Single suite with a single test consisting of a single test class with * five methods with a data provider specifying 3 sets of data * *

1) Thread count and parallel mode are specified at the suite level 2) The thread count is * equal to the number of test methods times 3, the number of times each method will be invoked with * a data set from the data provider. Expectation is that only 5 threads will be spawned, one for * each of the methods and that in this thread, the method will be invoked 3 times, once for each * set of data from the data provider. 3) There are NO configuration methods 4) All test methods * pass 5) NO ordering is specified 6) group-by-instances is NOT set 7) There are no method * exclusions */ public class ParallelByMethodsTestCase3Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase3Scenario1.class); private static final String SUITE = "SingleTestSuite"; private static final String TEST = "SingleTestClassTest"; private List suiteLevelEventLogs; private List testLevelEventLogs; private List suiteAndTestLevelEventLogs; private List testMethodLevelEventLogs; private EventLog suiteListenerOnStartEventLog; private EventLog suiteListenerOnFinishEventLog; private EventLog testListenerOnStartEventLog; private EventLog testListenerOnFinishEventLog; private Long testListenerOnStartThreadId; private Map expectedInvocationCounts = new HashMap<>(); @BeforeClass public void setUp() { reset(); XmlSuite suite = createXmlSuite(SUITE); suite.setParallel(XmlSuite.ParallelMode.METHODS); suite.setThreadCount(15); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); createXmlTest( suite, TEST, TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class); addParams(suite, SUITE, TEST, "100", "paramOne,paramTwo,paramThree"); TestNG tng = create(suite); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase3Scenario1. This test scenario consists of a " + "single suite with a single test consisting of a single test class with five methods with a data " + "provider specifying 3 sets of data. There are no dependencies or factories."); log.debug( "Suite: " + SUITE + ", Test: " + TEST + ", Test class: " + TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class .getCanonicalName() + ". Thread count: 15"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); suiteAndTestLevelEventLogs = getAllSuiteAndTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE); suiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE); testListenerOnStartEventLog = getTestListenerStartEventLog(SUITE, TEST); testListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE, TEST); testListenerOnStartThreadId = getTestListenerStartThreadId(SUITE, TEST); } // Verifies that the expected number of suite, test and test method level events were logged. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 45, "There should be 45 test method level events logged for " + SUITE + ": " + testMethodLevelEventLogs); } // Verify that the suite listener and test listener events have timestamps in the following order: // suite start, // test start, test finish, suite finish. Verify that all of these events run in the same thread // because the // parallelization mode is by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderInSameThread() { verifySameThreadIdForAllEvents( suiteAndTestLevelEventLogs, "The thread ID for all the suite and test level " + "event logs should be the same because there is no parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifySequentialTimingOfEvents( suiteAndTestLevelEventLogs, "The timestamps of suite and test level events " + "logged first should be earlier than those which are logged afterwards because there is no " + "parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifyEventsOccurBetween( suiteListenerOnStartEventLog, testLevelEventLogs, suiteListenerOnFinishEventLog, "All of the test level event logs should have timestamps between the suite listener's onStart and " + "onFinish event logs. Suite listener onStart event log: " + suiteListenerOnStartEventLog + ". Suite listener onFinish event log: " + suiteListenerOnFinishEventLog + ". Test level " + "event logs: " + testLevelEventLogs); } // Verify that there is only a single test class instance associated with each of the test methods // from the // sample test class // Verify that the same test class instance is associated with each of the test methods from the // sample test class @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethods() { verifyNumberOfInstancesOfTestClassForMethods( SUITE, TEST, TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE, TEST, TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class); } // Verifies that all the test method level events execute between the test listener onStart and // onFinish methods @Test public void verifyTestMethodLevelEventsAllOccurBetweenTestListenerStartAndFinish() { verifyEventsOccurBetween( testListenerOnStartEventLog, testMethodLevelEventLogs, testListenerOnFinishEventLog, "All of the test method level event logs should have timestamps between the test listener's onStart " + "and onFinish event logs. Test Listener onStart event log: " + testListenerOnStartEventLog + ". Test Listener onFinish event log: " + testListenerOnFinishEventLog + ". Test method level " + "event logs: " + testMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( testListenerOnStartThreadId, testMethodLevelEventLogs, "All the thread IDs " + "for the test method level events should be greater than the thread ID for the suite and test level " + "events. The expectation is that since the suite and test level events are running sequentially, and " + "all the test methods are running in parallel, new threads will be spawned after the thread " + "executing the suite and test level events when new methods begin executing. Suite and test level " + "events thread ID: " + testListenerOnStartThreadId + ". Test method level event logs: " + testMethodLevelEventLogs); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE, TEST), TEST, expectedInvocationCounts, 5, 5); } // Verifies that all the test method level events for any given test method run in the same // thread. @Test public void verifyThatAllEventsForATestMethodExecuteInSameThread() { verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, SUITE, TEST); } } ParallelByMethodsTestCase3Scenario2.java000066400000000000000000000663231475274123300370600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.thread.parallelization.sample.TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; /** * This class covers PTP_TC_3, Scenario 2 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites using a non-parallel * data provider but no dependencies and no factories. * *

Scenario Description: Two suites with 1 and 2 tests respectively. One test for a suite shall * consist of a single test class while the rest shall consist of more than one test class. Each * test class has some methods with use a data provider and some which do not. Two data providers * are used: one which provides two sets of data, one which provide three sets of data. * *

1) For both suites, the thread count and parallel mode are specified at the suite level 2) The * thread count is less than the number of test methods for all tests in both suites, so methods * will have to wait the active thread count to drop below the maximum thread count before they can * begin execution. The expectation is that a thread for a method does not terminate until the * method has been invoked for all sets of data if it uses a data provider. 3) There are NO * configuration methods 4) All test methods pass 5) NO ordering is specified 6) group-by-instances * is NOT set 7) There are no method exclusions */ public class ParallelByMethodsTestCase3Scenario2 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase3Scenario2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private Map> suiteEventLogsMap = new HashMap<>(); private Map expectedInvocationCounts = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_A, TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(3); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); suiteTwo.setThreadCount(4); addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100", "paramOne,paramTwo,paramThree"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100", "paramOne,paramTwo"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100", "paramOne,paramTwo"); TestNG tng = create(suiteOne, suiteTwo); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase3Scenario2. This test scenario consists of two " + "suites with 1 and 2 tests respectively. One test for a suite shall consist of a single test class " + "while the rest shall consist of more than one test class. Each test class has some methods with use " + "a data provider and some which do not. Two data providers are used: one which provides two sets of " + "data, one which provide three sets of data. There are no dependencies or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ". Thread count: 3"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ". Thread count: 4"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ", " + TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ", " + TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ". Thread count: 4"); tng.run(); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 3); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 2); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 2); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 2); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 2); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 2); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 2); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteEventLogsMap.put(SUITE_A, getAllEventLogsForSuite(SUITE_A)); suiteEventLogsMap.put(SUITE_B, getAllEventLogsForSuite(SUITE_B)); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 4, "There should be 4 suite level events logged for " + SUITE_A + ", " + SUITE_B + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_A + ", " + SUITE_B + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 150, "There should 150 test method level events logged for " + SUITE_A + ", " + SUITE_B + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 69, "There should be 69 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 81, "There should be 54 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); } // Verify that all the events in the second suite and third suites run have timestamps later than // the suite // listener's onFinish event for the first suite run. // Verify that all the events in the third suite run have timestamps later than the suite // listener's onFinish // event for the second suite run. // Verify that all suite level events run in the same thread @Test public void verifySuitesRunSequentiallyInSameThread() { verifySequentialSuites(suiteLevelEventLogs, suiteEventLogsMap); } // For all suites, verify that the test level events run sequentially because the parallel mode is // by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); } // Verify that there is only a single test class instance associated with each of the test methods // from the sample // classes for every test in all the suites. // Verify that the same test class instance is associated with each of the test methods from the // sample test class @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, expectedInvocationCounts, 11, 3); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, expectedInvocationCounts, 5, 4); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, expectedInvocationCounts, 13, 4); } } ParallelByMethodsTestCase4Scenario1.java000066400000000000000000001434721475274123300370610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.sample.TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; import test.thread.parallelization.sample.TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample; /** * This class covers PTP_TC_4, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with parallel test suites using a non-parallel * data provider but no dependencies and no factories. * *

Scenario Description: Three suites with 1, 2 and 3 tests respectively. One test for a suite * shall consist of a single test class while the rest shall consist of more than one test class. * Some test classes have a mixture of some methods that use a data provider and some which do not. * The data providers provide data sets of varying sizes. * *

1) The suite thread pool is 2, so one suite will have to wait for one of the others to * complete execution before it can begin execution 2) For one of the suites, the thread count and * parallel mode are specified at the suite level 3) For one of the suites, the thread count and * parallel mode are specified at the test level 4) For one of the suites, the parallel mode is * specified at the suite level, and the thread counts are specified at the test level (thread * counts for each test differ) 5) The thread count is less than the number of test methods for the * tests in two of the suites, so some methods will have to wait the active thread count to drop * below the maximum thread count before they can begin execution. The expectation is that a thread * for a method does not terminate until the method has been invoked for all sets of data if it uses * a data provider. 6) The thread count is more than the number of test methods for the tests in one * of the suites, ensuring that none of the methods in that suite should have to wait for any other * method to complete execution. The expectation is that a thread for a method does not terminate * until the method has been invoked for all sets of data if it uses a data provider. 7) There are * NO configuration methods 8) All test methods pass 9) NO ordering is specified 10) * group-by-instances is NOT set 11) There are no method exclusions */ public class ParallelByMethodsTestCase4Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase4Scenario1.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_C = "TestSuiteC"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private static final String SUITE_C_TEST_A = "TestSuiteC-ThreeTestClassTest"; private static final String SUITE_C_TEST_B = "TestSuiteC-TwoTestClassTest"; private static final String SUITE_C_TEST_C = "TestSuiteC-FourTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map> suiteEventLogsMap = new HashMap<>(); private Map expectedInvocationCounts = new HashMap<>(); private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteThreeSuiteAndTestLevelEventLogs; private List suiteThreeSuiteLevelEventLogs; private List suiteThreeTestLevelEventLogs; private List suiteThreeTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private List suiteThreeTestOneTestMethodLevelEventLogs; private List suiteThreeTestTwoTestMethodLevelEventLogs; private List suiteThreeTestThreeTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); XmlSuite suiteThree = createXmlSuite(SUITE_C); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(3); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_A, TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(6); } else { test.setThreadCount(20); } } createXmlTest( suiteThree, SUITE_C_TEST_A, TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_B, TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_C, TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class); for (XmlTest test : suiteThree.getTests()) { test.setParallel(XmlSuite.ParallelMode.METHODS); switch (test.getName()) { case SUITE_C_TEST_A: test.setThreadCount(10); break; case SUITE_C_TEST_B: test.setThreadCount(5); break; default: test.setThreadCount(12); break; } } addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100", "paramOne,paramTwo,paramThree"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100", "paramOne,paramTwo"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100", "paramOne,paramTwo"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_A, "100", "paramOne,paramTwo,paramThree"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_B, "100", "paramOne,paramTwo"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_C, "100", "paramOne,paramTwo,paramThree"); TestNG tng = create(suiteOne, suiteTwo, suiteThree); tng.setSuiteThreadPoolSize(2); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase4Scenario1. This test scenario consists of three " + "suites with 1, 2 and 3 tests respectively. The suites run in parallel and the thread pool size is " + "2. One test for a suite shall consist of a single test class while the rest shall consist of more " + "han one test class. Some test classes have a mixture of some methods that use a data provider and " + "some which do not. The data providers provide data sets of varying sizes. There are no " + "dependencies or factories."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ". Thread count: 3"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ". Thread count: 6"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ", " + TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ", " + TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ". Thread count: 20"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_A + ", Test classes: " + TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class + ". Thread count: 10"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_B + ", Test classes: " + TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class + ". Thread count: 5"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_C + ", Test classes: " + TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class .getCanonicalName() + ", " + TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class .getCanonicalName() + ". Thread count: 12."); tng.run(); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 3); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 2); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 2); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 2); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 2); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 2); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 2); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); expectedInvocationCounts.put( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 2); expectedInvocationCounts.put( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 2); expectedInvocationCounts.put( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 2); expectedInvocationCounts.put( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 2); expectedInvocationCounts.put( TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 2); expectedInvocationCounts.put( TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 2); expectedInvocationCounts.put( TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 2); expectedInvocationCounts.put( TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); expectedInvocationCounts.put( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 3); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteThreeSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_C); suiteThreeSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_C); suiteThreeTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_C); suiteEventLogsMap.put(SUITE_A, getAllEventLogsForSuite(SUITE_A)); suiteEventLogsMap.put(SUITE_B, getAllEventLogsForSuite(SUITE_B)); suiteEventLogsMap.put(SUITE_C, getAllEventLogsForSuite(SUITE_C)); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_C); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_A, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A)); testEventLogsMap.put(SUITE_C_TEST_B, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_C, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteThreeSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_C); suiteThreeSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_C); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_C); suiteThreeTestThreeListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_C); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 6, "There should be 6 suite level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 12, "There should be 12 test level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 420, "There should 420 test method level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 69, "There should be 69 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 81, "There should be 81 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); assertEquals( suiteThreeSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_C + ": " + suiteThreeSuiteLevelEventLogs); assertEquals( suiteThreeTestLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_C + ": " + suiteThreeTestLevelEventLogs); assertEquals( suiteThreeTestMethodLevelEventLogs.size(), 270, "There should be 270 test method level events " + "logged for " + SUITE_C + ": " + suiteThreeTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); verifySequentialTests( suiteThreeSuiteAndTestLevelEventLogs, suiteThreeTestLevelEventLogs, suiteThreeSuiteListenerOnStartEventLog, suiteThreeSuiteListenerOnFinishEventLog); } // Verify that there is only a single test class instance associated with each of the test methods // from the sample // classes for every test in all the suites. // Verify that the same test class instance is associated with each of the test methods from the // sample test class @Test public void verifyOnlyOneInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestOneListenerOnStartEventLog, suiteThreeTestOneTestMethodLevelEventLogs, suiteThreeTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_A + ". Test listener onStart event log: " + suiteThreeTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestTwoListenerOnStartEventLog, suiteThreeTestTwoTestMethodLevelEventLogs, suiteThreeTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_B + ". Test listener onStart event log: " + suiteThreeTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestThreeListenerOnStartEventLog, suiteThreeTestThreeTestMethodLevelEventLogs, suiteThreeTestThreeListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_C + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_C + ". Test listener onStart event log: " + suiteThreeTestThreeListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestThreeListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestThreeTestMethodLevelEventLogs); } @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater " + "than the thread ID for the suite and test level events. The expectation is that since the " + "suite and test level events are running sequentially, and all the test methods are running " + "in parallel, new threads will be spawned after the thread executing the suite and test " + "level events when new methods begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, expectedInvocationCounts, 11, 3); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, expectedInvocationCounts, 5, 6); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, expectedInvocationCounts, 13, 20); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A), SUITE_C_TEST_A, expectedInvocationCounts, 12, 10); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B), SUITE_C_TEST_B, expectedInvocationCounts, 9, 5); verifyParallelTestMethodsWithNonParallelDataProvider( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C), SUITE_C_TEST_C, expectedInvocationCounts, 18, 12); } } ParallelByMethodsTestCase5Scenario1.java000066400000000000000000000235111475274123300370510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteAndTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartThreadId; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.List; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.sample.FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; /** * This class covers PTP_TC_5, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites using a factory but no * dependencies and no data providers. * *

Scenario Description: Single suite with a single test consisting of a factory that provides * two instances of a single test class with five methods * *

1) Thread count and parallel mode are specified at the suite level 2) The thread count is * equal to the number of test methods times 2, the number of times each method will be invoked * because there are two instances of the test class. Expectation is that 10 threads will be spawned * because each method will run once for each of the two instances and that each instance of a test * method will run in separate threads. 3) There are NO configuration methods 4) All test methods * pass 5) ordering is specified 6) group-by-instances is NOT set 7) There are no method exclusions */ public class ParallelByMethodsTestCase5Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase5Scenario1.class); private static final String SUITE = "SingleTestSuite"; private static final String TEST = "SingleTestClassTest"; private List suiteLevelEventLogs; private List testLevelEventLogs; private List suiteAndTestLevelEventLogs; private List testMethodLevelEventLogs; private EventLog suiteListenerOnStartEventLog; private EventLog suiteListenerOnFinishEventLog; private EventLog testListenerOnStartEventLog; private EventLog testListenerOnFinishEventLog; private Long testListenerOnStartThreadId; @BeforeClass public void setUp() { reset(); XmlSuite suite = createXmlSuite(SUITE); suite.setParallel(XmlSuite.ParallelMode.METHODS); suite.setThreadCount(15); createXmlTest(suite, TEST, FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample.class); addParams(suite, SUITE, TEST, "100"); TestNG tng = create(suite); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase5Scenario1. This test scenario consists of a " + "single suite with a single test consisting of a factory that provides two instances of a single" + "test class with five methods. There are no dependencies or data providers."); log.debug( "Suite: " + SUITE + ", Test: " + TEST + ", Test class: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 15"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); suiteAndTestLevelEventLogs = getAllSuiteAndTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE); suiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE); testListenerOnStartEventLog = getTestListenerStartEventLog(SUITE, TEST); testListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE, TEST); testListenerOnStartThreadId = getTestListenerStartThreadId(SUITE, TEST); } // Verifies that the expected number of suite, test and test method level events were logged. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 30, "There should be 15 test method level event logged for " + SUITE + ": " + testMethodLevelEventLogs); } // Verify that the suite listener and test listener events have timestamps in the following order: // suite start, // test start, test finish, suite finish. Verify that all of these events run in the same thread // because the // parallelization mode is by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderInSameThread() { verifySameThreadIdForAllEvents( suiteAndTestLevelEventLogs, "The thread ID for all the suite and test level " + "event logs should be the same because there is no parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifySequentialTimingOfEvents( suiteAndTestLevelEventLogs, "The timestamps of suite and test level events " + "logged first should be earlier than those which are logged afterwards because there is no " + "parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifyEventsOccurBetween( suiteListenerOnStartEventLog, testLevelEventLogs, suiteListenerOnFinishEventLog, "All of the test level event logs should have timestamps between the suite listener's onStart and " + "onFinish event logs. Suite listener onStart event log: " + suiteListenerOnStartEventLog + ". Suite listener onFinish event log: " + suiteListenerOnFinishEventLog + ". Test level " + "event logs: " + testLevelEventLogs); } // Verify that there are two test class instances associated with each of the test methods from // the sample test class // Verify that the same test class instances are associated with each of the test methods from the // sample test class @Test public void verifyTwoInstancesOfTestClassForAllTestMethods() { verifyNumberOfInstancesOfTestClassForMethods( SUITE, TEST, TestClassAFiveMethodsWithNoDepsSample.class, 2); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE, TEST, TestClassAFiveMethodsWithNoDepsSample.class); } // Verifies that all the test method level events execute between the test listener onStart and // onFinish methods @Test public void verifyTestMethodLevelEventsAllOccurBetweenTestListenerStartAndFinish() { verifyEventsOccurBetween( testListenerOnStartEventLog, testMethodLevelEventLogs, testListenerOnFinishEventLog, "All of the test method level event logs should have timestamps between the test listener's onStart " + "and onFinish event logs. Test Listener onStart event log: " + testListenerOnStartEventLog + ". Test Listener onFinish event log: " + testListenerOnFinishEventLog + ". Test method level " + "event logs: " + testMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( testListenerOnStartThreadId, testMethodLevelEventLogs, "All the thread IDs " + "for the test method level events should be greater than the thread ID for the suite and test level " + "events. The expectation is that since the suite and test level events are running sequentially, and " + "all the test methods are running in parallel, new threads will be spawned after the thread " + "executing the suite and test level events when new methods begin executing. Suite and test level " + "events thread ID: " + testListenerOnStartThreadId + ". Test method level event logs: " + testMethodLevelEventLogs); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods(testMethodLevelEventLogs, TEST, 10); } // Verifies that all the test method level events for any given test method occur twice and that // there are two // thread IDs because there are two instances of the test class that run. @Test public void verifyThatAllEventsForATestMethodInClassInstanceExecuteInSameThread() { verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE, TEST); } } ParallelByMethodsTestCase5Scenario2.java000066400000000000000000000532271475274123300370610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.sample.FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassBFourMethodsWithNoDepsFiveInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassCSixMethodsWithNoDepsThreeInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassDThreeMethodsWithNoDepsFourInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassFSixMethodsWithNoDepsSixInstancesSample; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithNoDepsSample; /** * This class covers PTP_TC_5, Scenario 2 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites using a factory but no * dependencies and no data providers. * *

Scenario Description: Two suites with 1 and 2 tests respectively. One suite with two tests has * a test consisting of a single test class without a factory while the other consists of factories * which provide multiple instances of multiple test classes. One suite shall consist of a single * test with multiple test classes which uses factories. * *

1) For both suites, the thread count and parallel mode are specified at the suite level 2) The * thread count is less than the number of test methods for all tests in both suites, so methods * will have to wait for the active thread count to drop below the maximum thread count before they * can begin execution. The expectation is that threads will be spawned for each test method that * executes just as they would if there were no factories and test suites simply used the default * mechanism for instantiating single instances of the test classes. 3) There are NO configuration * methods 4) All test methods pass 5) NO ordering is specified 6) group-by-instances is NOT set 7) * There are no method exclusions */ public class ParallelByMethodsTestCase5Scenario2 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase5Scenario2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private Map> suiteEventLogsMap = new HashMap<>(); private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(10); createXmlTest( suiteOne, SUITE_A_TEST_A, FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample.class, FactoryForTestClassCSixMethodsWithNoDepsThreeInstancesSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, FactoryForTestClassDThreeMethodsWithNoDepsFourInstancesSample.class, FactoryForTestClassBFourMethodsWithNoDepsFiveInstancesSample.class, FactoryForTestClassFSixMethodsWithNoDepsSixInstancesSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(3); } else { test.setThreadCount(20); } } addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100"); TestNG tng = create(suiteOne, suiteTwo); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase5Scenario2. This test scenario consists of two " + "suites with 1 and 2 tests respectively. One suite with two tests has a test consisting of a single " + "test class without a factory while the other consists of factories which provide multiple instances " + "of multiple test classes. One suite shall consist of a single test with multiple test classes which " + "uses factories. There are no dependencies or data providers."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassCSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 10"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithNoDepsSample.class + ", " + TestClassBFourMethodsWithNoDepsSample.class + ", " + TestClassFSixMethodsWithNoDepsSample.class + ". Thread count: 20"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteEventLogsMap.put(SUITE_A, getAllEventLogsForSuite(SUITE_A)); suiteEventLogsMap.put(SUITE_B, getAllEventLogsForSuite(SUITE_B)); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 4, "There should be 4 suite level events logged for " + SUITE_A + " and " + SUITE_B + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_A + " and " + SUITE_B + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 303, "There should 303 test method level events logged for " + SUITE_A + " and " + SUITE_B + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 84, "There should be 84 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 219, "There should be 219 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); } // Verify that all the events in the second suite run have timestamps later than the suite // listener's onFinish event // for the first suite run. // Verify that all suite level events run in the same thread @Test public void verifySuitesRunSequentiallyInSameThread() { verifySequentialSuites(suiteLevelEventLogs, suiteEventLogsMap); } // For all suites, verify that the test level events run sequentially because the parallel mode is // by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); } // Verify the expected number of test class instances for the test method events. // Verify that the same test class instances are associated with each of the test methods from the // sample test class @Test public void verifyNumberOfInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class), 2, 3); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class), 4, 5, 6); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); } // Verify that the methods are run in separate threads. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 10); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 20); } } ParallelByMethodsTestCase6Scenario1.java000066400000000000000000001070711475274123300370560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.sample.FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassBFourMethodsWithNoDepsFiveInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassCSixMethodsWithNoDepsThreeInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassDThreeMethodsWithNoDepsFourInstancesSample; import test.thread.parallelization.sample.FactoryForTestClassFSixMethodsWithNoDepsSixInstancesSample; import test.thread.parallelization.sample.TestClassAFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassGThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassHFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassIFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassJFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassKFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassLThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassMFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassNFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassOSixMethodsWithNoDepsSample; /** * This class covers PTP_TC_6, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with parallel test suites using factories but no * dependencies and no data providers. * *

Scenario Description: Three suites with 1, 2 and 3 tests respectively. One suite with two * tests has a test consisting of a single test class without a factory while the other shall * consist of factories which provide multiple instances of multiple test classes. One suite shall * consist of a single test with multiple test classes which uses factories. One suite shall have * multiple tests with multiple classes, none of which use a factory. * *

1) The suite thread pool is 2, so one suite will have to wait for one of the others to * complete execution before it can begin execution 2) For one of the suites, the thread count and * parallel mode are specified at the suite level 3) For one of the suites, the thread count and * parallel mode are specified at the test level 4) For one of the suites, the parallel mode is * specified at the suite level, and the thread counts are specified at the test level (thread * counts for each test differ) 5) The thread count is less than the number of test methods for the * tests in two of the suites, so some methods will have to wait for the active thread count to drop * below the maximum thread count before they can begin execution. 6) The thread count is more than * the number of test methods for the tests in one of the suites, ensuring that none of the methods * in that suite should have to wait for any other method to complete execution 7) The expectation * is that threads will be spawned for each test method that executes just as they would if there * were no factories and test suites simply used the default mechanism for instantiating single * instances of the test classes. 8) There are NO configuration methods 9) All test methods pass 10) * NO ordering is specified 11) group-by-instances is NOT set 12) There are no method exclusions */ public class ParallelByMethodsTestCase6Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase6Scenario1.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_C = "TestSuiteC"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private static final String SUITE_C_TEST_A = "TestSuiteC-ThreeTestClassTest"; private static final String SUITE_C_TEST_B = "TestSuiteC-TwoTestClassTest"; private static final String SUITE_C_TEST_C = "TestSuiteC-FourTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteThreeSuiteAndTestLevelEventLogs; private List suiteThreeSuiteLevelEventLogs; private List suiteThreeTestLevelEventLogs; private List suiteThreeTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private List suiteThreeTestOneTestMethodLevelEventLogs; private List suiteThreeTestTwoTestMethodLevelEventLogs; private List suiteThreeTestThreeTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); XmlSuite suiteThree = createXmlSuite(SUITE_C); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(10); createXmlTest( suiteOne, SUITE_A_TEST_A, FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample.class, FactoryForTestClassCSixMethodsWithNoDepsThreeInstancesSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, FactoryForTestClassDThreeMethodsWithNoDepsFourInstancesSample.class, FactoryForTestClassBFourMethodsWithNoDepsFiveInstancesSample.class, FactoryForTestClassFSixMethodsWithNoDepsSixInstancesSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(3); } else { test.setThreadCount(20); } } createXmlTest( suiteThree, SUITE_C_TEST_A, TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_B, TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_C, TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class); for (XmlTest test : suiteThree.getTests()) { test.setParallel(XmlSuite.ParallelMode.METHODS); switch (test.getName()) { case SUITE_C_TEST_A: test.setThreadCount(10); break; case SUITE_C_TEST_B: test.setThreadCount(5); break; default: test.setThreadCount(12); break; } } addParams(suiteOne, SUITE_A, SUITE_A_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_A, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_C, "100"); TestNG tng = create(suiteOne, suiteTwo, suiteThree); tng.setSuiteThreadPoolSize(2); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase6Scenario1. This test scenario consists of three " + "suites with 1, 2 and 3 tests respectively. The suites run in parallel and the thread pool size is " + "2. One suite with two tests has a test consisting of a single test class without a factory while " + "the other shall consist of factories which provide multiple instances of multiple test classes. One " + "suite shall consist of a single test with multiple test classes which uses factories. One suite " + "shall have multiple tests with multiple classes, none of which use a factory. There are no " + "dependencies."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassCSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 10"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithNoDepsSample.class + ", " + TestClassBFourMethodsWithNoDepsSample.class + ", " + TestClassFSixMethodsWithNoDepsSample.class + ". Thread count: 20"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_A + ", Test classes: " + TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassIFiveMethodsWithNoDepsSample.class + ". Thread count: 10"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_B + ", Test classes: " + TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassKFiveMethodsWithNoDepsSample.class + ". Thread count: 5"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_C + ", Test classes: " + TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 12."); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteThreeSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_C); suiteThreeSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_C); suiteThreeTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_C); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_C); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_A, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A)); testEventLogsMap.put(SUITE_C_TEST_B, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_C, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteThreeSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_C); suiteThreeSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_C); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_C); suiteThreeTestThreeListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_C); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 6, "There should be 6 suite level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 12, "There should be 12 test level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 420, "There should 420 test method level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 84, "There should be 84 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 219, "There should be 219 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); assertEquals( suiteThreeSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_C + ": " + suiteThreeSuiteLevelEventLogs); assertEquals( suiteThreeTestLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_C + ": " + suiteThreeTestLevelEventLogs); assertEquals( suiteThreeTestMethodLevelEventLogs.size(), 117, "There should be 87 test method level events " + "logged for " + SUITE_C + ": " + suiteThreeTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); verifySequentialTests( suiteThreeSuiteAndTestLevelEventLogs, suiteThreeTestLevelEventLogs, suiteThreeSuiteListenerOnStartEventLog, suiteThreeSuiteListenerOnFinishEventLog); } // Verify the expected number of test class instances for the test method events. // Verify that the same test class instances are associated with each of the test methods from the // sample test class @Test public void verifyNumberOfInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class), 2, 3); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithNoDepsSample.class, TestClassCSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class), 4, 5, 6); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithNoDepsSample.class, TestClassBFourMethodsWithNoDepsSample.class, TestClassFSixMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestOneListenerOnStartEventLog, suiteThreeTestOneTestMethodLevelEventLogs, suiteThreeTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_A + ". Test listener onStart event log: " + suiteThreeTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestTwoListenerOnStartEventLog, suiteThreeTestTwoTestMethodLevelEventLogs, suiteThreeTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_B + ". Test listener onStart event log: " + suiteThreeTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestThreeListenerOnStartEventLog, suiteThreeTestThreeTestMethodLevelEventLogs, suiteThreeTestThreeListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_C + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_C + ". Test listener onStart event log: " + suiteThreeTestThreeListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestThreeListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestThreeTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassGThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassHFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassIFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassJFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassKFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassLThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassMFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassNFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassOSixMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); } // Verify that the methods are run in separate threads in true parallel fashion by checking that // the start and run // times of events that should be run simultaneously start basically at the same time using the // timestamps and the // known values of the wait time specified for the event. Verify that the thread IDs of parallel // events are // different. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 10); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 20); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A), SUITE_C_TEST_A, 10); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B), SUITE_C_TEST_B, 5); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C), SUITE_C_TEST_C, 12); } } ParallelByMethodsTestCase7Scenario1.java000066400000000000000000000243731475274123300370620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteAndTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartThreadId; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.List; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.sample.TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample; /** * This class covers PTP_TC_7, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites using a factory which * uses a non-parallel data provider and there are no dependencies. * *

Scenario Description: Single suite with a single test consisting of a single test class with * five methods with a factory method using a data provider specifying 3 sets of data. * *

1) Thread count and parallel mode are specified at the suite level 2) The thread count is * equal to the number of test methods times 3, the number of times each method will be invoked with * a data set from the data provider. Expectation is that only 15 threads will be spawned at once. * There will be three instances of the test class, one for each of the three data sets and each * instance will have the five test methods defined on the class, for a total of 15 test method * invocations. 3) No test method invocation should be queued because the thread count is sufficient * to service all the test method invocations. 4) There are NO configuration methods 5) All test * methods pass 6) NO ordering is specified 7) group-by-instances is NOT set 8) There are no method * exclusions */ public class ParallelByMethodsTestCase7Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase7Scenario1.class); private static final String SUITE = "SingleTestSuite"; private static final String TEST = "SingleTestClassTest"; private List suiteLevelEventLogs; private List testLevelEventLogs; private List suiteAndTestLevelEventLogs; private List testMethodLevelEventLogs; private EventLog suiteListenerOnStartEventLog; private EventLog suiteListenerOnFinishEventLog; private EventLog testListenerOnStartEventLog; private EventLog testListenerOnFinishEventLog; private Long testListenerOnStartThreadId; @BeforeClass public void setUp() { reset(); XmlSuite suite = createXmlSuite(SUITE); suite.setParallel(XmlSuite.ParallelMode.METHODS); suite.setThreadCount(15); createXmlTest( suite, TEST, TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class); addParams(suite, SUITE, TEST, "100", "paramOne,paramTwo,paramThree"); TestNG tng = create(suite); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase7Scenario1. This test scenario consists of a " + "single suite with a single test consisting of a single test class with five methods with a " + "factory method using a data provider specifying 3 sets of data. There are no dependencies."); log.debug( "Suite: " + SUITE + ", Test: " + TEST + ", Test class: " + TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + ". Thread count: 15"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); suiteAndTestLevelEventLogs = getAllSuiteAndTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE); suiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE); testListenerOnStartEventLog = getTestListenerStartEventLog(SUITE, TEST); testListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE, TEST); testListenerOnStartThreadId = getTestListenerStartThreadId(SUITE, TEST); } // Verifies that the expected number of suite, test and test method level events were logged. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 45, "There should be 45 test method level events logged for " + SUITE + ": " + testMethodLevelEventLogs); } // Verify that the suite listener and test listener events have timestamps in the following order: // suite start, // test start, test finish, suite finish. Verify that all of these events run in the same thread // because the // parallelization mode is by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderInSameThread() { verifySameThreadIdForAllEvents( suiteAndTestLevelEventLogs, "The thread ID for all the suite and test level " + "event logs should be the same because there is no parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifySequentialTimingOfEvents( suiteAndTestLevelEventLogs, "The timestamps of suite and test level events " + "logged first should be earlier than those which are logged afterwards because there is no " + "parallelism specified at the suite or test level: " + suiteAndTestLevelEventLogs); verifyEventsOccurBetween( suiteListenerOnStartEventLog, testLevelEventLogs, suiteListenerOnFinishEventLog, "All of the test level event logs should have timestamps between the suite listener's onStart and " + "onFinish event logs. Suite listener onStart event log: " + suiteListenerOnStartEventLog + ". Suite listener onFinish event log: " + suiteListenerOnFinishEventLog + ". Test level " + "event logs: " + testLevelEventLogs); } // Verify that there are three test class instance associated with each of the test methods from // the sample test // class // Verify that the same test class instances are associated with each of the test methods from the // sample test class @Test public void verifyThreeInstancesOfTestClassForAllTestMethods() { verifyNumberOfInstancesOfTestClassForMethods( SUITE, TEST, TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, 3); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE, TEST, TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class); } // Verifies that all the test method level events execute between the test listener onStart and // onFinish methods @Test public void verifyTestMethodLevelEventsAllOccurBetweenTestListenerStartAndFinish() { verifyEventsOccurBetween( testListenerOnStartEventLog, testMethodLevelEventLogs, testListenerOnFinishEventLog, "All of the test method level event logs should have timestamps between the test listener's onStart " + "and onFinish event logs. Test Listener onStart event log: " + testListenerOnStartEventLog + ". Test Listener onFinish event log: " + testListenerOnFinishEventLog + ". Test method level " + "event logs: " + testMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( testListenerOnStartThreadId, testMethodLevelEventLogs, "All the thread IDs " + "for the test method level events should be greater than the thread ID for the suite and test level " + "events. The expectation is that since the suite and test level events are running sequentially, and " + "all the test methods are running in parallel, new threads will be spawned after the thread " + "executing the suite and test level events when new methods begin executing. Suite and test level " + "events thread ID: " + testListenerOnStartThreadId + ". Test method level event logs: " + testMethodLevelEventLogs); } // Verifies that all the test method level events for any given test method in any given instance // run in the same // thread. @Test public void verifyThatAllEventsForATestMethodExecuteInSameThread() { verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE, TEST); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods(getTestMethodLevelEventLogsForTest(SUITE, TEST), TEST, 15); } } ParallelByMethodsTestCase7Scenario2.java000066400000000000000000000553131475274123300370610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.sample.TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample; /** * This class covers PTP_TC_7, Scenario 2 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with sequential test suites using a factory with a * non-parallel data provider and there are no dependencies. * *

Scenario Description: Two suites with 1 and 2 tests respectively. One suite with two tests has * a test consisting of a single test class without a factory while the other consists of factories * using data providers with varying numbers of data sets which provide multiple instances of * multiple test classes. One suite shall consist of a single test with multiple test classes which * use factories with data providers with varying numbers of data sets. * *

1) For both suites, the thread count and parallel mode are specified at the suite level 2) The * thread count is less than the number of test methods for all tests in both suites, so methods * will have to wait for the active thread count to drop below the maximum thread count before they * can begin execution. The expectation is that threads will be spawned for each test method that * executes just as they would if there were no factories and data providers and test suites simply * use the default mechanism for instantiating single instances of the test classes. 3) There are NO * configuration methods 4) All test methods pass 5) NO ordering is specified 6) group-by-instances * is NOT set 7) There are no method exclusions */ public class ParallelByMethodsTestCase7Scenario2 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase7Scenario2.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private Map> suiteEventLogsMap = new HashMap<>(); private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(25); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(3); } else { test.setThreadCount(40); } } addParams( suiteOne, SUITE_A, SUITE_A_TEST_A, "100", TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + "(paramOne,paramTwo,paramThree)" + TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + "(paramOne,paramTwo,paramThree,paramFour)"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams( suiteTwo, SUITE_B, SUITE_B_TEST_B, "100", TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + "(paramOne,paramTwo,paramThree)" + TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + "(paramOne,paramTwo,paramThree,paramFour)" + TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + "(paramOne,paramTwo,paramThree,paramFour,paramFive)"); TestNG tng = create(suiteOne, suiteTwo); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase7Scenario2. This test scenario consists of two " + "suites with 1 and 2 tests respectively. One suite with two tests has a test consisting of a single " + "test class without a factory while the other consists of factories using data providers with " + "varying numbers of data sets which provide multiple instances of multiple test classes. One suite " + "shall consist of a single test with multiple test classes which use factories with data providers " + "with varying numbers of data sets. There are no dependencies."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + ", " + TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + ". Thread count: 25"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class + ", " + TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class + ", " + TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class + ". Thread count: 40"); tng.run(); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteEventLogsMap.put(SUITE_A, getAllEventLogsForSuite(SUITE_A)); suiteEventLogsMap.put(SUITE_B, getAllEventLogsForSuite(SUITE_B)); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 4, "There should be 4 suite level events logged for " + SUITE_A + " and " + SUITE_B + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_A + " and " + SUITE_B + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 297, "There should 267 test method level events logged for " + SUITE_A + " and " + SUITE_B + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 117, "There should be 117 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 180, "There should be 180 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); } // Verify that all the events in the second suite run have timestamps later than the suite // listener's onFinish event // for the first suite run. // Verify that all suite level events run in the same thread @Test public void verifySuitesRunSequentiallyInSameThread() { verifySequentialSuites(suiteLevelEventLogs, suiteEventLogsMap); } // For all suites, verify that the test level events run sequentially because the parallel mode is // by methods only. @Test public void verifySuiteAndTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); } // Verify the expected number of test class instances for the test method events. // Verify that the same test class instances are associated with each of the test methods from the // sample test class @Test public void verifyNumberOfInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class), 3, 4); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class), 3, 4, 5); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); } // Verify that the methods are run in separate threads. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 25); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 40); } } ParallelByMethodsTestCase8Scenario1.java000066400000000000000000001331411475274123300370550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.testng.Assert.assertEquals; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllSuiteListenerStartEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getAllTestMethodLevelEventLogs; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteAndTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getSuiteListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerFinishEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestListenerStartEventLog; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForSuite; import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodLevelEventLogsForTest; import static test.thread.parallelization.TestNgRunStateTracker.reset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.log4testng.Logger; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.thread.parallelization.sample.TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassEFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample; import test.thread.parallelization.sample.TestClassGThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassHFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassIFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassJFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassKFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassLThreeMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassMFourMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassNFiveMethodsWithNoDepsSample; import test.thread.parallelization.sample.TestClassOSixMethodsWithNoDepsSample; /** * This class covers PTP_TC_8, Scenario 1 in the Parallelization Test Plan. * *

Test Case Summary: Parallel by methods mode with parallel test suites using factories with * data providers but no dependencies. * *

Scenario Description: Three suites with 1, 2 and 3 tests respectively. One suite with two * tests has a test consisting of a single test class without a factory while the other shall * consist of test classes with factories using data providers with varying numbers of data sets. * One suite shall consist of a single test with multiple test classes with factories using data * providers with varying numbers of data sets. One suite shall have multiple tests with multiple * classes, none of which use a factory. * *

1) The suite thread pool is 2, so one suite will have to wait for one of the others to * complete execution before it can begin execution 2) For one of the suites, the thread count and * parallel mode are specified at the suite level 3) For one of the suites, the thread count and * parallel mode are specified at the test level 4) For one of the suites, the parallel mode is * specified at the suite level, and the thread counts are specified at the test level (thread * counts for each test differ) 5) The thread count is less than the number of test methods for the * tests in two of the suites, so some methods will have to wait for the active thread count to drop * below the maximum thread count before they can begin execution. 6) The thread count is more than * the number of test methods for the tests in one of the suites, ensuring that none of the methods * in that suite should have to wait for any other method to complete execution 7) The expectation * is that threads will be spawned for each test method that executes just as they would if there * were no factories and test suites simply used the default mechanism for instantiating single * instances of the test classes. 8) There are NO configuration methods 9) All test methods pass 10) * NO ordering is specified 11) `group-by-instances is NOT set 12) here are no method exclusions */ public class ParallelByMethodsTestCase8Scenario1 extends BaseParallelizationTest { private static final Logger log = Logger.getLogger(ParallelByMethodsTestCase8Scenario1.class); private static final String SUITE_A = "TestSuiteA"; private static final String SUITE_B = "TestSuiteB"; private static final String SUITE_C = "TestSuiteC"; private static final String SUITE_A_TEST_A = "TestSuiteA-TwoTestClassTest"; private static final String SUITE_B_TEST_A = "TestSuiteB-SingleTestClassTest"; private static final String SUITE_B_TEST_B = "TestSuiteB-ThreeTestClassTest"; private static final String SUITE_C_TEST_A = "TestSuiteC-ThreeTestClassTest"; private static final String SUITE_C_TEST_B = "TestSuiteC-TwoTestClassTest"; private static final String SUITE_C_TEST_C = "TestSuiteC-FourTestClassTest"; private static final int THREAD_POOL_SIZE = 2; private Map expectedInvocationCounts = new HashMap<>(); private Map> testEventLogsMap = new HashMap<>(); private List suiteLevelEventLogs; private List testLevelEventLogs; private List testMethodLevelEventLogs; private List suiteOneSuiteAndTestLevelEventLogs; private List suiteOneSuiteLevelEventLogs; private List suiteOneTestLevelEventLogs; private List suiteOneTestMethodLevelEventLogs; private List suiteTwoSuiteAndTestLevelEventLogs; private List suiteTwoSuiteLevelEventLogs; private List suiteTwoTestLevelEventLogs; private List suiteTwoTestMethodLevelEventLogs; private List suiteThreeSuiteAndTestLevelEventLogs; private List suiteThreeSuiteLevelEventLogs; private List suiteThreeTestLevelEventLogs; private List suiteThreeTestMethodLevelEventLogs; private List suiteOneTestOneTestMethodLevelEventLogs; private List suiteTwoTestOneTestMethodLevelEventLogs; private List suiteTwoTestTwoTestMethodLevelEventLogs; private List suiteThreeTestOneTestMethodLevelEventLogs; private List suiteThreeTestTwoTestMethodLevelEventLogs; private List suiteThreeTestThreeTestMethodLevelEventLogs; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeSuiteListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteOneTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteTwoTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestOneListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestTwoListenerOnFinishEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnStartEventLog; private TestNgRunStateTracker.EventLog suiteThreeTestThreeListenerOnFinishEventLog; @BeforeClass public void setUp() { reset(); XmlSuite suiteOne = createXmlSuite(SUITE_A); XmlSuite suiteTwo = createXmlSuite(SUITE_B); XmlSuite suiteThree = createXmlSuite(SUITE_C); suiteOne.setParallel(XmlSuite.ParallelMode.METHODS); suiteOne.setThreadCount(10); createXmlTest( suiteOne, SUITE_A_TEST_A, TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class); createXmlTest(suiteTwo, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); createXmlTest( suiteTwo, SUITE_B_TEST_B, TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class); suiteTwo.setParallel(XmlSuite.ParallelMode.METHODS); for (XmlTest test : suiteTwo.getTests()) { if (test.getName().equals(SUITE_B_TEST_A)) { test.setThreadCount(3); } else { test.setThreadCount(20); } } createXmlTest( suiteThree, SUITE_C_TEST_A, TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_B, TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class); createXmlTest( suiteThree, SUITE_C_TEST_C, TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class); for (XmlTest test : suiteThree.getTests()) { test.setParallel(XmlSuite.ParallelMode.METHODS); switch (test.getName()) { case SUITE_C_TEST_A: test.setThreadCount(25); break; case SUITE_C_TEST_B: test.setThreadCount(5); break; default: test.setThreadCount(12); break; } } addParams( suiteOne, SUITE_A, SUITE_A_TEST_A, "100", TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + "(paramOne,paramTwo,paramThree)" + TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + "(paramOne,paramTwo,paramThree,paramFour)"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_A, "100"); addParams(suiteTwo, SUITE_B, SUITE_B_TEST_B, "100", "paramOne,paramTwo,paramThree,paramFour"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_A, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_B, "100"); addParams(suiteThree, SUITE_C, SUITE_C_TEST_C, "100"); TestNG tng = create(suiteOne, suiteTwo, suiteThree); tng.setSuiteThreadPoolSize(2); tng.addListener((ITestNGListener) new TestNgRunStateListener()); log.debug( "Beginning ParallelByMethodsTestCase8Scenario1. This test scenario consists of three " + "suites with 1, 2 and 3 tests respectively. One suite with two tests has a test consisting of a " + "single test class without a factory while the other shall consist of test classes with factories " + "using data providers with varying numbers of data sets. One suite shall consist of a single test " + "with multiple test classes with factories using data providers with varying numbers of data sets. " + "One suite shall have multiple tests with multiple classes, none of which use a factory."); log.debug( "Suite: " + SUITE_A + ", Test: " + SUITE_A_TEST_A + ", Test classes: " + TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + ", " + TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class .getCanonicalName() + ". Thread count: 10"); log.debug( "Suite: " + SUITE_B + ", Test: " + SUITE_B_TEST_A + ", Test class: " + TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 3"); log.debug( "Suite " + SUITE_B + ", Test: " + SUITE_B_TEST_B + ", Test classes: " + TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class + ", " + TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class + ", " + TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class + ". Thread count: 20"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_A + ", Test classes: " + TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassIFiveMethodsWithNoDepsSample.class + ". Thread count: 10"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_B + ", Test classes: " + TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassKFiveMethodsWithNoDepsSample.class + ". Thread count: 5"); log.debug( "Suite: " + SUITE_C + ", Test: " + SUITE_C_TEST_C + ", Test classes: " + TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ", " + TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ". Thread count: 12."); tng.run(); expectedInvocationCounts.put( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 3); expectedInvocationCounts.put( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 3); expectedInvocationCounts.put( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 4); expectedInvocationCounts.put( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 4); expectedInvocationCounts.put( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 4); expectedInvocationCounts.put( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 4); expectedInvocationCounts.put( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 4); expectedInvocationCounts.put( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 4); expectedInvocationCounts.put( TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassEFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 4); expectedInvocationCounts.put( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 4); expectedInvocationCounts.put( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 4); expectedInvocationCounts.put( TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 4); expectedInvocationCounts.put( TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 4); expectedInvocationCounts.put( TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 4); expectedInvocationCounts.put( TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 4); expectedInvocationCounts.put( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodA", 4); expectedInvocationCounts.put( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodB", 4); expectedInvocationCounts.put( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodC", 4); expectedInvocationCounts.put( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodD", 4); expectedInvocationCounts.put( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodE", 4); expectedInvocationCounts.put( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getCanonicalName() + ".testMethodF", 4); expectedInvocationCounts.put( TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassGThreeMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassHFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassIFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassIFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassIFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassIFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassIFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassJFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassKFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassLThreeMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassMFourMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassNFiveMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodA", 1); expectedInvocationCounts.put( TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodB", 1); expectedInvocationCounts.put( TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodC", 1); expectedInvocationCounts.put( TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodD", 1); expectedInvocationCounts.put( TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodE", 1); expectedInvocationCounts.put( TestClassOSixMethodsWithNoDepsSample.class.getCanonicalName() + ".testMethodF", 1); suiteLevelEventLogs = getAllSuiteLevelEventLogs(); testLevelEventLogs = getAllTestLevelEventLogs(); testMethodLevelEventLogs = getAllTestMethodLevelEventLogs(); suiteOneSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_A); suiteOneSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_A); suiteOneTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_A); suiteTwoSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_B); suiteTwoSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_B); suiteTwoTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_B); suiteThreeSuiteAndTestLevelEventLogs = getSuiteAndTestLevelEventLogsForSuite(SUITE_C); suiteThreeSuiteLevelEventLogs = getSuiteLevelEventLogsForSuite(SUITE_C); suiteThreeTestLevelEventLogs = getTestLevelEventLogsForSuite(SUITE_C); suiteOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_A); suiteTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_B); suiteThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForSuite(SUITE_C); suiteOneTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeTestMethodLevelEventLogs = getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C); testEventLogsMap.put(SUITE_B_TEST_A, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A)); testEventLogsMap.put(SUITE_B_TEST_B, getTestLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_A, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A)); testEventLogsMap.put(SUITE_C_TEST_B, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B)); testEventLogsMap.put(SUITE_C_TEST_C, getTestLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C)); suiteOneSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_A); suiteOneSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_A); suiteTwoSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_B); suiteTwoSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_B); suiteThreeSuiteListenerOnStartEventLog = getSuiteListenerStartEventLog(SUITE_C); suiteThreeSuiteListenerOnFinishEventLog = getSuiteListenerFinishEventLog(SUITE_C); suiteOneTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_A, SUITE_A_TEST_A); suiteOneTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_A, SUITE_A_TEST_A); suiteTwoTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_A); suiteTwoTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_B, SUITE_B_TEST_B); suiteTwoTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_B, SUITE_B_TEST_B); suiteThreeTestOneListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestOneListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_A); suiteThreeTestTwoListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestTwoListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_B); suiteThreeTestThreeListenerOnStartEventLog = getTestListenerStartEventLog(SUITE_C, SUITE_C_TEST_C); suiteThreeTestThreeListenerOnFinishEventLog = getTestListenerFinishEventLog(SUITE_C, SUITE_C_TEST_C); } // Verifies that the expected number of suite, test and test method level events were logged for // each of the three // suites. @Test public void sanityCheck() { assertEquals( suiteLevelEventLogs.size(), 6, "There should be 6 suite level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + suiteLevelEventLogs); assertEquals( testLevelEventLogs.size(), 12, "There should be 12 test level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testLevelEventLogs); assertEquals( testMethodLevelEventLogs.size(), 405, "There should 405 test method level events logged for " + SUITE_A + ", " + SUITE_B + " and " + SUITE_C + ": " + testMethodLevelEventLogs); assertEquals( suiteOneSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_A + ": " + suiteOneSuiteLevelEventLogs); assertEquals( suiteOneTestLevelEventLogs.size(), 2, "There should be 2 test level events logged for " + SUITE_A + ": " + suiteOneTestLevelEventLogs); assertEquals( suiteOneTestMethodLevelEventLogs.size(), 117, "There should be 117 test method level events " + "logged for " + SUITE_A + ": " + suiteOneTestMethodLevelEventLogs); assertEquals( suiteTwoSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_B + ": " + suiteTwoSuiteLevelEventLogs); assertEquals( suiteTwoTestLevelEventLogs.size(), 4, "There should be 4 test level events logged for " + SUITE_B + ": " + suiteTwoTestLevelEventLogs); assertEquals( suiteTwoTestMethodLevelEventLogs.size(), 171, "There should be 171 test method level events " + "logged for " + SUITE_B + ": " + suiteTwoTestMethodLevelEventLogs); assertEquals( suiteThreeSuiteLevelEventLogs.size(), 2, "There should be 2 suite level events logged for " + SUITE_C + ": " + suiteThreeSuiteLevelEventLogs); assertEquals( suiteThreeTestLevelEventLogs.size(), 6, "There should be 6 test level events logged for " + SUITE_C + ": " + suiteThreeTestLevelEventLogs); assertEquals( suiteThreeTestMethodLevelEventLogs.size(), 117, "There should be 117 test method level events " + "logged for " + SUITE_C + ": " + suiteThreeTestMethodLevelEventLogs); } // Verify that the suites run in parallel by checking that the suite and test level events for // both suites have // overlapping timestamps. Verify that there are two separate threads executing the suite-level // and test-level // events for each suite. @Test public void verifyThatSuitesRunInParallelThreads() { verifyParallelSuitesWithUnequalExecutionTimes(suiteLevelEventLogs, THREAD_POOL_SIZE); } @Test public void verifyTestLevelEventsRunInSequentialOrderForIndividualSuites() { verifySequentialTests( suiteOneSuiteAndTestLevelEventLogs, suiteOneTestLevelEventLogs, suiteOneSuiteListenerOnStartEventLog, suiteOneSuiteListenerOnFinishEventLog); verifySequentialTests( suiteTwoSuiteAndTestLevelEventLogs, suiteTwoTestLevelEventLogs, suiteTwoSuiteListenerOnStartEventLog, suiteTwoSuiteListenerOnFinishEventLog); verifySequentialTests( suiteThreeSuiteAndTestLevelEventLogs, suiteThreeTestLevelEventLogs, suiteThreeSuiteListenerOnStartEventLog, suiteThreeSuiteListenerOnFinishEventLog); } // Verify the expected number of test class instances for the test method events. // Verify that the same test class instances are associated with each of the test methods from the // sample test class @Test public void verifyNumberOfInstanceOfTestClassForAllTestMethodsForAllSuites() { verifyNumberOfInstancesOfTestClassesForMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class), 3, 4); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_A, SUITE_A_TEST_A, Arrays.asList( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassForMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class, 1); verifySameInstancesOfTestClassAssociatedWithMethods( SUITE_B, SUITE_B_TEST_A, TestClassEFiveMethodsWithNoDepsSample.class); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class), 4, 4, 4); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_B, SUITE_B_TEST_B, Arrays.asList( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_A, Arrays.asList( TestClassGThreeMethodsWithNoDepsSample.class, TestClassHFourMethodsWithNoDepsSample.class, TestClassIFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_B, Arrays.asList( TestClassJFourMethodsWithNoDepsSample.class, TestClassKFiveMethodsWithNoDepsSample.class)); verifyNumberOfInstancesOfTestClassesForMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class), 1); verifySameInstancesOfTestClassesAssociatedWithMethods( SUITE_C, SUITE_C_TEST_C, Arrays.asList( TestClassLThreeMethodsWithNoDepsSample.class, TestClassMFourMethodsWithNoDepsSample.class, TestClassNFiveMethodsWithNoDepsSample.class, TestClassOSixMethodsWithNoDepsSample.class)); } // Verify that the test method listener's onTestStart method runs after the test listener's // onStart method for // all the test methods in all tests and suites. @Test public void verifyTestLevelMethodLevelEventLogsOccurBetweenAfterTestListenerStartAndFinishEventLogs() { verifyEventsOccurBetween( suiteOneTestOneListenerOnStartEventLog, suiteOneTestOneTestMethodLevelEventLogs, suiteOneTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_A_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_A_TEST_A + ". Test listener onStart event log: " + suiteOneTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteOneTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteOneTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestOneListenerOnStartEventLog, suiteTwoTestOneTestMethodLevelEventLogs, suiteTwoTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_A + ". Test listener onStart event log: " + suiteTwoTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteTwoTestTwoListenerOnStartEventLog, suiteTwoTestTwoTestMethodLevelEventLogs, suiteTwoTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_B_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_B_TEST_B + ". Test listener onStart event log: " + suiteTwoTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteTwoTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteTwoTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestOneListenerOnStartEventLog, suiteThreeTestOneTestMethodLevelEventLogs, suiteThreeTestOneListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_A + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_A + ". Test listener onStart event log: " + suiteThreeTestOneListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestOneListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestOneTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestTwoListenerOnStartEventLog, suiteThreeTestTwoTestMethodLevelEventLogs, suiteThreeTestTwoListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_B + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_B + ". Test listener onStart event log: " + suiteThreeTestTwoListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestTwoListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestTwoTestMethodLevelEventLogs); verifyEventsOccurBetween( suiteThreeTestThreeListenerOnStartEventLog, suiteThreeTestThreeTestMethodLevelEventLogs, suiteThreeTestThreeListenerOnFinishEventLog, "All of the test method level event logs for " + SUITE_C_TEST_C + " should have timestamps between the test listener's onStart and onFinish " + "event logs for " + SUITE_C_TEST_C + ". Test listener onStart event log: " + suiteThreeTestThreeListenerOnStartEventLog + ". Test listener onFinish event log: " + suiteThreeTestThreeListenerOnFinishEventLog + ". Test method level event logs: " + suiteThreeTestThreeTestMethodLevelEventLogs); } // Verifies that the method level events all run in different threads from the test and suite // level events. // Verifies that the test method listener and execution events for a given test method all run in // the same thread. @Test public void verifyThatMethodLevelEventsRunInDifferentThreadsFromSuiteAndTestLevelEvents() { verifyEventThreadsSpawnedAfter( getAllSuiteListenerStartEventLogs().get(0).getThreadId(), testMethodLevelEventLogs, "All the thread IDs for the test method level events should be greater than the thread ID for the " + "suite and test level events. The expectation is that since the suite and test level events " + "are running sequentially, and all the test methods are running in parallel, new threads " + "will be spawned after the thread executing the suite and test level events when new methods " + "begin executing. Suite and test level events thread ID: " + getAllSuiteListenerStartEventLogs().get(0).getThreadId() + ". Test method level event logs: " + testMethodLevelEventLogs); verifyEventsForTestMethodsRunInTheSameThread( TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_A, SUITE_A_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassEFiveMethodsWithNoDepsSample.class, SUITE_B, SUITE_B_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class, SUITE_B, SUITE_B_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassGThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassHFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassIFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_A); verifyEventsForTestMethodsRunInTheSameThread( TestClassJFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassKFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_B); verifyEventsForTestMethodsRunInTheSameThread( TestClassLThreeMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassMFourMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassNFiveMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); verifyEventsForTestMethodsRunInTheSameThread( TestClassOSixMethodsWithNoDepsSample.class, SUITE_C, SUITE_C_TEST_C); } // Verifies that the test methods execute in different threads in parallel fashion. @Test public void verifyThatTestMethodsRunInParallelThreads() { verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_A, SUITE_A_TEST_A), SUITE_A_TEST_A, 10); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_A), SUITE_B_TEST_A, 3); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_B, SUITE_B_TEST_B), SUITE_B_TEST_B, 20); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_A), SUITE_C_TEST_A, 25); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_B), SUITE_C_TEST_B, 5); verifySimultaneousTestMethods( getTestMethodLevelEventLogsForTest(SUITE_C, SUITE_C_TEST_C), SUITE_C_TEST_C, 12); } } TestNgRunStateListener.java000066400000000000000000000122331475274123300346070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_SUITE_FINISH; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_SUITE_START; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_FINISH; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_FAIL; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_FAIL_PERCENTAGE; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_PASS; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_SKIPPED; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_START; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_START; import static test.thread.parallelization.TestNgRunStateTracker.logEvent; import java.util.concurrent.TimeUnit; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import test.thread.parallelization.TestNgRunStateTracker.EventLog; import test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent; public class TestNgRunStateListener implements ISuiteListener, ITestListener { @Override public void onStart(ISuite suite) { logEvent(buildEventLog(suite, LISTENER_SUITE_START).build()); delayAfterEvent(LISTENER_SUITE_START); } @Override public void onFinish(ISuite suite) { logEvent(buildEventLog(suite, LISTENER_SUITE_FINISH).build()); delayAfterEvent(LISTENER_SUITE_FINISH); } @Override public void onStart(ITestContext context) { logEvent(buildEventLog(context, LISTENER_TEST_START).build()); delayAfterEvent(LISTENER_TEST_START); } @Override public void onFinish(ITestContext context) { logEvent(buildEventLog(context, LISTENER_TEST_FINISH).build()); delayAfterEvent(LISTENER_TEST_FINISH); } @Override public void onTestStart(ITestResult result) { logEvent(buildEventLog(result, LISTENER_TEST_METHOD_START).build()); delayAfterEvent(LISTENER_TEST_METHOD_START); } @Override public void onTestSuccess(ITestResult result) { logEvent(buildEventLog(result, LISTENER_TEST_METHOD_PASS).build()); delayAfterEvent(LISTENER_TEST_METHOD_PASS); } @Override public void onTestFailure(ITestResult result) { logEvent(buildEventLog(result, LISTENER_TEST_METHOD_FAIL).build()); delayAfterEvent(LISTENER_TEST_METHOD_FAIL); } @Override public void onTestSkipped(ITestResult result) { logEvent(buildEventLog(result, LISTENER_TEST_METHOD_SKIPPED).build()); delayAfterEvent(LISTENER_TEST_METHOD_SKIPPED); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { logEvent(buildEventLog(result, LISTENER_TEST_METHOD_FAIL_PERCENTAGE).build()); delayAfterEvent(LISTENER_TEST_METHOD_FAIL_PERCENTAGE); } private TestNgRunStateTracker.EventLogBuilder buildEventLog(ISuite suite, TestNgRunEvent event) { long time = System.currentTimeMillis(); return EventLog.builder() .setEvent(event) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(SUITE_NAME, suite.getName()); } private TestNgRunStateTracker.EventLogBuilder buildEventLog( ITestContext context, TestNgRunEvent event) { return buildEventLog(context.getSuite(), event).addData(TEST_NAME, context.getName()); } private TestNgRunStateTracker.EventLogBuilder buildEventLog( ITestResult result, TestNgRunEvent event) { return (buildEventLog(result.getTestContext(), event)) .addData(METHOD_NAME, result.getMethod().getMethodName()) .addData(CLASS_NAME, result.getMethod().getRealClass().getCanonicalName()) .addData(CLASS_INSTANCE, result.getMethod().getInstance()) .addData(GROUPS_DEPENDED_ON, result.getMethod().getGroupsDependedUpon()) .addData(METHODS_DEPENDED_ON, result.getMethod().getMethodsDependedUpon()) .addData(GROUPS_BELONGING_TO, result.getMethod().getGroups()); } private void delayAfterEvent(TestNgRunEvent event) { try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { throw new RuntimeException("Problem with delaying after listener event: " + event, e); } } } TestNgRunStateTracker.java000066400000000000000000001150371475274123300344230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; /** * {@code TestNgRunStateTracker} tracks state information for a TestNG run: suite listener start, * suite listener end, test listener start, test listener end, method listener start, method * execution, and method listener completion. {@code TestNgRunStateListener} can be used in * conjunction with {@code TestNgRunStateTracker} to log the time and thread IDs for each of these * events. */ public class TestNgRunStateTracker { private static final Collection eventLogs = new ConcurrentLinkedQueue<>(); public static void logEvent(EventLog eventLog) { eventLogs.add(eventLog); } // Get all event logs for all suites public static Collection getAllEventLogs() { return eventLogs; } // Get all suite level event logs public static List getAllSuiteLevelEventLogs() { List suiteEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isSuiteLevelEventLog(eventLog)) { suiteEventLogs.add(eventLog); } } return suiteEventLogs; } // Get all suite listener onStart event logs public static List getAllSuiteListenerStartEventLogs() { List suiteStartEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_SUITE_START) { suiteStartEventLogs.add(eventLog); } } return suiteStartEventLogs; } // Get all suite listener onFinish event logs public static List getAllSuiteListenerFinishEventLogs() { List suiteFinishEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_SUITE_FINISH) { suiteFinishEventLogs.add(eventLog); } } return suiteFinishEventLogs; } // Get all suite level event logs associated with the specified suite public static List getSuiteLevelEventLogsForSuite(String suiteName) { List suiteEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isSuiteLevelEventLog(eventLog) && belongsToSuite(suiteName, eventLog)) { suiteEventLogs.add(eventLog); } } return suiteEventLogs; } // Get all event logs associated with the specified suite public static List getAllEventLogsForSuite(String suiteName) { List suiteEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (belongsToSuite(suiteName, eventLog)) { suiteEventLogs.add(eventLog); } } return suiteEventLogs; } // Get event logs for the specified suite and event public static List getEventLogsByEventTypeForSuite( String suiteName, TestNgRunEvent event) { List suiteEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == event && belongsToSuite(suiteName, eventLog)) { suiteEventLogs.add(eventLog); } } return suiteEventLogs; } // Get the event log for the suite listener's onStart method for the specified suite public static EventLog getSuiteListenerStartEventLog(String suiteName) { for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_SUITE_START && belongsToSuite(suiteName, eventLog)) { return eventLog; } } return null; } // Get the event log for the suite listener's onStart method for the specified suite public static EventLog getSuiteListenerFinishEventLog(String suiteName) { for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_SUITE_FINISH && belongsToSuite(suiteName, eventLog)) { return eventLog; } } return null; } // Get the timestamp for the suite listener's onStart method for the specified suite public static Long getSuiteListenerStartTimestamp(String suiteName) { EventLog eventLog = getSuiteListenerStartEventLog(suiteName); return eventLog == null ? null : eventLog.getTimeOfEvent(); } // Get the timestamp for suite listener's onFinish method for the specified suite public static Long getSuiteListenerFinishTimestamp(String suiteName) { EventLog eventLog = getSuiteListenerFinishEventLog(suiteName); return eventLog == null ? null : eventLog.getTimeOfEvent(); } // Get the threadId for suite listener's onStart method for the specified suite public static Long getSuiteListenerStartThreadId(String suiteName) { EventLog eventLog = getSuiteListenerStartEventLog(suiteName); return eventLog == null ? null : eventLog.getThreadId(); } // Get the threadId for suite listener's onFinish method for the specified suite public static Long getSuiteListenerFinishThreadId(String suiteName) { EventLog eventLog = getSuiteListenerFinishEventLog(suiteName); return eventLog == null ? null : eventLog.getThreadId(); } // Get all test level event logs public static List getAllTestLevelEventLogs() { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isTestLevelEventLog(eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get all suite and test level event logs public static List getAllSuiteAndTestLevelEventLogs() { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isSuiteLevelEventLog(eventLog) || isTestLevelEventLog(eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get all test level event logs for the specified suite public static List getTestLevelEventLogsForSuite(String suiteName) { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isTestLevelEventLog(eventLog) && belongsToSuite(suiteName, eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get all suite and test level event logs for the specified suite public static List getSuiteAndTestLevelEventLogsForSuite(String suiteName) { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if ((isSuiteLevelEventLog(eventLog) || isTestLevelEventLog(eventLog)) && belongsToSuite(suiteName, eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get all the test listener onStart event logs for the specified suite public static List getTestListenerStartEventLogsForSuite(String suiteName) { List testStartEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_START && belongsToSuite(suiteName, eventLog)) { testStartEventLogs.add(eventLog); } } return testStartEventLogs; } // Get all the test listener onFinish event logs for the specified suite public static List getTestListenerFinishEventLogsForSuite(String suiteName) { List testFinishEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_FINISH && belongsToSuite(suiteName, eventLog)) { testFinishEventLogs.add(eventLog); } } return testFinishEventLogs; } // Get all test level event logs for with the specified test public static List getTestLevelEventLogsForTest(String suiteName, String testName) { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isTestLevelEventLog(eventLog) && belongsToTest(suiteName, testName, eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get all event logs associated with the specified test public static List getAllEventLogsForTest(String suiteName, String testName) { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (belongsToTest(suiteName, testName, eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get event logs for the specified test and event public static List getEventLogsByEventTypeForTest( String suiteName, String testName, TestNgRunEvent event) { List testEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == event && belongsToTest(suiteName, testName, eventLog)) { testEventLogs.add(eventLog); } } return testEventLogs; } // Get event log for test listener's onStart method for the specified test public static EventLog getTestListenerStartEventLog(String suiteName, String testName) { for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_START && belongsToTest(suiteName, testName, eventLog)) { return eventLog; } } return null; } // Get event log for test listener's onFinish method for the specified test public static EventLog getTestListenerFinishEventLog(String suiteName, String testName) { for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_FINISH && belongsToTest(suiteName, testName, eventLog)) { return eventLog; } } return null; } // Get the timestamp for test listener's onStart method for the specified test public static Long getTestListenerStartTimestamp(String suiteName, String testName) { EventLog eventLog = getTestListenerStartEventLog(suiteName, testName); return eventLog == null ? null : eventLog.getTimeOfEvent(); } // Get the timestamp for test listener's onFinish method for the specified test public static Long getTestListenerFinishTimestamp(String suiteName, String testName) { EventLog eventLog = getTestListenerFinishEventLog(suiteName, testName); return eventLog == null ? null : eventLog.getTimeOfEvent(); } // Get the threadId for test listener's onStart method for the specified test public static Long getTestListenerStartThreadId(String suiteName, String testName) { EventLog eventLog = getTestListenerStartEventLog(suiteName, testName); return eventLog == null ? null : eventLog.getThreadId(); } // Get the threadId for test listener's onFinish method for the specified test public static Long getTestListenerFinishThreadId(String suiteName, String testName) { EventLog eventLog = getTestListenerFinishEventLog(suiteName, testName); return eventLog == null ? null : eventLog.getThreadId(); } // Get all test method level event logs public static List getAllTestMethodLevelEventLogs() { List testMethodEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isTestMethodLevelEventLog(eventLog)) { testMethodEventLogs.add(eventLog); } } return testMethodEventLogs; } // Get all test method level event logs for the specified suite public static List getTestMethodLevelEventLogsForSuite(String suiteName) { List testMethodEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isTestMethodLevelEventLog(eventLog) && belongsToSuite(suiteName, eventLog)) { testMethodEventLogs.add(eventLog); } } return testMethodEventLogs; } // Get all test method level event logs for the specified test public static List getTestMethodLevelEventLogsForTest( String suiteName, String testName) { List testMethodEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (isTestMethodLevelEventLog(eventLog) && belongsToTest(suiteName, testName, eventLog)) { testMethodEventLogs.add(eventLog); } } return testMethodEventLogs; } // Get the test method listener onTestStart event logs for the specified suite and test public static List getTestMethodListenerStartEventLogsForTest( String suiteName, String testName) { List testMethodStartEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_START && belongsToTest(suiteName, testName, eventLog)) { testMethodStartEventLogs.add(eventLog); } } return testMethodStartEventLogs; } // Get the test method listener onTestSuccess event logs for the specified suite and test public static List getTestMethodListenerPassEventLogsForTest( String suiteName, String testName) { List testMethodPassEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_PASS && belongsToTest(suiteName, testName, eventLog)) { testMethodPassEventLogs.add(eventLog); } } return testMethodPassEventLogs; } // Get the test method execution event logs for the specified suite and test public static List getTestMethodExecutionEventLogsForTest( String suiteName, String testName) { List testMethodExecuteEventLogs = new ArrayList<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == TestNgRunEvent.TEST_METHOD_EXECUTION && belongsToTest(suiteName, testName, eventLog)) { testMethodExecuteEventLogs.add(eventLog); } } return testMethodExecuteEventLogs; } // Get the test method level event logs for the test methods from the specified suite, test and // test class, separated // out in a map where the keys are the class instances on which the methods were run. public static Multimap getTestMethodEventLogsForClass( String suiteName, String testName, String className) { Multimap testMethodEventLogs = ArrayListMultimap.create(); for (EventLog eventLog : eventLogs) { if (isTestMethodLevelEventLog(eventLog) && belongsToClass(suiteName, testName, className, eventLog)) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the test method level event logs for the test method from the specified suite, test and // test class, separated // out in a map where the keys are the class instances on which the method was run. public static Multimap getTestMethodEventLogsForMethod( String suiteName, String testName, String className, String methodName) { Multimap testMethodEventLogs = ArrayListMultimap.create(); for (EventLog eventLog : eventLogs) { if (belongsToMethod(suiteName, testName, className, methodName, eventLog)) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } public static Multimap getTestMethodEventLogsForMethodsBelongingToGroup( String groupName) { Multimap testMethodEventLogs = ArrayListMultimap.create(); for (EventLog eventLog : getAllTestMethodLevelEventLogs()) { String[] groupsBelongingTo = (String[]) eventLog.getData(EventInfo.GROUPS_BELONGING_TO); if (Arrays.asList(groupsBelongingTo).contains(groupName)) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } public static Multimap getTestMethodEventLogsForMethodsDependedOn( String suiteName, String testName, String className, String methodName) { Multimap testMethodEventLogs = ArrayListMultimap.create(); Map startEventLogs = getTestMethodListenerStartEventLogsForMethod(suiteName, testName, className, methodName); EventLog eventLog = new ArrayList<>(startEventLogs.values()).get(0); String[] methodsDependedOn = (String[]) eventLog.getData(EventInfo.METHODS_DEPENDED_ON); for (String methodDependOn : methodsDependedOn) { testMethodEventLogs.putAll( getTestMethodEventLogsForMethod(suiteName, testName, className, methodDependOn)); } return testMethodEventLogs; } public static Multimap getTestMethodEventLogsForMethodsBelongingToGroupsDependedOn( String suiteName, String testName, String className, String methodName) { Multimap testMethodEventLogs = ArrayListMultimap.create(); Map startEventLogs = getTestMethodListenerStartEventLogsForMethod(suiteName, testName, className, methodName); EventLog eventLog = new ArrayList<>(startEventLogs.values()).get(0); String[] groupsDependedOn = (String[]) eventLog.getData(EventInfo.GROUPS_DEPENDED_ON); for (String groupDependedOn : groupsDependedOn) { testMethodEventLogs.putAll(getTestMethodEventLogsForMethodsBelongingToGroup(groupDependedOn)); } return testMethodEventLogs; } // Get the test method event logs of the specified type for the specified test class from the // specified suite and // test in a multimap where the keys are the class instances for the test class public static Multimap getTestMethodEventLogsByEventTypeForClass( String suiteName, String testName, String className, TestNgRunEvent event) { Multimap testMethodEventLogs = ArrayListMultimap.create(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == event && belongsToClass(suiteName, testName, className, eventLog)) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the test method level event logs for the test method from the specified suite, test, test // class, and event // separated out in a map where the keys are the class instances on which the method was run. public static Map getTestMethodEventLogsByEventTypeForMethod( String suiteName, String testName, String className, String methodName, TestNgRunEvent event) { Map testMethodEventLogs = new HashMap<>(); for (EventLog eventLog : eventLogs) { if (eventLog.getEvent() == event && belongsToMethod(suiteName, testName, className, methodName, eventLog)) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the event logs for test method listener's onTestStart method for the specified test method // from the // specified suite, test and test class as a map where the keys are the test class instances on // which the method was // run public static Map getTestMethodListenerStartEventLogsForMethod( String suiteName, String testName, String className, String methodName) { return getTestMethodEventLogsByEventTypeForMethod( suiteName, testName, className, methodName, TestNgRunEvent.LISTENER_TEST_METHOD_START); } // Get the event logs for test method listener's onTestSuccess method for the specified test // method from the // specified suite, test and test class as a map where the keys are the test class instances on // which the method was // run public static Map getTestMethodListenerPassEventLogsForMethod( String suiteName, String testName, String className, String methodName) { Map testMethodEventLogs = new HashMap<>(); for (EventLog eventLog : eventLogs) { if (belongsToMethod(suiteName, testName, className, methodName, eventLog) && eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_PASS) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the event logs for test method listener's onTestFailure method for the specified test // method from the // specified suite, test and test class as a map where the keys are the test class instances on // which the method was // run public static Map getTestMethodListenerFailEventLogsForMethod( String suiteName, String testName, String className, String methodName) { Map testMethodEventLogs = new HashMap<>(); for (EventLog eventLog : eventLogs) { if (belongsToMethod(suiteName, testName, className, methodName, eventLog) && eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_FAIL) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the event logs for test method listener's onTestFailedButWithinSuccessPercentage method for // the specified // test method from the specified suite, test and test class as a map where the keys are the test // class instances on // which the method was run public static Map getTestMethodListenerFailWithinSuccessPercentageEventLogsForMethod( String suiteName, String testName, String className, String methodName) { Map testMethodEventLogs = new HashMap<>(); for (EventLog eventLog : eventLogs) { if (belongsToMethod(suiteName, testName, className, methodName, eventLog) && eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_FAIL_PERCENTAGE) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the event logs for test method listener's nTestSkipped method for the specified test method // from the // specified suite, test and test class as a map where the keys are the test class instances on // which the method was run public static Map getTestMethodListenerSkippedEventLogsForMethod( String suiteName, String testName, String className, String methodName) { Map testMethodEventLogs = new HashMap<>(); for (EventLog eventLog : eventLogs) { if (belongsToMethod(suiteName, testName, className, methodName, eventLog) && eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_SKIPPED) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the event logs for execution of the test method's body for the specified test method from // the // specified suite, test and test class as a map where the keys are the test class instances on // which the method was run public static Map getTestMethodExecutionEventLogsForMethod( String suiteName, String testName, String className, String methodName) { Map testMethodEventLogs = new HashMap<>(); for (EventLog eventLog : eventLogs) { if (belongsToMethod(suiteName, testName, className, methodName, eventLog) && eventLog.getEvent() == TestNgRunEvent.TEST_METHOD_EXECUTION) { testMethodEventLogs.put(eventLog.getData(EventInfo.CLASS_INSTANCE), eventLog); } } return testMethodEventLogs; } // Get the timestamps for test method listener's onTestStart method for the specified test method // from the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerStartTimestamps( String suiteName, String testName, String className, String methodName) { Map testMethodEventTimes = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerStartEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventTimes.put(instance, testMethodEventLogs.get(instance).getTimeOfEvent()); } return testMethodEventTimes; } // Get the timestamps for test listener's onTestSuccess method for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerPassTimestamps( String suiteName, String testName, String className, String methodName) { Map testMethodEventTimes = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerPassEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventTimes.put(instance, testMethodEventLogs.get(instance).getTimeOfEvent()); } return testMethodEventTimes; } // Get the timestamps for test listener's onTestFailure method for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerFailTimestamps( String suiteName, String testName, String className, String methodName) { Map testMethodEventTimes = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerFailEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventTimes.put(instance, testMethodEventLogs.get(instance).getTimeOfEvent()); } return testMethodEventTimes; } // Get the timestamps for test listener's onTestFailedButWithinSuccessPercentage method for the // specified test method // from the specified suite, test and test class separated out in a map where the keys are the // class instances on // which the method was run. public static Map getTestMethodListenerFailWithinSuccessPercentageTimestamps( String suiteName, String testName, String className, String methodName) { Map testMethodEventTimes = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerFailWithinSuccessPercentageEventLogsForMethod( suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventTimes.put(instance, testMethodEventLogs.get(instance).getTimeOfEvent()); } return testMethodEventTimes; } // Get the timestamps for test method listener onTestSkipped event logs for the specified test // method from the // specified suite, test and test class. public static Map getTestMethodListenerSkipTimestamps( String suiteName, String testName, String className, String methodName) { Map testMethodEventTimes = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerSkippedEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventTimes.put(instance, testMethodEventLogs.get(instance).getTimeOfEvent()); } return testMethodEventTimes; } // Get the timestamps for execution of the test method's body for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodExecutionTimestamps( String suiteName, String testName, String className, String methodName) { Map testMethodEventTimes = new HashMap<>(); Map testMethodEventLogs = getTestMethodExecutionEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventTimes.put(instance, testMethodEventLogs.get(instance).getTimeOfEvent()); } return testMethodEventTimes; } // Get the thread IDs for test method listener's onTestStart method for the specified test method // from the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerStartThreadIds( String suiteName, String testName, String className, String methodName) { Map testMethodEventThreadIds = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerStartEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventThreadIds.put(instance, testMethodEventLogs.get(instance).getThreadId()); } return testMethodEventThreadIds; } // Get the thread IDs for test listener's onTestSuccess method for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerPassThreadIds( String suiteName, String testName, String className, String methodName) { Map testMethodEventThreadIds = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerPassEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventThreadIds.put(instance, testMethodEventLogs.get(instance).getThreadId()); } return testMethodEventThreadIds; } // Get the thread IDs for test listener's onTestFailure method for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerFailThreadIds( String suiteName, String testName, String className, String methodName) { Map testMethodEventThreadIds = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerFailEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventThreadIds.put(instance, testMethodEventLogs.get(instance).getThreadId()); } return testMethodEventThreadIds; } // Get the thread IDs for test listener's onTestFailedButWithinSuccessPercentage method for the // specified test // method from the specified suite, test and test class separated out in a map where the keys are // the class // instances on which the method was run. public static Map getTestMethodListenerFailWithSuccessPercentageThreadIds( String suiteName, String testName, String className, String methodName) { Map testMethodEventThreadIds = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerFailWithinSuccessPercentageEventLogsForMethod( suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventThreadIds.put(instance, testMethodEventLogs.get(instance).getThreadId()); } return testMethodEventThreadIds; } // Get the thread IDs for test listener's onTestSkipped method for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodListenerSkipThreadIds( String suiteName, String testName, String className, String methodName) { Map testMethodEventThreadIds = new HashMap<>(); Map testMethodEventLogs = getTestMethodListenerSkippedEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventThreadIds.put(instance, testMethodEventLogs.get(instance).getThreadId()); } return testMethodEventThreadIds; } // Get the thread IDs for execution of the test method's body for the specified test method from // the specified // suite, test and test class separated out in a map where the keys are the class instances on // which the method was // run. public static Map getTestMethodExecutionThreadIds( String suiteName, String testName, String className, String methodName) { Map testMethodEventThreadIds = new HashMap<>(); Map testMethodEventLogs = getTestMethodExecutionEventLogsForMethod(suiteName, testName, className, methodName); for (Object instance : testMethodEventLogs.keySet()) { testMethodEventThreadIds.put(instance, testMethodEventLogs.get(instance).getThreadId()); } return testMethodEventThreadIds; } public static void reset() { eventLogs.clear(); } private static boolean isSuiteLevelEventLog(EventLog eventLog) { return eventLog.getEvent() == TestNgRunEvent.LISTENER_SUITE_START || eventLog.getEvent() == TestNgRunEvent.LISTENER_SUITE_FINISH; } private static boolean isTestLevelEventLog(EventLog eventLog) { return eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_START || eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_FINISH; } private static boolean isTestMethodLevelEventLog(EventLog eventLog) { return eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_START || eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_PASS || eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_FAIL || eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_FAIL_PERCENTAGE || eventLog.getEvent() == TestNgRunEvent.LISTENER_TEST_METHOD_SKIPPED || eventLog.getEvent() == TestNgRunEvent.TEST_METHOD_EXECUTION; } private static boolean belongsToSuite(String suiteName, EventLog eventLog) { return suiteName.equals(eventLog.getData(EventInfo.SUITE_NAME)); } private static boolean belongsToTest(String suiteName, String testName, EventLog eventLog) { return suiteName.equals(eventLog.getData(EventInfo.SUITE_NAME)) && testName.equals(eventLog.getData(EventInfo.TEST_NAME)); } private static boolean belongsToClass( String suiteName, String testName, String className, EventLog eventLog) { return suiteName.equals(eventLog.getData(EventInfo.SUITE_NAME)) && testName.equals(eventLog.getData(EventInfo.TEST_NAME)) && className.equals(eventLog.getData(EventInfo.CLASS_NAME)); } private static boolean belongsToMethod( String suiteName, String testName, String className, String methodName, EventLog eventLog) { return suiteName.equals(eventLog.getData(EventInfo.SUITE_NAME)) && testName.equals(eventLog.getData(EventInfo.TEST_NAME)) && className.equals(eventLog.getData(EventInfo.CLASS_NAME)) && methodName.equals(eventLog.getData(EventInfo.METHOD_NAME)); } public enum TestNgRunEvent { LISTENER_SUITE_START, LISTENER_SUITE_FINISH, LISTENER_TEST_START, LISTENER_TEST_FINISH, LISTENER_TEST_METHOD_START, TEST_METHOD_EXECUTION, LISTENER_TEST_METHOD_PASS, LISTENER_TEST_METHOD_FAIL, LISTENER_TEST_METHOD_FAIL_PERCENTAGE, LISTENER_TEST_METHOD_SKIPPED, } public enum EventInfo { SUITE_NAME, TEST_NAME, CLASS_NAME, METHOD_NAME, CLASS_INSTANCE, DATA_PROVIDER_PARAM, GROUPS_DEPENDED_ON, METHODS_DEPENDED_ON, GROUPS_BELONGING_TO } public static class EventLog { private TestNgRunEvent event; private long timeOfEvent; private long threadId; private Thread thread; private Map data = new HashMap<>(); public void setEvent(TestNgRunEvent event) { this.event = event; } public TestNgRunEvent getEvent() { return event; } public void setTimeOfEvent(long timeOfEvent) { this.timeOfEvent = timeOfEvent; } public long getTimeOfEvent() { return timeOfEvent; } public void setThread(Thread thread) { this.thread = thread; this.threadId = thread.getId(); } public long getThreadId() { return threadId; } public void addData(EventInfo key, Object value) { data.put(key, value); } public Object getData(EventInfo key) { return data.get(key); } private Thread getThread() { return thread; } public static EventLogBuilder builder() { return new EventLogBuilder(); } @Override public String toString() { final StringBuffer sb = new StringBuffer("EventLog{"); sb.append("Event: ").append(event); sb.append(", Suite: ").append(getData(EventInfo.SUITE_NAME)); if (getData(EventInfo.TEST_NAME) != null) { sb.append(", Test: ").append(getData(EventInfo.TEST_NAME)); } if (getData(EventInfo.CLASS_NAME) != null) { sb.append(", Class: ").append(getData(EventInfo.CLASS_NAME)); } if (getData(EventInfo.CLASS_INSTANCE) != null) { sb.append(", Class instance hash code: ") .append(getData(EventInfo.CLASS_INSTANCE).hashCode()); } if (getData(EventInfo.METHOD_NAME) != null) { sb.append(", Method name: ").append(getData(EventInfo.METHOD_NAME)); } if (getData(EventInfo.DATA_PROVIDER_PARAM) != null) { sb.append(", Data provider param: ").append(getData(EventInfo.DATA_PROVIDER_PARAM)); } Date now = new Date(timeOfEvent); SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sb.append(", Time of event: ").append(sdfDate.format(timeOfEvent)); sb.append(", Thread ID: ").append(threadId); sb.append("}"); return sb.toString(); } } public static class EventLogBuilder { private EventLog eventLog = new EventLog(); public EventLogBuilder setEvent(TestNgRunEvent event) { eventLog.setEvent(event); return this; } public EventLogBuilder setTimeOfEvent(long timeOfEvent) { eventLog.setTimeOfEvent(timeOfEvent); return this; } public EventLogBuilder setThread(Thread thread) { eventLog.setThread(thread); return this; } public EventLogBuilder addData(EventInfo key, Object value) { eventLog.addData(key, value); return this; } public EventLog build() { return eventLog; } } } ThreadAffinityTest.java000066400000000000000000000110121475274123300337420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelizationpackage test.thread.parallelization; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Map; import java.util.Set; import org.assertj.core.api.Assertions; import org.assertj.core.api.SoftAssertions; import org.testng.TestNG; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.internal.RuntimeBehavior; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import test.SimpleBaseTest; import test.thread.parallelization.issue1773.LogGatheringListener; import test.thread.parallelization.issue1773.MethodDependenciesSample1; import test.thread.parallelization.issue1773.MethodDependenciesSample2; import test.thread.parallelization.issue1773.PriorityTestSample1; import test.thread.parallelization.issue1773.PriorityTestSample2; import test.thread.parallelization.issue2110.TestClass; import test.thread.parallelization.issue2321.TestMultipleInstance; public class ThreadAffinityTest extends SimpleBaseTest { @BeforeClass public void setup() { System.setProperty(RuntimeBehavior.TESTNG_THREAD_AFFINITY, "true"); } @BeforeMethod public void beforeMethod() { LogGatheringListener.reset(); } @Test(dataProvider = "dp1") public void testThreadAffinity(Class... classes) { XmlSuite xmlsuite = createXmlSuite("test_suite"); xmlsuite.setParallel(XmlSuite.ParallelMode.CLASSES); xmlsuite.setThreadCount(6); createXmlTest(xmlsuite, "Test_1", classes); TestNG testng = create(xmlsuite); testng.run(); Map, Set> map = LogGatheringListener.getLog().get("Test_1"); SoftAssertions softly = new SoftAssertions(); Arrays.stream(classes) .forEach( each -> softly .assertThat(map.get(each)) .withFailMessage( "All tests within " + each.getName() + " should have run in the same thread") .hasSize(1)); softly.assertAll(); } @Test(dataProvider = "dp2") public void testThreadAffinityAcrossTests(XmlSuite.ParallelMode mode) { XmlSuite xmlsuite = createXmlSuite("test_suite"); xmlsuite.setParallel(XmlSuite.ParallelMode.TESTS); xmlsuite.setThreadCount(6); Class[] testClasses = new Class[] {PriorityTestSample1.class, PriorityTestSample2.class}; createXmlTest(xmlsuite, "Test_1", testClasses).setParallel(mode); createXmlTest(xmlsuite, "Test_2", testClasses).setParallel(mode); TestNG testng = create(xmlsuite); testng.run(); SoftAssertions softly = new SoftAssertions(); for (String test : Arrays.asList("Test_1", "Test_2")) { Map, Set> map = LogGatheringListener.getLog().get(test); for (Class cls : testClasses) { softly .assertThat(map.get(cls)) .withFailMessage( "All tests within " + cls.getName() + " should have run in the same thread") .hasSize(1); } } softly.assertAll(); } @DataProvider(name = "dp2") public Object[][] createTestData() { return new Object[][] {{XmlSuite.ParallelMode.NONE}, {XmlSuite.ParallelMode.CLASSES}}; } @DataProvider(name = "dp1") public Object[][] getData() { return new Object[][] { {PriorityTestSample1.class, PriorityTestSample2.class}, {MethodDependenciesSample1.class, MethodDependenciesSample2.class} }; } @Test(description = "GITHUB-2321") public void testThreadAffinityInFactoryInstances() { ParallelMode mode = ParallelMode.INSTANCES; XmlSuite xmlsuite = createXmlSuite("test_suite"); xmlsuite.setParallel(mode); xmlsuite.setThreadCount(6); createXmlTest(xmlsuite, "Test_1", TestMultipleInstance.class).setParallel(mode); TestNG testng = create(xmlsuite); testng.run(); Assertions.assertThat(testng.getStatus()).isEqualTo(0); } @Test(description = "GITHUB-2110") public void ensureNoNPEIsThrown() { XmlSuite xmlsuite = createXmlSuite("2110_suite"); xmlsuite.setParallel(ParallelMode.CLASSES); xmlsuite.setThreadCount(50); createXmlTest(xmlsuite, "2110_test", TestClass.class); TestNG testng = create(xmlsuite); testng.run(); assertThat(TestClass.getThreadIds()).hasSize(1); } @AfterClass(alwaysRun = true) public void teardown() { System.setProperty(RuntimeBehavior.TESTNG_THREAD_AFFINITY, "false"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue1773/000077500000000000000000000000001475274123300310745ustar00rootroot00000000000000LogGatheringListener.java000066400000000000000000000012431475274123300357400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue1773package test.thread.parallelization.issue1773; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class LogGatheringListener { private static Map, Set>> log = new ConcurrentHashMap<>(); public static Map, Set>> getLog() { return log; } public static void addLog(String testname, Class cls, long threadId) { log.computeIfAbsent(testname, t -> new ConcurrentHashMap<>()) .computeIfAbsent(cls, c -> new HashSet<>()) .add(threadId); } public static void reset() { log = new ConcurrentHashMap<>(); } } MethodDependenciesSample1.java000066400000000000000000000010171475274123300366310ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue1773package test.thread.parallelization.issue1773; import org.testng.Reporter; import org.testng.annotations.Test; public class MethodDependenciesSample1 { @Test public void parentMethod() { log(); } @Test(dependsOnMethods = "parentMethod") public void childMethod() { log(); } private void log() { String testname = Reporter.getCurrentTestResult().getTestContext().getName(); LogGatheringListener.addLog( testname, MethodDependenciesSample1.class, Thread.currentThread().getId()); } } MethodDependenciesSample2.java000066400000000000000000000010171475274123300366320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue1773package test.thread.parallelization.issue1773; import org.testng.Reporter; import org.testng.annotations.Test; public class MethodDependenciesSample2 { @Test public void parentMethod() { log(); } @Test(dependsOnMethods = "parentMethod") public void childMethod() { log(); } private void log() { String testname = Reporter.getCurrentTestResult().getTestContext().getName(); LogGatheringListener.addLog( testname, MethodDependenciesSample2.class, Thread.currentThread().getId()); } } PriorityTestSample1.java000066400000000000000000000010721475274123300355640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue1773package test.thread.parallelization.issue1773; import org.testng.Reporter; import org.testng.annotations.Test; public class PriorityTestSample1 { @Test(priority = 1) public void FirstTest() { log(); } @Test(priority = 2) public void SecondTest() { log(); } @Test(priority = 3) public void ThridTest() { log(); } private void log() { String testname = Reporter.getCurrentTestResult().getTestContext().getName(); LogGatheringListener.addLog( testname, PriorityTestSample1.class, Thread.currentThread().getId()); } } PriorityTestSample2.java000066400000000000000000000010721475274123300355650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue1773package test.thread.parallelization.issue1773; import org.testng.Reporter; import org.testng.annotations.Test; public class PriorityTestSample2 { @Test(priority = 1) public void FirstTest() { log(); } @Test(priority = 2) public void SecondTest() { log(); } @Test(priority = 3) public void ThridTest() { log(); } private void log() { String testname = Reporter.getCurrentTestResult().getTestContext().getName(); LogGatheringListener.addLog( testname, PriorityTestSample2.class, Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue2110/000077500000000000000000000000001475274123300310565ustar00rootroot00000000000000TestClass.java000066400000000000000000000015371475274123300335550ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue2110package test.thread.parallelization.issue2110; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.testng.annotations.Test; public class TestClass { static Set threadIds = Collections.newSetFromMap(new ConcurrentHashMap<>()); public static Set getThreadIds() { return threadIds; } @Test public void test0() { threadIds.add(Thread.currentThread().getId()); } @Test public void test1() { threadIds.add(Thread.currentThread().getId()); } @Test(dependsOnMethods = "test1") public void test2() { threadIds.add(Thread.currentThread().getId()); } @Test(dependsOnMethods = "test2") public void test3() { threadIds.add(Thread.currentThread().getId()); } @Test public void test4() { threadIds.add(Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue2321/000077500000000000000000000000001475274123300310625ustar00rootroot00000000000000TestMultipleInstance.java000066400000000000000000000013541475274123300357710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/issue2321package test.thread.parallelization.issue2321; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class TestMultipleInstance { private long threadId; @Factory(dataProvider = "dp") public TestMultipleInstance(int part) {} @Test public void independent() { threadId = Thread.currentThread().getId(); } @Test(dependsOnMethods = "independent") public void dependent() { long currentThreadId = Thread.currentThread().getId(); Assert.assertEquals(currentThreadId, threadId, "Thread Ids didn't match"); } @DataProvider(name = "dp") public static Object[][] getData() { return new Object[][] {{1}, {2}}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/sample/000077500000000000000000000000001475274123300307035ustar00rootroot00000000000000FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample.java000066400000000000000000000014271475274123300453070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import java.util.ArrayList; import java.util.List; import org.testng.TestNGException; import org.testng.annotations.Factory; import org.testng.internal.objects.InstanceCreator; public class FactoryForTestClassAFiveMethodsWithNoDepsTwoInstancesSample { @Factory public Object[] init() { List instances = new ArrayList<>(); try { instances.add(InstanceCreator.newInstance(TestClassAFiveMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassAFiveMethodsWithNoDepsSample.class)); } catch (TestNGException e) { throw new RuntimeException( "Could not instantiate an instance of TestClassAFiveMethodsWithNoDepsSample", e); } return instances.toArray(); } } FactoryForTestClassBFourMethodsWithNoDepsFiveInstancesSample.java000066400000000000000000000020641475274123300454500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import java.util.ArrayList; import java.util.List; import org.testng.TestNGException; import org.testng.annotations.Factory; import org.testng.internal.objects.InstanceCreator; public class FactoryForTestClassBFourMethodsWithNoDepsFiveInstancesSample { @Factory public Object[] init() { List instances = new ArrayList<>(); try { instances.add(InstanceCreator.newInstance(TestClassBFourMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassBFourMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassBFourMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassBFourMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassBFourMethodsWithNoDepsSample.class)); } catch (TestNGException e) { throw new RuntimeException( "Could not instantiate an instance of TestClassBFourMethodsWithNoDepsSample", e); } return instances.toArray(); } } FactoryForTestClassCSixMethodsWithNoDepsThreeInstancesSample.java000066400000000000000000000015621475274123300454610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import java.util.ArrayList; import java.util.List; import org.testng.TestNGException; import org.testng.annotations.Factory; import org.testng.internal.objects.InstanceCreator; public class FactoryForTestClassCSixMethodsWithNoDepsThreeInstancesSample { @Factory public Object[] init() { List instances = new ArrayList<>(); try { instances.add(InstanceCreator.newInstance(TestClassCSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassCSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassCSixMethodsWithNoDepsSample.class)); } catch (TestNGException e) { throw new RuntimeException( "Could not instantiate an instance of TestClassCSixMethodsWithNoDepsSample", e); } return instances.toArray(); } } FactoryForTestClassDThreeMethodsWithNoDepsFourInstancesSample.java000066400000000000000000000017331475274123300456320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import java.util.ArrayList; import java.util.List; import org.testng.TestNGException; import org.testng.annotations.Factory; import org.testng.internal.objects.InstanceCreator; public class FactoryForTestClassDThreeMethodsWithNoDepsFourInstancesSample { @Factory public Object[] init() { List instances = new ArrayList<>(); try { instances.add(InstanceCreator.newInstance(TestClassDThreeMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassDThreeMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassDThreeMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassDThreeMethodsWithNoDepsSample.class)); } catch (TestNGException e) { throw new RuntimeException( "Could not instantiate an instance of TestClassDThreeMethodsWithNoDepsSample", e); } return instances.toArray(); } } FactoryForTestClassFSixMethodsWithNoDepsSixInstancesSample.java000066400000000000000000000022121475274123300451510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import java.util.ArrayList; import java.util.List; import org.testng.TestNGException; import org.testng.annotations.Factory; import org.testng.internal.objects.InstanceCreator; public class FactoryForTestClassFSixMethodsWithNoDepsSixInstancesSample { @Factory public Object[] init() { List instances = new ArrayList<>(); try { instances.add(InstanceCreator.newInstance(TestClassFSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassFSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassFSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassFSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassFSixMethodsWithNoDepsSample.class)); instances.add(InstanceCreator.newInstance(TestClassFSixMethodsWithNoDepsSample.class)); } catch (TestNGException e) { throw new RuntimeException( "Could not instantiate an instance of TestClassFSixMethodsWithNoDepsSample", e); } return instances.toArray(); } } TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample.java000066400000000000000000000154161475274123300461530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassAFiveMethodsWithDataProviderOnAllMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodD(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodE(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000153451475274123300463470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassAFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodE(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.java000066400000000000000000000162211475274123300462320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample { private final String suiteName; private final String testName; private final int sleepFor; private final String dpVal; @Factory(dataProvider = "data-provider") public TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample( String suiteName, String testName, String sleepFor, String dpVal) { this.suiteName = suiteName; this.testName = testName; this.sleepFor = Integer.parseInt(sleepFor); this.dpVal = dpVal; } @Test public void testMethodA() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodB() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodC() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodD() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodE() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @DataProvider(name = "data-provider") public static Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = null; String classNamePattern = TestClassAFiveMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getSimpleName() + "("; if (dataProviderParam.contains(classNamePattern)) { dataProviderParam = dataProviderParam.substring( dataProviderParam.indexOf(classNamePattern) + classNamePattern.length()); dataProviderParam = dataProviderParam.substring(0, dataProviderParam.indexOf(")")); } dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassAFiveMethodsWithNoDepsSample.java000066400000000000000000000132011475274123300407370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassAFiveMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample.java000066400000000000000000000134761475274123300462020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassBFourMethodsWithDataProviderOnAllMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodD(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.java000066400000000000000000000144721475274123300462630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample { private final String suiteName; private final String testName; private final int sleepFor; private final String dpVal; @Factory(dataProvider = "data-provider") public TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample( String suiteName, String testName, String sleepFor, String dpVal) { this.suiteName = suiteName; this.testName = testName; this.sleepFor = Integer.parseInt(sleepFor); this.dpVal = dpVal; } @Test public void testMethodA() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodB() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodC() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodD() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @DataProvider(name = "data-provider") public static Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = null; String classNamePattern = TestClassBFourMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getSimpleName() + "("; if (dataProviderParam.contains(classNamePattern)) { dataProviderParam = dataProviderParam.substring( dataProviderParam.indexOf(classNamePattern) + classNamePattern.length()); dataProviderParam = dataProviderParam.substring(0, dataProviderParam.indexOf(")")); } dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassBFourMethodsWithNoDepsSample.java000066400000000000000000000113341475274123300407670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassBFourMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample.java000066400000000000000000000173341475274123300460270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassBSixMethodsWithDataProviderOnAllMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodD(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodE(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodF(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000172111475274123300462140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassBSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodD(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodF(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000153451475274123300463510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassCFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodE(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.java000066400000000000000000000177311475274123300461150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample { private final String suiteName; private final String testName; private final int sleepFor; private final String dpVal; @Factory(dataProvider = "data-provider") public TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample( String suiteName, String testName, String sleepFor, String dpVal) { this.suiteName = suiteName; this.testName = testName; this.sleepFor = Integer.parseInt(sleepFor); this.dpVal = dpVal; } @Test public void testMethodA() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodB() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodC() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodD() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodE() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodF() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @DataProvider(name = "data-provider") public static Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = null; String classNamePattern = TestClassCSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getSimpleName() + "("; if (dataProviderParam.contains(classNamePattern)) { dataProviderParam = dataProviderParam.substring( dataProviderParam.indexOf(classNamePattern) + classNamePattern.length()); dataProviderParam = dataProviderParam.substring(0, dataProviderParam.indexOf(")")); } dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassCSixMethodsWithNoDepsSample.java000066400000000000000000000150451475274123300406230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassCSixMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodF(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample.java000066400000000000000000000115601475274123300463300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassDThreeMethodsWithDataProviderOnAllMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000115101475274123300465160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassDThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.java000066400000000000000000000127461475274123300464230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample { private final String suiteName; private final String testName; private final int sleepFor; private final String dpVal; @Factory(dataProvider = "data-provider") public TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample( String suiteName, String testName, String sleepFor, String dpVal) { this.suiteName = suiteName; this.testName = testName; this.sleepFor = Integer.parseInt(sleepFor); this.dpVal = dpVal; } @Test public void testMethodA() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodB() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodC() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @DataProvider(name = "data-provider") public static Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = null; String classNamePattern = TestClassDThreeMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getSimpleName() + "("; if (dataProviderParam.contains(classNamePattern)) { dataProviderParam = dataProviderParam.substring( dataProviderParam.indexOf(classNamePattern) + classNamePattern.length()); dataProviderParam = dataProviderParam.substring(0, dataProviderParam.indexOf(")")); } dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassDThreeMethodsWithNoDepsSample.java000066400000000000000000000074701475274123300411330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassDThreeMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassEFiveMethodsWithNoDepsSample.java000066400000000000000000000132011475274123300407430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassEFiveMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000134261475274123300463730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassEFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000172111475274123300462200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassFSixMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodD(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodF(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.java000066400000000000000000000177311475274123300461200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample { private final String suiteName; private final String testName; private final int sleepFor; private final String dpVal; @Factory(dataProvider = "data-provider") public TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample( String suiteName, String testName, String sleepFor, String dpVal) { this.suiteName = suiteName; this.testName = testName; this.sleepFor = Integer.parseInt(sleepFor); this.dpVal = dpVal; } @Test public void testMethodA() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodB() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodC() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodD() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodE() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @Test public void testMethodF() throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(sleepFor); } @DataProvider(name = "data-provider") public static Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = null; String classNamePattern = TestClassFSixMethodsWithFactoryUsingDataProviderAndNoDepsSample.class.getSimpleName() + "("; if (dataProviderParam.contains(classNamePattern)) { dataProviderParam = dataProviderParam.substring( dataProviderParam.indexOf(classNamePattern) + classNamePattern.length()); dataProviderParam = dataProviderParam.substring(0, dataProviderParam.indexOf(")")); } dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassFSixMethodsWithNoDepsSample.java000066400000000000000000000150441475274123300406250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassFSixMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodF(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000134261475274123300463750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassGFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassGThreeMethodsWithNoDepsSample.java000066400000000000000000000074701475274123300411360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassGThreeMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000153451475274123300463560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassHFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodE(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassHFourMethodsWithNoDepsSample.java000066400000000000000000000113331475274123300407740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassHFourMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassIFiveMethodsWithNoDepsSample.java000066400000000000000000000132011475274123300407470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassIFiveMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000115101475274123300465230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassIThreeMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000134261475274123300464000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassJFourMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodB(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassJFourMethodsWithNoDepsSample.java000066400000000000000000000113331475274123300407760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassJFourMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample.java000066400000000000000000000153451475274123300463610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.DATA_PROVIDER_PARAM; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.Map; import java.util.concurrent.TimeUnit; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassKFiveMethodsWithDataProviderOnSomeMethodsAndNoDepsSample { @Test(dataProvider = "data-provider") public void testMethodA(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodC(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Test(dataProvider = "data-provider") public void testMethodE(String suiteName, String testName, String sleepFor, String dpVal) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(DATA_PROVIDER_PARAM, dpVal) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @DataProvider(name = "data-provider") public Object[][] dataProvider(ITestContext context) { Map params = context.getCurrentXmlTest().getAllParameters(); String suiteName = params.get("suiteName"); String testName = params.get("testName"); String sleepFor = params.get("sleepFor"); String dataProviderParam = params.get("dataProviderParam"); String[] dataProviderVals = dataProviderParam.split(","); Object[][] dataToProvide = new Object[dataProviderVals.length][4]; for (int i = 0; i < dataProviderVals.length; i++) { dataToProvide[i][0] = suiteName; dataToProvide[i][1] = testName; dataToProvide[i][2] = sleepFor; dataToProvide[i][3] = dataProviderVals[i]; } return dataToProvide; } } TestClassKFiveMethodsWithNoDepsSample.java000066400000000000000000000132011475274123300407510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassKFiveMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassLThreeMethodsWithNoDepsSample.java000066400000000000000000000074701475274123300411430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassLThreeMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassMFourMethodsWithNoDepsSample.java000066400000000000000000000113331475274123300410010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassMFourMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassNFiveMethodsWithNoDepsSample.java000066400000000000000000000132011475274123300407540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassNFiveMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } TestClassOSixMethodsWithNoDepsSample.java000066400000000000000000000150441475274123300406360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/parallelization/samplepackage test.thread.parallelization.sample; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_INSTANCE; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_BELONGING_TO; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.GROUPS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHODS_DEPENDED_ON; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME; import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.TEST_NAME; import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION; import java.util.concurrent.TimeUnit; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import test.thread.parallelization.TestNgRunStateTracker; public class TestClassOSixMethodsWithNoDepsSample { @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodA(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodA") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodB(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodB") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodC(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodC") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodD(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodD") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodE(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodE") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } @Parameters({"suiteName", "testName", "sleepFor"}) @Test public void testMethodF(String suiteName, String testName, String sleepFor) throws InterruptedException { long time = System.currentTimeMillis(); TestNgRunStateTracker.logEvent( TestNgRunStateTracker.EventLog.builder() .setEvent(TEST_METHOD_EXECUTION) .setTimeOfEvent(time) .setThread(Thread.currentThread()) .addData(METHOD_NAME, "testMethodF") .addData(CLASS_NAME, getClass().getCanonicalName()) .addData(CLASS_INSTANCE, this) .addData(TEST_NAME, testName) .addData(SUITE_NAME, suiteName) .addData(GROUPS_DEPENDED_ON, new String[0]) .addData(METHODS_DEPENDED_ON, new String[0]) .addData(GROUPS_BELONGING_TO, new String[0]) .build()); TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepFor)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/thread/testng.xml000066400000000000000000000007541475274123300262640ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/000077500000000000000000000000001475274123300244475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/GitHub1314Sample.java000066400000000000000000000007311475274123300301500ustar00rootroot00000000000000package test.timeout; import org.testng.annotations.Test; public class GitHub1314Sample { @Test private void iWorkWell() { System.out.println("Test1"); } @Test( timeOut = 100, dependsOnMethods = {"iWorkWell"}) private void iHangHorribly() { System.out.println("Test2"); while (true) { int two = 1 + 1; } } @Test(dependsOnMethods = {"iHangHorribly"}) private void iAmNeverRun() { System.out.println("Test3"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/InvocationTimeOutSampleTest.java000066400000000000000000000010351475274123300327330ustar00rootroot00000000000000package test.timeout; import org.testng.annotations.Test; public class InvocationTimeOutSampleTest { @Test(invocationCount = 5, invocationTimeOut = 2_000) public void shouldPass() { try { Thread.sleep(250); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } @Test(invocationCount = 5, invocationTimeOut = 1_000) public void shouldFail() { try { Thread.sleep(250); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TestTimeOutSampleTest.java000066400000000000000000000004201475274123300315360ustar00rootroot00000000000000package test.timeout; import org.testng.annotations.Test; public class TestTimeOutSampleTest { @Test public void timeoutTest() { try { Thread.sleep(2_000); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TimeOutFromXmlTest.java000066400000000000000000000043561475274123300310550ustar00rootroot00000000000000package test.timeout; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.testng.annotations.Test; import org.testng.xml.SuiteXmlParser; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.BaseTest; public class TimeOutFromXmlTest extends BaseTest { private void timeOutTest(boolean onSuite) { addClass(TestTimeOutSampleTest.class); if (onSuite) { setSuiteTimeOut(1_000); } else { setTestTimeOut(1_000); } run(); verifyPassedTests(); verifyFailedTests("timeoutTest"); } @Test public void timeOutOnSuiteTag() { timeOutTest(true /* on suite */); } @Test public void timeOutOnTestTag() { timeOutTest(false /* on test */); } @Test public void noTimeOut() { addClass(TestTimeOutSampleTest.class); run(); verifyPassedTests("timeoutTest"); verifyFailedTests(); } @Test public void twoDifferentTests() { XmlSuite result = new XmlSuite(); result.setName("Suite"); createXmlTest(result, "WithoutTimeOut"); createXmlTest(result, "WithTimeOut").setTimeOut(1_000); setSuite(result); run(); verifyPassedTests("timeoutTest"); verifyFailedTests("timeoutTest"); } private XmlTest createXmlTest(XmlSuite suite, String name) { XmlTest result = new XmlTest(suite); result.setName(name); List classes = new ArrayList<>(); XmlClass cls = new XmlClass(TestTimeOutSampleTest.class); cls.setIncludedMethods(Collections.singletonList(new XmlInclude("timeoutTest"))); classes.add(cls); result.setXmlClasses(classes); return result; } @Test public void timeOutInParallelTestsFromXml() throws IOException { String file = "src/test/resources/test/timeout/issue575.xml"; try (FileInputStream stream = new FileInputStream(file)) { SuiteXmlParser suiteParser = new SuiteXmlParser(); XmlSuite suite = suiteParser.parse(file, stream, true); setSuite(suite); run(); verifyPassedTests("timeoutShouldPass"); verifyFailedTests("timeoutShouldFailByException", "timeoutShouldFailByTimeOut"); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TimeOutIntegrationTest.java000066400000000000000000000026561475274123300317550ustar00rootroot00000000000000package test.timeout; import static org.assertj.core.api.Assertions.assertThat; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.InvokedMethodNameListener; import test.SimpleBaseTest; public class TimeOutIntegrationTest extends SimpleBaseTest { @Test(description = "https://github.com/cbeust/testng/issues/811") public void testTimeOutWhenParallelIsTest() { TestNG tng = create(TimeOutWithParallelSample.class); tng.setParallel(XmlSuite.ParallelMode.TESTS); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getFailedMethodNames()).containsExactly("myTestMethod"); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSucceedMethodNames()).isEmpty(); } @Test(description = "https://github.com/cbeust/testng/issues/1314") public void testGitHub1314() { TestNG tng = create(GitHub1314Sample.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); tng.addListener((ITestNGListener) listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("iWorkWell"); assertThat(listener.getFailedMethodNames()).containsExactly("iHangHorribly"); assertThat(listener.getSkippedMethodNames()).containsExactly("iAmNeverRun"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TimeOutSample2Test.java000066400000000000000000000004441475274123300307660ustar00rootroot00000000000000package test.timeout; import org.testng.annotations.Test; /** * Tests timeouts set from testng.xml * * @author cbeust */ public class TimeOutSample2Test { @Test(timeOut = 1_500) public void timeoutShouldFailByTimeOut() throws InterruptedException { Thread.sleep(10_000); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TimeOutSampleTest.java000066400000000000000000000010601475274123300306770ustar00rootroot00000000000000package test.timeout; import org.testng.annotations.Test; /** * This class tests timeouts * * @author cbeust */ public class TimeOutSampleTest { @Test(timeOut = 5_000 /* 5 seconds */) public void timeoutShouldPass() {} @Test(timeOut = 5_000 /* 5 seconds */) public void timeoutShouldFailByException() { throw new RuntimeException("EXCEPTION SHOULD MAKE THIS METHOD FAIL"); } @Test(timeOut = 1_000 /* 1 second */) public void timeoutShouldFailByTimeOut() throws InterruptedException { Thread.sleep(10_000 /* 10 seconds */); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TimeOutTest.java000066400000000000000000000061571475274123300275510ustar00rootroot00000000000000package test.timeout; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.internal.thread.ThreadTimeoutException; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import test.BaseTest; import test.timeout.github1493.TestClassSample; import test.timeout.issue2009.TimeOutWithParallelSample; public class TimeOutTest extends BaseTest { private final long m_id; public TimeOutTest() { m_id = System.currentTimeMillis(); } private void privateTimeOutTest(XmlSuite.ParallelMode parallel) { addClass(TimeOutSampleTest.class); if (parallel != null) { setParallel(parallel); } run(); verifyPassedTests("timeoutShouldPass"); verifyFailedTests("timeoutShouldFailByException", "timeoutShouldFailByTimeOut"); } @DataProvider(name = "parallelModes") public Iterator createData() { final Iterator parallelModes = Arrays.asList(XmlSuite.ParallelMode.values()).iterator(); return new Iterator() { @Override public boolean hasNext() { return parallelModes.hasNext(); } @Override public Object[] next() { return new Object[] {parallelModes.next()}; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }; } @Test(dataProvider = "parallelModes") public void timeOutInParallel(XmlSuite.ParallelMode parallelMode) { privateTimeOutTest(parallelMode); } @Test public void timeOutInNonParallel() { privateTimeOutTest(null); } @Test public void verifyInvocationTimeOut() { addClass(InvocationTimeOutSampleTest.class); run(); verifyPassedTests("shouldPass"); verifyFailedTests("shouldFail"); } @Test public void testWithOnlyOneThread() { addClass(TestClassSample.class); run(); Collection> failed = getFailedTests().values(); Assert.assertEquals(failed.size(), 1); ITestResult failedResult = failed.iterator().next().get(0); Assert.assertTrue(failedResult.getThrowable() instanceof ThreadTimeoutException); Assert.assertEquals( failedResult.getThrowable().getMessage(), String.format( "Method %s.testMethod() didn't finish within the time-out 1000", TestClassSample.class.getName())); } @Test(description = "GITHUB-2009") public void testTimeOutWhenParallelIsMethods() { addClass(TimeOutWithParallelSample.class); setParallel(ParallelMode.METHODS); run(); Assert.assertEquals(getFailedTests().values().size(), 1); Assert.assertEquals(getSkippedTests().values().size(), 0); Assert.assertEquals(getPassedTests().values().size(), 0); ITestResult result = getFailedTests().values().iterator().next().get(0); long time = result.getEndMillis() - result.getStartMillis(); Assert.assertTrue(time < 2000); } @Override public Long getId() { return m_id; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/TimeOutWithParallelSample.java000066400000000000000000000003311475274123300323500ustar00rootroot00000000000000package test.timeout; import org.testng.annotations.Test; public class TimeOutWithParallelSample { @Test(timeOut = 1_000) public void myTestMethod() throws InterruptedException { Thread.sleep(1_500); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github1493/000077500000000000000000000000001475274123300262525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github1493/TestClassSample.java000066400000000000000000000003671475274123300321720ustar00rootroot00000000000000package test.timeout.github1493; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; public class TestClassSample { @Test(timeOut = 1000) public void testMethod() throws Exception { TimeUnit.SECONDS.sleep(2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github2440/000077500000000000000000000000001475274123300262435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github2440/TimeoutTest.java000066400000000000000000000010771475274123300314010ustar00rootroot00000000000000package test.timeout.github2440; import org.testng.annotations.Test; import org.testng.internal.thread.ThreadTimeoutException; public class TimeoutTest { @Test(description = "First", timeOut = 1000) public void test1() throws InterruptedException { Thread.sleep(500); } @Test(description = "Second") public void test2() throws InterruptedException { Thread.sleep(1000); } @Test(description = "Third", expectedExceptions = ThreadTimeoutException.class, timeOut = 100) public void test3() throws InterruptedException { Thread.sleep(1000); } } TimeoutWithNoExecutorTest.java000066400000000000000000000017361475274123300341740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github2440package test.timeout.github2440; import java.util.Collections; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class TimeoutWithNoExecutorTest extends SimpleBaseTest { @Test public void testTimeout() { TestNG testNG = new TestNG(); XmlSuite xmlSuite = new XmlSuite(); XmlTest xmlTest = new XmlTest(xmlSuite); xmlTest.setClasses(Collections.singletonList(new XmlClass(TimeoutTest.class))); xmlSuite.setParallel(XmlSuite.ParallelMode.CLASSES); testNG.setXmlSuites(Collections.singletonList(xmlSuite)); TestListenerAdapter listener = new TestListenerAdapter(); testNG.addListener(listener); testNG.run(); Assert.assertTrue(listener.getFailedTests().isEmpty()); Assert.assertTrue(listener.getConfigurationFailures().isEmpty()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github2672/000077500000000000000000000000001475274123300262525ustar00rootroot00000000000000TimeoutStacktraceTest.java000066400000000000000000000022521475274123300333320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github2672package test.timeout.github2672; import static org.testng.Assert.assertTrue; import java.util.Arrays; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.internal.thread.ThreadTimeoutException; public class TimeoutStacktraceTest { private static class TimeoutStacktraceTestListener implements ITestListener { private Throwable testError = null; @Override public void onTestSuccess(ITestResult result) { testError = result.getThrowable(); } public Throwable getTestError() { return testError; } } @Test public void verifyTimeoutStacktrace() { TestNG testng = new TestNG(); testng.setTestClasses(new Class[] {TimeoutStacktraceTestSample.class}); TimeoutStacktraceTestListener listener = new TimeoutStacktraceTestListener(); testng.addListener(listener); testng.run(); Throwable testError = listener.getTestError(); assertTrue(testError instanceof ThreadTimeoutException); assertTrue( Arrays.stream(testError.getStackTrace()) .anyMatch(s -> s.getMethodName().equals("testTimeoutStacktrace"))); } } TimeoutStacktraceTestSample.java000066400000000000000000000006131475274123300344730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/github2672package test.timeout.github2672; import org.testng.annotations.Test; import org.testng.internal.thread.ThreadTimeoutException; class TimeoutStacktraceTestSample { @Test( description = "testTimeoutStacktrace", expectedExceptions = ThreadTimeoutException.class, timeOut = 100) public void testTimeoutStacktrace() throws InterruptedException { Thread.sleep(1000); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/issue2009/000077500000000000000000000000001475274123300261125ustar00rootroot00000000000000TimeOutWithParallelSample.java000066400000000000000000000003401475274123300337340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/timeout/issue2009package test.timeout.issue2009; import org.testng.annotations.Test; public class TimeOutWithParallelSample { @Test(timeOut = 1000) public void myTestMethod() throws InterruptedException { Thread.sleep(2000); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/000077500000000000000000000000001475274123300235615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/A.java000066400000000000000000000015161475274123300246070ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; @Test public class A { // private FlexibleAssert m_assert = new FlexibleAssert(); private SoftAssert m_assert = new SoftAssert(); // private LoggingAssert m_assert = new LoggingAssert(); public void test1() { m_assert.assertTrue(true, "test1()"); } public void test2() { m_assert.assertTrue(true, "test2()"); } // @AfterClass // public void ac() { // System.out.println("Tests run in this class:" + m_assert.getMessages()); // } public void multiple() { m_assert.assertTrue(true, "Success 1"); m_assert.assertTrue(true, "Success 2"); m_assert.assertTrue(false, "Failure 1"); m_assert.assertTrue(true, "Success 3"); m_assert.assertTrue(false, "Failure 2"); m_assert.assertAll(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/AA.java000066400000000000000000000022341475274123300247060ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(singleThreaded = true) public class AA { private int m_n; public AA() {} public AA(int n) { m_n = n; } private void log(String s) { System.out.println(" [AA(" + m_n + ") thread:" + Thread.currentThread().getId() + "] " + s); } @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {42}, }; } // @BeforeClass // public void bc() { // log("beforeClass"); // } // // @AfterClass // public void ac() { // log("afterClass"); // } @Factory public Object[] create() { return new Object[] {new A(), new AA()}; } @Test public void aatest1() { log("aatest1"); } @Test(dependsOnMethods = "aatest1") public void aatest2() { log("aatest2"); } // @Test(priority = 3) public void atest3() {} public String getTestName() { return "This is test A"; } // @Test(groups = "mytest", dependsOnMethods = "g") // public void f() { // } // // // @AfterMethod // public void after() { // } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/AFactory.java000066400000000000000000000002561475274123300261370ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.Factory; public class AFactory { @Factory public Object[] create() { return new Object[] {new A(), new AA()}; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/AnnotationTransformer.java000066400000000000000000000024071475274123300307640ustar00rootroot00000000000000package test.tmp; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.annotations.ITestAnnotation; public class AnnotationTransformer implements IAnnotationTransformer, ITestListener { @Override public void transform( ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {} @Override public void onFinish(ITestContext context) { // TODO Auto-generated method stub } @Override public void onStart(ITestContext context) { // TODO Auto-generated method stub } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { // TODO Auto-generated method stub } @Override public void onTestFailure(ITestResult result) { // TODO Auto-generated method stub } @Override public void onTestSkipped(ITestResult result) { // TODO Auto-generated method stub } @Override public void onTestStart(ITestResult result) { // TODO Auto-generated method stub } @Override public void onTestSuccess(ITestResult result) { // TODO Auto-generated method stub } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/AssertEqualsTest.java000066400000000000000000000026101475274123300276770ustar00rootroot00000000000000package test.tmp; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Random; import java.util.Set; import org.testng.Assert; import org.testng.annotations.Test; public class AssertEqualsTest { private void log(String s) { System.out.println("[" + Thread.currentThread().getId() + "] " + s); } @Test(threadPoolSize = 3, invocationCount = 6) public void f1() { log("start"); try { int sleepTime = new Random().nextInt(500); Thread.sleep(sleepTime); } catch (Exception e) { log(" *** INTERRUPTED"); } log("end"); } @Test(threadPoolSize = 10, invocationCount = 10000) public void verifyMethodIsThreadSafe() { // foo(); } @Test(dependsOnMethods = "verifyMethodIsThreadSafe") public void verify() { // make sure that nothing was broken } public static void main(String[] args) { Set set1 = new LinkedHashSet(); Set set2 = new HashSet(); set1.add(5); set2.add(5); set1.add(6); set2.add(6); set1.add(1); set2.add(1); set1.add(9); set2.add(9); System.out.println("set1 is:" + set1.toString()); System.out.println("set2 is:" + set2.toString()); System.out.println("is set1 equals set2 :" + set1.equals(set2)); try { Assert.assertEquals(set1, set2, "set1 must equals with set2"); } catch (Exception ex) { ex.printStackTrace(); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/B.java000066400000000000000000000004771475274123300246150ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class B extends C { public static final String G = "group"; @BeforeMethod public void bm() { System.out.println("B.bm"); } @Test public void btest1() { System.out.println("B.btest1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/BListener.java000066400000000000000000000007271475274123300263210ustar00rootroot00000000000000package test.tmp; import org.testng.ITestResult; import org.testng.TestListenerAdapter; public class BListener extends TestListenerAdapter { public BListener() { System.out.println("BListener created"); } @Override public void onTestSuccess(ITestResult tr) { System.out.println("Success"); super.onTestSuccess(tr); } @Override public void onTestFailure(ITestResult tr) { System.out.println("Failure"); super.onTestFailure(tr); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Base.java000066400000000000000000000003021475274123300252710ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeMethod; public class Base { @BeforeMethod public void bm() { System.out.println("Thread" + Thread.currentThread().getId()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/BeforeGroupTest.java000066400000000000000000000010621475274123300275020ustar00rootroot00000000000000package test.tmp; import org.testng.ITestContext; import org.testng.annotations.BeforeGroups; public class BeforeGroupTest { // Logger l = LoggerFactory.getLogger(this.getClass()); @BeforeGroups( groups = {"NewUser"}, value = {"NewUser"}) public void preNewUser(ITestContext itc) { System.out.println("BEFOREGROUPS perfroming pre groups init"); // m_inj = Guice.createInjector(new JUnitModule(), new RequestModule(), // new GenericModule(), new SecurityModule()); // itc.setAttribute("injector", m_inj); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/C.java000066400000000000000000000007671475274123300246200ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class C { @BeforeMethod public void cm() { // System.out.println("C.cm"); } @Test(dataProvider = "data") public void c(String s) { System.out.println("c(" + s + ")"); } @DataProvider(name = "data") public static Object[][] data() { return new Object[][] { new Object[] {"Foo"}, new Object[] {"Bar"}, }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/ChildTest.java000066400000000000000000000004711475274123300263110ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ChildTest extends ParentTest { @BeforeMethod public void btm2() {} @AfterMethod public void atm2() {} @Override @Test public void t1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/ConcreteTest.java000066400000000000000000000004741475274123300270330ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class ConcreteTest extends Fixturable { @BeforeTest @AfterGroups("fixture") public void beforeFixture() {} @Test(groups = "fixture") public void test() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/DataDrivenTest.java000066400000000000000000000020061475274123300273030ustar00rootroot00000000000000package test.tmp; 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.List; import java.util.Properties; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataDrivenTest { @DataProvider(name = "provider") public Object[][] createData() throws FileNotFoundException, IOException { Properties p = new Properties(); List vResult = new ArrayList<>(); p.load(new FileInputStream(new File("c:/t/data.properties"))); for (Enumeration e = p.keys(); e.hasMoreElements(); ) { vResult.add(e.nextElement()); } Object[][] result = new Object[vResult.size()][1]; for (int i = 0; i < result.length; i++) { result[i] = new Object[] {vResult.get(i)}; } return result; } @Test(dataProvider = "provider") public void foo(int n) { Assert.assertTrue(n > 0); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/ExponentTest.java000066400000000000000000000021221475274123300270610ustar00rootroot00000000000000package test.tmp; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.log4testng.Logger; @Test(suiteName = "Exponent suite", testName = "Exponent test") public class ExponentTest { @DataProvider(name = "random") public Object[][] generateRandomExps() { // This array should be generated with random numbers return new Object[][] { new Object[] {0.0, Math.exp(0)}, new Object[] {1.0, Math.exp(1)}, new Object[] {2.0, Math.exp(2)}, }; } @BeforeMethod public void setUp() { debug("BEFORE METHOD"); } @Test(dataProvider = "random") public void testExponent(double exponent, double expected) { debug("COMPARING " + myExpFunction(exponent) + " AND " + expected); assertEquals(myExpFunction(exponent), expected); } private void debug(String s) { Logger.getLogger(ExponentTest.class).info("[ExponentTest] " + s); } private double myExpFunction(double exponent) { return Math.exp(exponent); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Fixturable.java000066400000000000000000000002341475274123300265300ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeTest; public class Fixturable { @BeforeTest(groups = "fixture") public void setupFixture() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/IgnoreUntil.java000066400000000000000000000006671475274123300266740ustar00rootroot00000000000000package test.tmp; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD, TYPE, CONSTRUCTOR}) public @interface IgnoreUntil { /** Format: hhmm */ public String time(); } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/ParamTest.java000066400000000000000000000007271475274123300263320ustar00rootroot00000000000000package test.tmp; import org.testng.Reporter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ParamTest { @Test(dataProvider = "dp") public void f(String s, int n) { // if ("Alois".equals(s)) assert false; Reporter.log("CALL " + n); } @DataProvider(name = "dp") public Object[][] create() { return new Object[][] { new Object[] {"Cedric", 36}, new Object[] {"Alois", 35}, }; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/ParentTest.java000066400000000000000000000004331475274123300265150ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ParentTest { @BeforeMethod public void btm1() {} @AfterMethod public void atm1() {} @Test public void t1() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/RegisterCommandTest.java000066400000000000000000000011371475274123300303510ustar00rootroot00000000000000package test.tmp; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = {"NewUser"}) public class RegisterCommandTest { // Logger l = LoggerFactory.getLogger(this.getClass()); @BeforeClass public void beforeClass(ITestContext itc) { System.out.println("BEFORECLASS getting injector from context"); // m_inj = (Injector) itc.getAttribute("injector"); // m_inj.injectMembers(this); } public void testExecute(ITestContext itc) throws Exception { System.out.println("TESTEXECUTE do somthing"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/RetryAnalyzer.java000066400000000000000000000004001475274123300272310ustar00rootroot00000000000000package test.tmp; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryAnalyzer implements IRetryAnalyzer { @Override public boolean retry(ITestResult result) { System.out.println("retry()"); return true; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/StaticInitializerTest.java000066400000000000000000000004301475274123300307140ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.Test; @Test public class StaticInitializerTest { static { foo(); } public void testMe() { System.err.println("**** testMe ****"); } private static void foo() { throw new RuntimeException("FAILING"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Sub.java000066400000000000000000000012511475274123300251540ustar00rootroot00000000000000package test.tmp; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = {"sub"}) public class Sub extends Base { boolean m_beforeTest; boolean m_afterTest; @BeforeClass public void subSetup() { System.out.println("sub before class"); } @AfterClass public void subTeardown() { System.out.println("sub after class"); } public void subTest() { System.out.println("sub test"); } @AfterSuite public void verify() { Assert.assertTrue(m_beforeTest); Assert.assertTrue(m_afterTest); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Test0.java000066400000000000000000000006321475274123300254240ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class Test0 { @BeforeTest public void setup() { System.out.println("setup"); } @Test(groups = {"G0"}) public void test() { System.out.println("Test0.test"); } @AfterTest public void tearDown() { System.out.println("tearDown"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Test1.java000066400000000000000000000002611475274123300254230ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.Test; @Test(dependsOnGroups = {"G0"}) public class Test1 { public void test() { System.out.println("Test1.test"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/TestA.java000066400000000000000000000017221475274123300254460ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestA { @BeforeClass public void insertA() { // Inserts an entity 'A'. This is an expensive operation. // After this, the entity 'A' is the first row on the table. } @Test public void testGetA() { // Checks that 'A' is the first row on the table, and loads it. } @Test(dependsOnMethods = "testGetA") public void testViewA_Details1() { // Loads the first row (assumed A) and checks some details } @Test(dependsOnMethods = "testGetA") public void testViewA_Details2() { // Loads the first row (assumed A) and checks some details } @Test(dependsOnMethods = "testGetA") public void testViewA_Details3() { // Loads the first row (assumed A) and checks some details } @Test(dependsOnMethods = "testGetA") public void testViewA_Details4() { // Loads the first row (assumed A) and checks some details } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/TestB.java000066400000000000000000000016201475274123300254440ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestB { @BeforeClass public void insertB() { // Inserts an entity 'B'. This is an expensive operation. // After this, the entity 'B' is the first row on the table. } @Test public void testGetB() { // Checks that 'B' is the first row on the table, and loads it. } @Test(dependsOnMethods = "testGetB") public void testViewB_Details1() { // Loads the first row (assumed B) and checks some details } @Test(dependsOnMethods = "testGetB") public void testViewB_Details2() { // Loads the first row (assumed B) and checks some details } @Test(dependsOnMethods = "testGetB") public void testViewB_Details3() { // Loads the first row (assumed B) and checks some details } @Test(dependsOnMethods = "testGetB") public void testViewB_Details4() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/TestCaseFactory.java000066400000000000000000000005361475274123300274730ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class TestCaseFactory { class MyTestClass { @Test public void testAll() {} } @Factory public Object[] createTestCases() { Object[] testCases = new Object[1]; testCases[0] = new MyTestClass() {}; return testCases; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/TestFixture.java000066400000000000000000000011431475274123300267110ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.BeforeTest; public class TestFixture { public static int globalCallSequence = 0; public static int printGlobalCallSequence(String methodName) { globalCallSequence++; System.err.println("*** " + methodName + ": globalCallSequence=" + globalCallSequence); return globalCallSequence; } public int fixtureBeforeTestCallSequence; @BeforeTest(groups = "fixture") public void beforeTest() { fixtureBeforeTestCallSequence = printGlobalCallSequence("TestFixture.beforeTest"); } public int getSomeRandomValue() { return 20; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/TestNGBug.java000066400000000000000000000006461475274123300262340ustar00rootroot00000000000000package test.tmp; import org.testng.Reporter; import org.testng.annotations.Test; public class TestNGBug { // @Configuration(beforeTestMethod = true) public void init() {} @Test public void test1() { Reporter.log("Child.test1"); } @Test(enabled = false) public void test2() { Reporter.log("Child.test2"); } @Test(groups = "a") public void test3() { Reporter.log("Child.test3"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Test_TestListenerAppender.java000066400000000000000000000007501475274123300315310ustar00rootroot00000000000000package test.tmp; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Test_TestListenerAppender { @DataProvider(name = "test1") public Object[][] createData1() { // throw new RuntimeException("Intentionally thrown exception"); return new Object[][] { {"Cedric", 36}, {"Anne", 37}, }; } @Test(dataProvider = "test1") public void verifyData1(String n1, Integer n2) { System.out.println(n1 + " " + n2); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/TimeBombTest.java000066400000000000000000000017231475274123300267650ustar00rootroot00000000000000package test.tmp; import java.lang.reflect.Method; import java.util.Calendar; import org.testng.annotations.Test; import org.testng.log4testng.Logger; public class TimeBombTest { @IgnoreUntil(time = "1022") @Test public void timeBomb() throws SecurityException, NoSuchMethodException { Method m = TimeBombTest.class.getMethod("timeBomb"); IgnoreUntil t = m.getAnnotation(IgnoreUntil.class); long now = Calendar.getInstance().getTimeInMillis(); long l = parseTime(t.time()); debug("IGNORE:" + (now < l)); } private long parseTime(String string) { int hour = Integer.parseInt(string.substring(0, 2)); int minute = Integer.parseInt(string.substring(2)); Calendar result = Calendar.getInstance(); result.set(Calendar.HOUR_OF_DAY, hour); result.set(Calendar.MINUTE, minute); return result.getTimeInMillis(); } private void debug(String string) { Logger.getLogger(getClass()).debug("[TimeBombTest] " + string); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Tmp.java000066400000000000000000000011751475274123300251700ustar00rootroot00000000000000package test.tmp; import java.util.Random; import org.testng.annotations.Test; import org.testng.log4testng.Logger; public class Tmp { @Test(invocationCount = 10, threadPoolSize = 5) public void f() { debug("START " + Thread.currentThread().getId()); try { Random r = new Random(); Thread.sleep(Math.abs(r.nextInt() % 300)); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); handled.printStackTrace(); } debug("END " + Thread.currentThread().getId()); } private void debug(String string) { Logger.getLogger(getClass()).info("[Tmp] " + string); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/Tn.java000066400000000000000000000007651475274123300250150ustar00rootroot00000000000000package test.tmp; import org.testng.Reporter; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class Tn { @Test(groups = {"g1"}) public void m1() { System.out.println("1"); } @Test( groups = {"g1"}, dependsOnMethods = "m1") public void m2() { System.out.println("2"); } @Parameters(value = "param") @Test(groups = {"g2"}) public void m3(String param) { System.out.println("3"); Reporter.log("M3 WAS CALLED"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/b/000077500000000000000000000000001475274123300240025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/b/TmpB.java000066400000000000000000000002251475274123300255060ustar00rootroot00000000000000package test.tmp.b; import org.testng.annotations.Test; public class TmpB { @Test public void tmpb1() { System.out.println("tmpb1"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/p1/000077500000000000000000000000001475274123300241015ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/p1/ContainerTest.java000066400000000000000000000005161475274123300275300ustar00rootroot00000000000000package test.tmp.p1; import static org.testng.AssertJUnit.assertNotNull; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public class ContainerTest { @BeforeSuite public void startup() { assertNotNull(null); } @AfterSuite public void shutdown() { assertNotNull(null); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/p2/000077500000000000000000000000001475274123300241025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/p2/ServiceTest.java000066400000000000000000000003411475274123300272030ustar00rootroot00000000000000package test.tmp.p2; import static org.testng.AssertJUnit.assertNotNull; import org.testng.annotations.Test; public class ServiceTest { @Test(groups = {"group1"}) public void service() { assertNotNull(null); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/verify/000077500000000000000000000000001475274123300250655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/verify/Verify.java000066400000000000000000000003541475274123300271760ustar00rootroot00000000000000package test.tmp.verify; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target(java.lang.annotation.ElementType.METHOD) public @interface Verify {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/verify/VerifyInterceptor.java000066400000000000000000000043761475274123300314250ustar00rootroot00000000000000package test.tmp.verify; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.TestNGUtils; import org.testng.collections.Maps; public class VerifyInterceptor implements IMethodInterceptor { /** * @return the list of methods received in parameters with all methods annotated with @Verify * inserted after each of these test methods. *

This happens in two steps: - Find all the methods annotated with @Verify in the classes * that contain test methods - Insert these verify methods after each method passed in * parameter These @Verify methods are stored in a map keyed by the class in order to avoid * looking them up more than once on the same class. */ @Override public List intercept(List methods, ITestContext context) { List result = new ArrayList<>(); Map, List> verifyMethods = Maps.newHashMap(); for (IMethodInstance mi : methods) { ITestNGMethod tm = mi.getMethod(); List verify = verifyMethods.get(tm.getRealClass()); if (verify == null) { verify = findVerifyMethods(tm.getRealClass(), tm); } result.add(mi); result.addAll(verify); } return result; } /** @return all the @Verify methods found on @code{realClass} */ private List findVerifyMethods(Class realClass, final ITestNGMethod tm) { List result = new ArrayList<>(); for (final Method m : realClass.getDeclaredMethods()) { Annotation a = m.getAnnotation(Verify.class); if (a != null) { final ITestNGMethod vm = TestNGUtils.createITestNGMethod(tm, m); result.add( new IMethodInstance() { @Override public ITestNGMethod getMethod() { return vm; } @Override public Object getInstance() { return tm.getInstance(); } }); } } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/tmp/verify/VerifyTest.java000066400000000000000000000005311475274123300300330ustar00rootroot00000000000000package test.tmp.verify; import org.testng.annotations.Test; public class VerifyTest { @Test public void f2() { System.out.println("f2()"); } @Test public void f1() { System.out.println("f1()"); } @Verify public void verify() { // throw new RuntimeException(); // System.out.println("verify()"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/triangle/000077500000000000000000000000001475274123300245665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/triangle/Base.java000066400000000000000000000007731475274123300263120ustar00rootroot00000000000000package test.triangle; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; /** * This class * * @author cbeust */ public class Base { protected boolean m_isInitialized = false; @BeforeSuite public void beforeSuite() { CountCalls.numCalls = 0; } @BeforeClass public void initBeforeTestClass() { m_isInitialized = true; } @AfterClass public void postAfterTestClass() { CountCalls.incr(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/triangle/CheckCount.java000066400000000000000000000007521475274123300274630ustar00rootroot00000000000000package test.triangle; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * this test checks the CountCalls's static counter to see if we got the expected number of calls */ public class CheckCount { @Parameters({"expected-calls"}) @Test public void testCheckCount(String expectedCalls) { int i = Integer.valueOf(expectedCalls); int numCalls = CountCalls.getNumCalls(); Assert.assertEquals(numCalls, i); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/triangle/Child1.java000066400000000000000000000006251475274123300265400ustar00rootroot00000000000000package test.triangle; import org.testng.annotations.Test; /** * This class * * @author cbeust */ public class Child1 extends Base { @Test public void child1() { assert m_isInitialized : "Wasn't initialized correctly " + hashCode() + " " + getClass(); } @Test public void child1a() { assert m_isInitialized : "Wasn't initialized correctly " + hashCode() + " " + getClass(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/triangle/Child2.java000066400000000000000000000003601475274123300265350ustar00rootroot00000000000000package test.triangle; import org.testng.annotations.Test; /** * This class * * @author cbeust */ public class Child2 extends Base { @Test public void child2() { assert m_isInitialized : "Wasn't initialized correctly"; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/triangle/CountCalls.java000066400000000000000000000004631475274123300275030ustar00rootroot00000000000000package test.triangle; /** * count the number of times something is called used to check whether certain methods have been * called */ public class CountCalls { static int numCalls = 0; public static void incr() { numCalls++; } public static int getNumCalls() { return numCalls; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/000077500000000000000000000000001475274123300253415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/BaseAfter.java000066400000000000000000000005021475274123300300350ustar00rootroot00000000000000package test.uniquesuite; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public class BaseAfter { public static int m_afterCount = 0; @BeforeSuite public void beforeSuite() { m_afterCount = 0; } @AfterSuite public void incrementAfter() { m_afterCount++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/BaseBefore.java000066400000000000000000000005551475274123300302060ustar00rootroot00000000000000package test.uniquesuite; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public class BaseBefore { public static int m_beforeCount = 0; public static int m_afterCount = 0; @BeforeSuite public void incrementBefore() { m_beforeCount++; } @AfterSuite public void incrementAfter() { m_afterCount++; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/TestAfter.java000066400000000000000000000012241475274123300301040ustar00rootroot00000000000000package test.uniquesuite; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; import testhelper.OutputDirectoryPatch; public class TestAfter { @Test public void testAfter() { TestNG tng = new TestNG(); tng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory()); tng.setTestClasses(new Class[] {TestAfter1.class, TestAfter2.class}); tng.run(); Assert.assertEquals(BaseAfter.m_afterCount, 1); } @AfterTest public void afterTest() { BaseAfter.m_afterCount = 0; BaseBefore.m_beforeCount = 0; BaseBefore.m_afterCount = 0; } } ///// jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/TestAfter1.java000066400000000000000000000002211475274123300301610ustar00rootroot00000000000000package test.uniquesuite; import org.testng.annotations.Test; public class TestAfter1 extends BaseAfter { @Test public void verify() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/TestAfter2.java000066400000000000000000000002211475274123300301620ustar00rootroot00000000000000package test.uniquesuite; import org.testng.annotations.Test; public class TestAfter2 extends BaseAfter { @Test public void verify() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/TestBefore1.java000066400000000000000000000003331475274123300303260ustar00rootroot00000000000000package test.uniquesuite; import org.testng.Assert; import org.testng.annotations.Test; public class TestBefore1 extends BaseBefore { @Test public void verify() { Assert.assertEquals(m_beforeCount, 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/uniquesuite/TestBefore2.java000066400000000000000000000003331475274123300303270ustar00rootroot00000000000000package test.uniquesuite; import org.testng.Assert; import org.testng.annotations.Test; public class TestBefore2 extends BaseBefore { @Test public void verify() { Assert.assertEquals(m_beforeCount, 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/v6/000077500000000000000000000000001475274123300233145ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/v6/A.java000066400000000000000000000016541475274123300243450ustar00rootroot00000000000000package test.v6; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class A { @Test(dependsOnMethods = "fa1") public void fa2() {} @Test(groups = "1") public void fa1() {} @Test public void fa3() {} @BeforeGroups("1") public void beforeGroups() {} @AfterGroups("1") public void afterGroups() {} @BeforeMethod public void beforeMethod() {} @AfterMethod public void afterMethod() {} @BeforeSuite public void beforeSuite() {} @AfterSuite public void afterSuite() {} @BeforeClass public void beforeClass() {} @AfterClass public void afterClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/v6/B.java000066400000000000000000000012421475274123300243370ustar00rootroot00000000000000package test.v6; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class B { @Test(dependsOnMethods = "fb1") public void fb2() {} @Test(groups = "1") public void fb1() {} @Test public void fb3() {} @BeforeMethod public void beforeMethod() {} @AfterMethod(groups = "1") public void afterMethod() {} @BeforeSuite public void beforeSuite() {} @BeforeClass public void beforeClass() {} @AfterClass public void afterClass() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/v6/C.java000066400000000000000000000007061475274123300243440ustar00rootroot00000000000000package test.v6; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class C { @BeforeTest public void beforeTest() {} @AfterTest public void afterTest() {} @Test public void fc1() {} @BeforeSuite public void beforeSuite() {} @AfterSuite public void afterSuite() {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/000077500000000000000000000000001475274123300242655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/Verifier.java000066400000000000000000000004761475274123300267120ustar00rootroot00000000000000package test.verify; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD, TYPE}) public @interface Verifier {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/Verify.java000066400000000000000000000004741475274123300264010ustar00rootroot00000000000000package test.verify; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD, TYPE}) public @interface Verify {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/Verify2SampleTest.java000066400000000000000000000020131475274123300304540ustar00rootroot00000000000000package test.verify; import org.testng.ITestNGListener; import org.testng.ITestNGListenerFactory; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Illustrate the implementation of a @Verify/@Verifier test. * *

One method should be annotated with @Verifier and then each test method annotated with @Verify * will be followed with a call to the @Verifier method. */ @Listeners(VerifyTestListener.class) public class Verify2SampleTest implements ITestNGListenerFactory { public Verify2SampleTest() {} @Verify @Test public void f1() { log("f1"); } @Verify @Test public void f2() { log("f2"); } @Verifier @Test public void verify() { log("Verifying"); } private void log(String string) { if (false) { System.out.println(hashCode() + " " + string); } } @Override public ITestNGListener createListener(Class listenerClass) { log("Creating a listener of type " + listenerClass); return null; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/Verify3Base.java000066400000000000000000000002011475274123300272430ustar00rootroot00000000000000package test.verify; import org.testng.annotations.Listeners; @Listeners(VerifyTestListener.class) public class Verify3Base {} jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/Verify3SampleTest.java000066400000000000000000000004151475274123300304610ustar00rootroot00000000000000package test.verify; import org.testng.annotations.BeforeClass; /** Make sure that @Listeners annotations can come from superclasses */ public class Verify3SampleTest extends Verify3Base { @BeforeClass public void bc() { VerifyTestListener.m_count = 0; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/VerifyMethodInterceptor.java000066400000000000000000000023331475274123300317550ustar00rootroot00000000000000package test.verify; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.collections.Lists; public class VerifyMethodInterceptor implements IMethodInterceptor { @Override public List intercept(List methods, ITestContext context) { List result = Lists.newArrayList(); IMethodInstance verifier = null; // Doing a naive approach here: we run through the list of methods // twice, once to find the verifier and once more to actually create // the result. Obviously, this can be done with just one loop for (IMethodInstance m : methods) { if (m.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Verifier.class) != null) { verifier = m; break; } } // Create the result with each @Verify method followed by a call // to the @Verifier method for (IMethodInstance m : methods) { if (m != verifier) { result.add(m); } if (m.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Verify.class) != null) { result.add(verifier); } } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/VerifyNoListenersSampleTest.java000066400000000000000000000007251475274123300325700ustar00rootroot00000000000000package test.verify; import org.testng.annotations.Test; /** Same class as VerifySampleTest but without the @Listeners annotation. */ public class VerifyNoListenersSampleTest { @Verify @Test public void f1() { log("f1"); } @Verify @Test public void f2() { log("f2"); } @Verifier @Test public void verify() { log("Verifying"); } private void log(String string) { if (false) { System.out.println(string); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/VerifySampleTest.java000066400000000000000000000012671475274123300304040ustar00rootroot00000000000000package test.verify; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Illustrate the implementation of a @Verify/@Verifier test. * *

One method should be annotated with @Verifier and then each test method annotated with @Verify * will be followed with a call to the @Verifier method. */ @Listeners(VerifyMethodInterceptor.class) public class VerifySampleTest { @Verify @Test public void f1() { log("f1"); } @Verify @Test public void f2() { log("f2"); } @Verifier @Test public void verify() { log("Verifying"); } private void log(String string) { if (false) { System.out.println(string); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/VerifyTest.java000066400000000000000000000022021475274123300272300ustar00rootroot00000000000000package test.verify; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; public class VerifyTest extends SimpleBaseTest { private void runTest(Class cls, int expected) { TestNG tng = create(cls); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), expected); } @Test public void verifyWithAnnotation() { runTest(VerifySampleTest.class, 4); } @Test public void verifyWithoutAnnotation() { runTest(VerifyNoListenersSampleTest.class, 3); } @Test public void verifyTestListener() { TestNG tng = create(Verify2SampleTest.class); VerifyTestListener.m_count = 0; tng.run(); Assert.assertEquals(VerifyTestListener.m_count, 1); } @Test public void verifyBaseClassTestListener() { TestNG tng = create(Verify3SampleTest.class); VerifyTestListener.m_count = 0; tng.run(); Assert.assertEquals(VerifyTestListener.m_count, 1); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/verify/VerifyTestListener.java000066400000000000000000000012671475274123300307500ustar00rootroot00000000000000package test.verify; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class VerifyTestListener implements ITestListener { public static int m_count = 0; @Override public void onFinish(ITestContext context) {} @Override public void onStart(ITestContext context) { m_count++; } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onTestFailure(ITestResult result) {} @Override public void onTestSkipped(ITestResult result) {} @Override public void onTestStart(ITestResult result) {} @Override public void onTestSuccess(ITestResult result) {} } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/xml/000077500000000000000000000000001475274123300235615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/xml/TestNGContentHandlerTest.java000066400000000000000000000017361475274123300312700ustar00rootroot00000000000000package test.xml; import java.io.FileInputStream; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.xml.SuiteXmlParser; import org.testng.xml.TestNGContentHandler; import org.testng.xml.XmlInclude; import test.SimpleBaseTest; public class TestNGContentHandlerTest extends SimpleBaseTest { @Test public void testDescriptionInclusion() throws Exception { final String xml = getPathToResource("xml/simple-suite-with-method-desc.xml"); SuiteXmlParser parser = new SuiteXmlParser(); TestNGContentHandler handler = new TestNGContentHandler(xml, false); parser.parse(new FileInputStream(xml), handler); List includes = handler.getSuite().getTests().get(0).getXmlClasses().get(0).getIncludedMethods(); String desc = includes.get(0).getDescription(); Assert.assertEquals("simple-description", desc); } public static class LocalTestClass { @Test public void helloWorld() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/xml/XMLStringBufferTest.java000066400000000000000000000020531475274123300302450ustar00rootroot00000000000000package test.xml; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.reporters.XMLStringBuffer.EOL; import java.util.Properties; import org.testng.annotations.Test; import org.testng.reporters.Buffer; import org.testng.reporters.IBuffer; import org.testng.reporters.XMLStringBuffer; public class XMLStringBufferTest { @Test public void testMethod() { IBuffer result = Buffer.create(); XMLStringBuffer sb = new XMLStringBuffer(result, ""); sb.push("family"); Properties p = new Properties(); p.setProperty("prop1", "value1"); p.setProperty("prop2", "value2"); sb.addRequired("cedric", "true", p); sb.addRequired("alois", "true"); sb.addOptional("anne-marie", (String) null); sb.pop(); String expected = "" + EOL + " true" + EOL + " true" + EOL + ""; assertThat(result.toString().trim()).isEqualTo(expected); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/xml/XmlVerifyTest.java000066400000000000000000000067071475274123300272230ustar00rootroot00000000000000package test.xml; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.Collections; import org.testng.Assert; import org.testng.ITestNGListener; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.TestNGException; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import test.SimpleBaseTest; public class XmlVerifyTest extends SimpleBaseTest { static { System.setProperty("testng.testmode", "true"); } private static final String COMMAND_LINE_TEST = ""; private static final String DEFAULT_SUITE = ""; @Test(description = "github-1455") public void testToXmlWithComments() { XmlSuite suite = createSuite(); String xml = suite.toXml(); assertThat(xml).contains(COMMAND_LINE_TEST); assertThat(xml).contains(DEFAULT_SUITE); } @Test(description = "github-1455", dependsOnMethods = "testToXmlWithComments") public void testToXmlWithoutComments() { System.setProperty("testng.xml.weaver", "org.testng.xml.CommentDisabledXmlWeaver"); XmlSuite suite = createSuite(); String xml = suite.toXml(); assertThat(xml).doesNotContain(COMMAND_LINE_TEST); assertThat(xml).doesNotContain(DEFAULT_SUITE); } @AfterMethod public void reset(Method method) { if (method.getName().equals("testToXmlWithoutComments")) { System.setProperty("testng.xml.weaver", "org.testng.xml.DefaultXmlWeaver"); } } private static XmlSuite createSuite() { XmlSuite suite = new XmlSuite(); XmlTest test = new XmlTest(suite); test.setName("command_line_test"); XmlClass xClass = new XmlClass(XmlVerifyTest.class); test.getXmlClasses().add(xClass); test.addExcludedGroup("fast"); return suite; } @Test( description = "Ensure that TestNG stops without running any tests if some class" + " included in suite is missing") public void handleInvalidSuites() { TestListenerAdapter tla = new TestListenerAdapter(); try { TestNG tng = create(); String testngXmlPath = getPathToResource("suite1.xml"); tng.setTestSuites(Collections.singletonList(testngXmlPath)); tng.addListener((ITestNGListener) tla); tng.run(); } catch (TestNGException ex) { Assert.assertEquals(tla.getPassedTests().size(), 0); } } @Test public void preserverOrderAttribute() { XmlSuite suite = new XmlSuite(); XmlTest test = new XmlTest(suite); suite.setPreserveOrder(true); test.setPreserveOrder(false); Assert.assertFalse(test.getPreserveOrder()); suite.setPreserveOrder(false); test.setPreserveOrder(true); Assert.assertTrue(test.getPreserveOrder()); suite.setPreserveOrder((Boolean) null); test.setPreserveOrder(false); Assert.assertFalse(test.getPreserveOrder()); suite.setPreserveOrder(false); test.setPreserveOrder((Boolean) null); Assert.assertFalse(test.getPreserveOrder()); suite.setPreserveOrder((Boolean) null); test.setPreserveOrder(true); Assert.assertTrue(test.getPreserveOrder()); suite.setPreserveOrder(true); test.setPreserveOrder((Boolean) null); Assert.assertTrue(test.getPreserveOrder()); suite.setPreserveOrder((Boolean) null); test.setPreserveOrder((Boolean) null); Assert.assertNull(test.getPreserveOrder()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/xml/issue2231/000077500000000000000000000000001475274123300252215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/xml/issue2231/IssueTest.java000066400000000000000000000027601475274123300300210ustar00rootroot00000000000000package test.xml.issue2231; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.TestListenerAdapter; import org.testng.annotations.Test; import org.testng.xml.XmlClass; import org.testng.xml.XmlSuite; import org.testng.xml.XmlSuite.ParallelMode; import org.testng.xml.XmlTest; import org.testng.xml.internal.Parser; public class IssueTest { @Test(description = "GITHUB-2231") public void ensureSuiteGenerationAdheresToDTD() throws IOException { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("CustomSuiteFile"); xmlSuite.setParallel(ParallelMode.TESTS); xmlSuite.setThreadCount(1); List group = Arrays.asList("Regression", "Smoke"); xmlSuite.setIncludedGroups(group); xmlSuite.addListener(TestListenerAdapter.class.getName()); Map parameters = new HashMap<>(); parameters.put("reportPath", "somePath"); xmlSuite.setParameters(parameters); XmlTest xmlTest = new XmlTest(xmlSuite); xmlTest.setName("Chrome"); xmlTest.setXmlClasses(Collections.singletonList(new XmlClass(ExampleTestCase.class.getName()))); File file = File.createTempFile("sample", ".xml"); Files.write(file.toPath(), xmlSuite.toXml().getBytes()); new Parser(file.getAbsolutePath()).parse(); } public static class ExampleTestCase { @Test public void testMethod() {} } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/yaml/000077500000000000000000000000001475274123300237235ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test/yaml/YamlTest.java000066400000000000000000000070221475274123300263310ustar00rootroot00000000000000package test.yaml; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.internal.Yaml; import org.testng.internal.YamlParser; import org.testng.reporters.Files; import org.testng.xml.SuiteXmlParser; import org.testng.xml.XmlSuite; import org.testng.xml.internal.Parser; import test.SimpleBaseTest; public class YamlTest extends SimpleBaseTest { public static final String CLASS_NOT_FOUND_MESSAGE = "Cannot find class in classpath"; @DataProvider public Object[][] dp() { return new Object[][] { new Object[] {"a1"}, new Object[] {"a2"}, new Object[] {"a3"}, new Object[] {"a4"}, }; } @Test(dataProvider = "dp") public void compareFiles(String name) throws IOException { Collection s1 = new Parser(getPathToResource("yaml" + File.separator + name + ".yaml")).parse(); Collection s2 = new Parser(getPathToResource("yaml" + File.separator + name + ".xml")).parse(); Assert.assertEquals(s1, s2); } @Test(description = "GITHUB-1787") public void testParameterInclusion() throws IOException { SuiteXmlParser parser = new SuiteXmlParser(); String file = "src/test/resources/yaml/1787.xml"; XmlSuite xmlSuite = parser.parse(file, new FileInputStream(file), false); StringBuilder yaml = org.testng.internal.Yaml.toYaml(xmlSuite); Matcher m = Pattern.compile("parameters:").matcher(yaml.toString()); int count = 0; while (m.find()) { count++; } assertThat(count).isEqualTo(5); File newSuite = File.createTempFile("suite", ".xml"); newSuite.deleteOnExit(); Files.writeFile(yaml.toString(), newSuite); assertThat(parser.parse(newSuite.getAbsolutePath(), new FileInputStream(file), false)) .isEqualTo(xmlSuite); } @Test(description = "GITHUB-2078") public void testXmlDependencyGroups() throws IOException { String actualXmlFile = "src/test/resources/yaml/2078.xml"; XmlSuite actualXmlSuite = new SuiteXmlParser().parse(actualXmlFile, new FileInputStream(actualXmlFile), false); String expectedYamlFile = "src/test/resources/yaml/2078.yaml"; String expectedYaml = new String( java.nio.file.Files.readAllBytes(Paths.get(expectedYamlFile)), StandardCharsets.UTF_8); assertThat(Yaml.toYaml(actualXmlSuite).toString()).isEqualToNormalizingNewlines(expectedYaml); } @Test(description = "GITHUB-2689") public void testLoadClassesFlag() throws IOException { YamlParser yamlParser = new YamlParser(); String yamlSuiteFile = "src/test/resources/yaml/suiteWithNonExistentTest.yaml"; try { yamlParser.parse(yamlSuiteFile, new FileInputStream(yamlSuiteFile), false); } catch (Throwable throwable) { Throwable rootCause = getRootCause(throwable); String rootCauseMessage = rootCause.getMessage(); if (rootCauseMessage.contains(CLASS_NOT_FOUND_MESSAGE)) { throw new AssertionError("TestNG shouldn't attempt to load test class", throwable); } throw new AssertionError("Yaml parser failed to parse suite", throwable); } } private Throwable getRootCause(Throwable throwable) { return throwable.getCause() != null ? getRootCause(throwable.getCause()) : throwable; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/000077500000000000000000000000001475274123300243575ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/AfterListenerSample.java000066400000000000000000000024451475274123300311400ustar00rootroot00000000000000package test_result; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.Test; public class AfterListenerSample { @Test public void failedTest() {} @Test(expectedExceptions = IllegalStateException.class, enabled = false) public void failedTest2() { throw new IllegalStateException(); } @Test public void skippedTest() {} @Test public void succeedTest() { Assert.fail(); } @Test public void succeedTest2() { throw new IllegalStateException(); } public static class MySkipTestListener implements IInvokedMethodListener { @Override public void afterInvocation(IInvokedMethod method, ITestResult result) { switch (method.getTestMethod().getMethodName()) { case "failedTest": case "failedTest2": result.setStatus(ITestResult.FAILURE); break; case "skippedTest": result.setStatus(ITestResult.SKIP); break; case "succeedTest": case "succeedTest2": result.setStatus(ITestResult.SUCCESS); break; default: throw new RuntimeException( "Unknown method name: " + method.getTestMethod().getMethodName()); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/BeforeListenerSample.java000066400000000000000000000024321475274123300312750ustar00rootroot00000000000000package test_result; import org.testng.*; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(BeforeListenerSample.MySkipTestListener.class) public class BeforeListenerSample { @Test public void failedTest() {} @Test(expectedExceptions = IllegalStateException.class, enabled = false) public void failedTest2() { throw new IllegalStateException(); } @Test public void skippedTest() {} @Test public void succeedTest() { Assert.fail(); } @Test public void succeedTest2() { throw new IllegalStateException(); } public static class MySkipTestListener implements IInvokedMethodListener { @Override public void beforeInvocation(IInvokedMethod method, ITestResult result) { switch (method.getTestMethod().getMethodName()) { case "failedTest": case "failedTest2": result.setStatus(ITestResult.FAILURE); break; case "skippedTest": result.setStatus(ITestResult.SKIP); break; case "succeedTest": case "succeedTest2": result.setStatus(ITestResult.SUCCESS); break; default: throw new RuntimeException( "Unknown method name: " + method.getTestMethod().getMethodName()); } } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/GitHub1197Sample.java000066400000000000000000000015761475274123300301010ustar00rootroot00000000000000package test_result; import org.testng.Assert; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.annotations.Test; public class GitHub1197Sample { @Test public void failedTest() { Reporter.getCurrentTestResult().setStatus(ITestResult.FAILURE); } @Test(expectedExceptions = IllegalStateException.class, enabled = false) public void failedTest2() { Reporter.getCurrentTestResult().setStatus(ITestResult.FAILURE); throw new IllegalStateException(); } @Test public void skippedTest() { Reporter.getCurrentTestResult().setStatus(ITestResult.SKIP); } @Test public void succeedTest() { Reporter.getCurrentTestResult().setStatus(ITestResult.SUCCESS); Assert.fail(); } @Test public void succeedTest2() { Reporter.getCurrentTestResult().setStatus(ITestResult.SUCCESS); throw new IllegalStateException(); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/OrderAbidingListener.java000066400000000000000000000070001475274123300312560ustar00rootroot00000000000000package test_result; import java.util.Arrays; import java.util.List; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGListener; import org.testng.ITestResult; public class OrderAbidingListener implements IInvokedMethodListener, ITestListener { private final List listeners; public OrderAbidingListener(ITestNGListener... listeners) { this.listeners = Arrays.asList(listeners); } @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { listeners.stream() .filter(l -> l instanceof IInvokedMethodListener) .map(l -> (IInvokedMethodListener) l) .forEach(l -> l.beforeInvocation(method, testResult)); } @Override public void beforeInvocation( IInvokedMethod method, ITestResult testResult, ITestContext context) { listeners.stream() .filter(l -> l instanceof IInvokedMethodListener) .map(l -> (IInvokedMethodListener) l) .forEach(l -> l.beforeInvocation(method, testResult, context)); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { listeners.stream() .filter(l -> l instanceof IInvokedMethodListener) .map(l -> (IInvokedMethodListener) l) .forEach(l -> l.afterInvocation(method, testResult)); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) { listeners.stream() .filter(l -> l instanceof IInvokedMethodListener) .map(l -> (IInvokedMethodListener) l) .forEach(l -> l.afterInvocation(method, testResult, context)); } @Override public void onStart(ITestContext context) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onStart(context)); } @Override public void onTestStart(ITestResult result) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onTestStart(result)); } @Override public void onTestSuccess(ITestResult result) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onTestSuccess(result)); } @Override public void onTestFailure(ITestResult result) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onTestFailure(result)); } @Override public void onTestSkipped(ITestResult result) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onTestSkipped(result)); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onTestFailedButWithinSuccessPercentage(result)); } @Override public void onTestFailedWithTimeout(ITestResult result) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onTestFailedWithTimeout(result)); } @Override public void onFinish(ITestContext context) { listeners.stream() .filter(l -> l instanceof ITestListener) .map(l -> (ITestListener) l) .forEach(l -> l.onFinish(context)); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/ResultStatusTest.java000066400000000000000000000053451475274123300305530ustar00rootroot00000000000000package test_result; import static org.assertj.core.api.Assertions.assertThat; import org.testng.TestNG; import org.testng.annotations.Test; import test.InvokedMethodNameListener; import test.SimpleBaseTest; import test_result.AfterListenerSample.MySkipTestListener; public class ResultStatusTest extends SimpleBaseTest { @Test public void testGitHub1197() { TestNG tng = create(GitHub1197Sample.class); // A skipped method is not supposed to be run but, here, it's the goal of the feature InvokedMethodNameListener listener = new InvokedMethodNameListener(true, true); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("succeedTest", "succeedTest2"); assertThat(listener.getFailedBeforeInvocationMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).containsExactly("failedTest"); // , "failedTest2"); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSkippedAfterInvocationMethodNames()).containsExactly("skippedTest"); } @Test public void testBeforeListener() { TestNG tng = create(BeforeListenerSample.class); // A skipped method is not supposed to be run but, here, it's the goal of the feature InvokedMethodNameListener listener = new InvokedMethodNameListener(true, true); tng.addListener(listener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("succeedTest", "succeedTest2"); assertThat(listener.getFailedBeforeInvocationMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).containsExactly("failedTest"); // , "failedTest2"); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSkippedAfterInvocationMethodNames()).containsExactly("skippedTest"); } @Test public void testAfterListener() { TestNG tng = create(AfterListenerSample.class); AfterListenerSample.MySkipTestListener testCaseListener = new MySkipTestListener(); // A skipped method is not supposed to be run but, here, it's the goal of the feature InvokedMethodNameListener listener = new InvokedMethodNameListener(true, true); OrderAbidingListener orderAbidingListener = new OrderAbidingListener(testCaseListener, listener); tng.addListener(orderAbidingListener); tng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("succeedTest", "succeedTest2"); assertThat(listener.getFailedBeforeInvocationMethodNames()).isEmpty(); assertThat(listener.getFailedMethodNames()).containsExactly("failedTest"); // , "failedTest2"); assertThat(listener.getSkippedMethodNames()).isEmpty(); assertThat(listener.getSkippedAfterInvocationMethodNames()).containsExactly("skippedTest"); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/TestResultTest.java000066400000000000000000000024641475274123300302060ustar00rootroot00000000000000package test_result; import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import org.testng.ITestResult; import org.testng.TestNG; import org.testng.annotations.Test; import test.SimpleBaseTest; import test_result.issue1590.TestclassSample; import test_result.issue2535.CalculatorTestSample; import test_result.issue2535.CalculatorTestSample.LocalListener; public class TestResultTest extends SimpleBaseTest { @Test(description = "GITHUB-1590") public void ensureITestResultHasValidStatusAndTimestampWhenInvokingConfigurationMethod() { TestNG testng = create(TestclassSample.class); testng.run(); assertThat(TestclassSample.startTimestamp).isLessThanOrEqualTo(0); assertThat(TestclassSample.startStatus).isEqualTo(ITestResult.STARTED); assertThat(TestclassSample.endTimestamp).isGreaterThan(0); assertThat(TestclassSample.endStatus).isEqualTo(ITestResult.SUCCESS); } @Test(description = "GITHUB-2535") public void ensureITestResultHasValidTimestampWhenConfigurationMethodFails() { TestNG testng = create(CalculatorTestSample.class); testng.run(); Map results = LocalListener.results; ITestResult skippedConfig = results.get("setup1"); assertThat(skippedConfig.getEndMillis()).isEqualTo(skippedConfig.getStartMillis()); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/issue1590/000077500000000000000000000000001475274123300260265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/issue1590/TestclassSample.java000066400000000000000000000024741475274123300320070ustar00rootroot00000000000000package test_result.issue1590; import java.util.concurrent.TimeUnit; import org.testng.IInvokedMethod; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestclassSample { public static int startStatus; public static int endStatus; public static long startTimestamp; public static long endTimestamp; @BeforeClass public void beforeClass(ITestContext context) throws InterruptedException { TimeUnit.SECONDS.sleep(1); ITestResult result = findConfigurationMethod(context).getTestResult(); startStatus = result.getStatus(); startTimestamp = result.getEndMillis(); } @Test public void testMethod() {} @AfterClass public void afterClass(ITestContext context) { ITestResult result = findConfigurationMethod(context).getTestResult(); endTimestamp = result.getEndMillis(); endStatus = ITestResult.SUCCESS; } private static IInvokedMethod findConfigurationMethod(ITestContext context) { return context.getSuite().getAllInvokedMethods().stream() .filter( iInvokedMethod -> iInvokedMethod.getTestMethod().getMethodName().equals("beforeClass")) .findFirst() .orElseThrow(IllegalStateException::new); } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/issue2535/000077500000000000000000000000001475274123300260265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/test_result/issue2535/CalculatorTestSample.java000066400000000000000000000017401475274123300327660ustar00rootroot00000000000000package test_result.issue2535; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import test_result.issue2535.CalculatorTestSample.LocalListener; @Listeners(LocalListener.class) public class CalculatorTestSample { @Test public void calculatorUiTest() {} @BeforeClass public void setup() { Assert.fail(); } @BeforeMethod public void setup1() {} public static class LocalListener implements IInvokedMethodListener { public static final Map results = new HashMap<>(); @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { results.put(method.getTestMethod().getMethodName(), testResult); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/testhelper/000077500000000000000000000000001475274123300241615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/testhelper/CompiledCode.java000066400000000000000000000013271475274123300273560ustar00rootroot00000000000000package testhelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import javax.tools.JavaFileObject.Kind; public class CompiledCode { private final byte[] byteCode; private final boolean skipLoading; private final String name; public CompiledCode(String name, File directory, boolean skipLoading) throws IOException { this.skipLoading = skipLoading; this.name = name; File classFile = new File(directory, name + Kind.CLASS.extension); this.byteCode = Files.readAllBytes(classFile.toPath()); } public byte[] getByteCode() { return byteCode; } public boolean isSkipLoading() { return skipLoading; } public String getName() { return name; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/testhelper/OutputDirectoryPatch.java000066400000000000000000000030421475274123300311700ustar00rootroot00000000000000package testhelper; /** * OutputDirectoryPatch is a helper class to provide an output directory for TestNG * tests that explicitly create an instance of TestNG and do not know the output directory specified * for the test. * * @author cquezel * @since 4.8 */ public final class OutputDirectoryPatch { /** * The default output directory name if none was specified. We should use something different than * "test-output" to make it clear that the output directory has not been set. */ private static final String DEFAULT_OUTPUT_DIRECTORY = "test-output"; /** The name of the System property used to store the output directory. */ private static final String OUTPUT_DIRECTORY_PROPERTY_NAME = "testng.outputDir"; /** * Private constructor to disable instantiation. * * @since 4.8 */ private OutputDirectoryPatch() { // Hide constructor } /** * Returns the output directory as specified for the current test. * * @return the output directory as specified for the current test. * @since 4.8 */ public static String getOutputDirectory() { String tmp = System.getProperty(OUTPUT_DIRECTORY_PROPERTY_NAME); if (tmp != null) { return tmp; } // System.err.println("System property: " + OUTPUT_DIRECTORY_PROPERTY_NAME // + " has not been set. Using default path: " + DEFAULT_OUTPUT_DIRECTORY); // new Throwable("Stack is only to help locate the problem. No excpetion // thrown.").printStackTrace(System.err); return DEFAULT_OUTPUT_DIRECTORY; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/testhelper/SimpleCompiler.java000066400000000000000000000024351475274123300277540ustar00rootroot00000000000000package testhelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.List; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import org.testng.TestNGException; import org.testng.collections.Lists; public class SimpleCompiler { public static List compileSourceCode(SourceCode... sources) throws IOException { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); String[] arguments = new String[sources.length]; int i = 0; for (SourceCode source : sources) { arguments[i++] = source.getLocation().getCanonicalPath(); } int rc = javac.run(null, null, null, arguments); if (rc != 0) { throw new TestNGException("Encountered errors when compiling code"); } List compiledCodes = Lists.newArrayList(); for (SourceCode source : sources) { source.getLocation().delete(); CompiledCode compiledCode = new CompiledCode(source.getName(), source.getDirectory(), source.isSkipLoading()); compiledCodes.add(compiledCode); } return compiledCodes; } public static File createTempDir() { try { return Files.createTempDirectory("custom").toFile(); } catch (IOException e) { throw new TestNGException(e); } } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/java/testhelper/SourceCode.java000066400000000000000000000017421475274123300270630ustar00rootroot00000000000000package testhelper; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import javax.tools.JavaFileObject.Kind; public class SourceCode { private final String name; private final File directory; private final boolean skipLoading; private final File location; public SourceCode(String name, String src, File directory, boolean skipLoading) throws IOException { this.name = name; this.directory = directory; this.skipLoading = skipLoading; this.location = new File(directory, name + Kind.SOURCE.extension); if (this.location.exists()) { this.location.delete(); } Files.write(location.toPath(), src.getBytes(), StandardOpenOption.CREATE_NEW); } public File getDirectory() { return directory; } public String getName() { return name; } public boolean isSkipLoading() { return skipLoading; } public File getLocation() { return location; } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/kotlin/000077500000000000000000000000001475274123300223615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/kotlin/org/000077500000000000000000000000001475274123300231505ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/kotlin/org/testng/000077500000000000000000000000001475274123300244545ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/kotlin/org/testng/BasicSample.kt000066400000000000000000000002431475274123300271760ustar00rootroot00000000000000package org.testng import org.testng.Assert.fail import org.testng.annotations.Test class BasicSample { @Test fun test() { fail("BOUM") } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/kotlin/org/testng/BasicTest.kt000066400000000000000000000007171475274123300267020ustar00rootroot00000000000000package org.testng import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test import test.SimpleBaseTest class BasicTest : SimpleBaseTest() { @Test fun `basic test as sample`() { val listener = run(BasicSample::class.java) assertThat(listener.failedMethodNames).containsExactly("test") assertThat(listener.succeedMethodNames).isEmpty() assertThat(listener.skippedMethodNames).isEmpty() } } jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/000077500000000000000000000000001475274123300230735ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/1332.xml000066400000000000000000000003611475274123300242050ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/1636.xml000066400000000000000000000004611475274123300242150ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/188.xml000066400000000000000000000003711475274123300241360ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/2532.xml000066400000000000000000000004371475274123300242140ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/987.xml000066400000000000000000000004101475274123300241370ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/META-INF/000077500000000000000000000000001475274123300242335ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/META-INF/services/000077500000000000000000000000001475274123300260565ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/META-INF/services/org.testng.IModule000066400000000000000000000000301475274123300314210ustar00rootroot00000000000000org.testng.SampleIModuleorg.testng.ITestNGListener000066400000000000000000000001171475274123300327750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/META-INF/servicestest.serviceloader.MyConfigurationListener test.testng1232.TestListenerFor1232 org.testng.xml.ISuiteParser000066400000000000000000000000401475274123300331630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/META-INF/servicesorg.testng.xml.FakeHttpXmlParserjtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/a.xml000066400000000000000000000003401475274123300240320ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/b.xml000066400000000000000000000003401475274123300240330ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/000077500000000000000000000000001475274123300303555ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/child-suite1.xml000066400000000000000000000003621475274123300333730ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/child-suite2.xml000066400000000000000000000003621475274123300333740ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/children/000077500000000000000000000000001475274123300321455ustar00rootroot00000000000000child-suite-3.xml000066400000000000000000000005421475274123300351630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/children child-suite-4.xml000066400000000000000000000003611475274123300351630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/children morechildren/000077500000000000000000000000001475274123300345415ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/childrenchild-suite-5.xml000066400000000000000000000003611475274123300376370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/children/morechildren parent-suite-with-duplicate-child.xml000066400000000000000000000006221475274123300374420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/checksuitesinitialization/parent-suite.xml000066400000000000000000000004601475274123300335170ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/create-serviceloader-jar.sh000066400000000000000000000007721475274123300302770ustar00rootroot00000000000000# This script will update serviceloader.jar with the latest version of TmpSuiteListener.class, # which is used by test.serviceloader.ServiceLoaderTest. # Run this script after building TestNG and its tests with ant j=${PWD} rm -rf /tmp/sl mkdir /tmp/sl cd /tmp/sl jar xvf ${j}/serviceloader.jar echo "test.serviceloader.TmpSuiteListener" >META-INF/services/org.testng.ITestNGListener cp ${j}/../../../target/test-classes/test/serviceloader/TmpSuiteListener.class test/tmp jar cvf ${j}/serviceloader.jar . jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/executionlistenersingletoncheck/000077500000000000000000000000001475274123300315655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/executionlistenersingletoncheck/child.xml000066400000000000000000000006241475274123300333740ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/executionlistenersingletoncheck/parent.xml000066400000000000000000000007261475274123300336050ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/groupinvocation/000077500000000000000000000000001475274123300263215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/groupinvocation/parent-suiteA.xml000066400000000000000000000003261475274123300315650ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/groupinvocation/parent-suiteB.xml000066400000000000000000000003261475274123300315660ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/groupinvocation/suiteA.xml000066400000000000000000000004231475274123300302740ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/groupinvocation/suiteB.xml000066400000000000000000000004241475274123300302760ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/hosts.properties000066400000000000000000000000611475274123300263460ustar00rootroot00000000000000testng.hosts=localhost:5150 testng.strategy=test jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/000077500000000000000000000000001475274123300255705ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/child.xml000077500000000000000000000006221475274123300274000ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/child/000077500000000000000000000000001475274123300266535ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/child/child.xml000077500000000000000000000006221475274123300304630ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/child/childofchild/000077500000000000000000000000001475274123300312675ustar00rootroot00000000000000childofchild.xml000077500000000000000000000004601475274123300343510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/child/childofchild jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/childofchild/000077500000000000000000000000001475274123300302045ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/childofchild/childofchild.xml000077500000000000000000000004601475274123300333450ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jarfileutils/testng-tests.xml000066400000000000000000000013101475274123300307510ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/jenkins-junit.xsd000066400000000000000000000141141475274123300264040ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/junit-suite.xml000066400000000000000000000004371475274123300261010ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/listener-in-xml.xml000066400000000000000000000006601475274123300266460ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/methodinterceptors/000077500000000000000000000000001475274123300270155ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/methodinterceptors/multipleinterceptors/000077500000000000000000000000001475274123300333125ustar00rootroot00000000000000multiple-interceptors.xml000066400000000000000000000012331475274123300403260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/methodinterceptors/multipleinterceptors jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/methodselector-in-xml.xml000066400000000000000000000007101475274123300300360ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/package.xml000066400000000000000000000011401475274123300252040ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/000077500000000000000000000000001475274123300262015ustar00rootroot00000000000000inherit-thread-count-child.yaml000066400000000000000000000001571475274123300341270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suitesname: Child suite tests: - name: Tests classes: - test.thread.Sample2 - test.thread.Sample1 inherit-thread-count-parent.yaml000066400000000000000000000001071475274123300343300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suitesname: Parent suite suiteFiles: - ./inherit-thread-count-child.yaml jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/simple-suite-parallel-0.xml000066400000000000000000000006021475274123300332700ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/simple-suite-parallel-1.xml000066400000000000000000000003641475274123300332760ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/simple-suite-parallel-2.xml000066400000000000000000000003641475274123300332770ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-0.xml000066400000000000000000000006501475274123300320040ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-1.xml000066400000000000000000000003641475274123300320070ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-2-1.xml000066400000000000000000000003701475274123300321430ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-2-2-1.xml000066400000000000000000000003741475274123300323060ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-2-2.xml000066400000000000000000000005171475274123300321470ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-2.xml000066400000000000000000000005741475274123300320130ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parallel-suites/suite-parallel-3.xml000066400000000000000000000003641475274123300320110ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/param-inheritance/000077500000000000000000000000001475274123300264625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/param-inheritance/child-suite.xml000066400000000000000000000003601475274123300314150ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/param-inheritance/parent-suite.xml000066400000000000000000000003721475274123300316260ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parametertest/000077500000000000000000000000001475274123300257535ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parametertest/1417.xml000066400000000000000000000013171475274123300270730ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parametertest/child1-suite.xml000066400000000000000000000006241475274123300307720ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parametertest/child2-suite.xml000066400000000000000000000007441475274123300307760ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parametertest/child3-suite.xml000066400000000000000000000006241475274123300307740ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parametertest/parent-suite.xml000066400000000000000000000005501475274123300311150ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/parent-module-suite.xml000066400000000000000000000004601475274123300275200ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/000077500000000000000000000000001475274123300254005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-a.xml000066400000000000000000000003761475274123300273250ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-b.xml000066400000000000000000000003761475274123300273260ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-s-1.xml000066400000000000000000000006721475274123300275040ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-s-2.xml000066400000000000000000000006721475274123300275050ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-s-3.xml000066400000000000000000000006741475274123300275100ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-s-a.xml000066400000000000000000000004041475274123300275550ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test-s-b.xml000066400000000000000000000004041475274123300275560ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test1.xml000066400000000000000000000012221475274123300271570ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test2.xml000066400000000000000000000006731475274123300271710ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/sanitycheck/test3.xml000066400000000000000000000006711475274123300271700ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/serviceloader.jar000066400000000000000000000024211475274123300264170ustar00rootroot00000000000000PKBxÕ> META-INF/þÊPKPKBxÕ>META-INF/MANIFEST.MFóMÌËLK-.Ñ K-*ÎÌϳR0Ô3àår.JM,IMÑuª ˜éÄ(h8ä¤*xæ%ëiòrñrPKz+ªÊ<<PK ãaÑ>META-INF/services/PKBxÕ>,META-INF/services/org.testng.ITestNGListener+I-.Ñ+N-*ËLNÍÉOLI-Ò É-.Í,IõÉ,.IÍK-âPKˆ¢Oç&$PK aÑ>test/PK aÑ> test/tmp/PKBxÕ>test/tmp/TmpSuiteListener.classPMKQ=×›,MÓhX‹‚VF›@†Z(îŸãCŸŒóâÍÿW« E? Ý7Ú&ÛÜs?ιçr?¿Þ?Üà$@mÇ>:>ºïN¥ÊÞʽË1¡ò §’ЈT*ŸòåDš‘˜$ÜiE:ÉXåêM³bç*#\DVf6̤Y©X&ZL¥ GË—a®¬ŒTfe*MŸPÓé€Ý²9¡Û‹´™…N—ÎÂÇ‚ÙwT3—ÚÌ ¾N‡VK†:7±(wGç·ÙõB¬DUx„óGh:E˜v{ž,ḑ[üÐq†ÿ‘ÀOuÈF}®BFb¬^½^9)¡ÆÑ+šö8Öרg$®6âÛ‚ma­v×ÃÐe‡h~ÍÝ+‚+Ž ~ëPKt¾b7+*PKBxÕ> META-INF/þÊPKBxÕ>z+ªÊ<<=META-INF/MANIFEST.MFPK ãaÑ>»META-INF/services/PKBxÕ>ˆ¢Oç&$,ëMETA-INF/services/org.testng.ITestNGListenerPK aÑ>ktest/PK aÑ> Žtest/tmp/PKBxÕ>t¾b7+*µtest/tmp/TmpSuiteListener.classPKÎ-jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/suite1-1.xml000066400000000000000000000004601475274123300251650ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/suite1-2.xml000066400000000000000000000003761475274123300251740ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/suite1.xml000066400000000000000000000007001475274123300250240ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/000077500000000000000000000000001475274123300240525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/listeners/000077500000000000000000000000001475274123300260625ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/listeners/github1284/000077500000000000000000000000001475274123300276635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/listeners/github1284/github1284.xml000066400000000000000000000011001475274123300321760ustar00rootroot00000000000000 github1284_nolistener.xml000066400000000000000000000007261475274123300343760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/listeners/github1284 github1284_withchildlistener.xml000066400000000000000000000011121475274123300357270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/listeners/github1284 github1284_withlistener.xml000066400000000000000000000010711475274123300347270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/listeners/github1284 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/methodselectors/000077500000000000000000000000001475274123300272565ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/methodselectors/sampleTest.xml000066400000000000000000000007011475274123300321170ustar00rootroot00000000000000 sampleTestExclusions.xml000066400000000000000000000010051475274123300341130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/methodselectors jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/timeout/000077500000000000000000000000001475274123300255405ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/test/timeout/issue575.xml000066400000000000000000000004431475274123300276540ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testnames/000077500000000000000000000000001475274123300250765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testnames/main-suite.xml000066400000000000000000000012451475274123300276750ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testnames/upstream-suite.xml000066400000000000000000000003271475274123300306110ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-all.xml000066400000000000000000000051261475274123300256730ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-annconv.xml000066400000000000000000000005511475274123300265620ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-ant.xml000066400000000000000000000004301475274123300256760ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-configfailure.xml000066400000000000000000000005041475274123300277330ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-methodselectors.xml000066400000000000000000000003751475274123300303300ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-override.xml000066400000000000000000000004161475274123300267370ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-package.xml000066400000000000000000000006171475274123300265160ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-single.xml000066400000000000000000000007211475274123300264000ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-single.yaml000066400000000000000000000004431475274123300265430ustar00rootroot00000000000000name: SingleSuite verbose: 2 tests: - name: Test1 excludedGroups: [ excludeThisGroup ] classes: - name: test.dependent.xml.GroupDependencyTest # includedMethods: [ a ] # - test.Test2 # - name: test.CommandLineTest # includedMethods: [ junitParsing ] jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-single2.xml000066400000000000000000000012141475274123300264600ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng-single2.yaml000066400000000000000000000020471475274123300266270ustar00rootroot00000000000000name: SingleSuite verbose: 2 parallel: false threadCount: 4 dataProviderThreadCount: 3 packages: - name: test.testng355.org.apache.tapestry5 include: [Foo, Foo2] exclude: [Bar] - name: test.testng355.org.apache.tapestry5.dom listeners: - test.invokedmethodlistener.MyListener parameters: { n: 42, p: 10, s: "a b c", t: "a,b" } methodSelectors: - className: org.testng.internal.XmlMethodSelector priority: 1 - expression: groups.containsKey("test1") language: beanshell tests: - name: Test3 includedGroups: [A, B] excludedGroups: [C, D] metaGroups: { a: [ b, d] } packages: [ com.example1, com.example2 ] parameters: { n: 43, z: foo } methodSelectors: - className: org.testng.internal.XmlMethodSelector priority: 1 - expression: groups.containsKey("test1") language: beanshell - name: Test1 classes: - name: test.tmp.A includedMethods: [test1, test2] excludedMethods: [test3] - test.tmp.B - name: Test2 classes: - test.tmp.B jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng.xml000066400000000000000000001016111475274123300251210ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng.yaml000066400000000000000000000236671475274123300253010ustar00rootroot00000000000000name: TestNG threadCount: 2 parameters: { short: 47, parameter: out, char: c, byte: 43, first-name: Cedric, int: 42, string: Cedric, factory-param: FactoryParam, boolean: true, long: 46, double: 44.0, float: 45.0 } tests: - name: Nopackage includedGroups: [ nopackage ] classes: - NoPackageTest - name: Regression1 excludedGroups: [ excludeThisGroup ] metaGroups: { evenodd: [ even, odd ] } classes: - test.parameters.ParameterSample - test.parameters.ParameterTest - test.Test1 - test.Test2 - test.CtorCalledOnce - test.expectedexceptions.ExpectedExceptionsTest - test.access.PrivateAccessConfigurationMethods - test.expectedexceptions.WrappedExpectedException - test.parameters.OptionalParameterTest - name: Regression2 excludedGroups: [ broken ] classes: - test.Test1 - test.MethodTest - test.sample.AfterClassCalledAtEnd - test.GraphTest - org.testng.internal.DynamicGraphTest - test.configuration.BaseGroupsTest - test.configuration.BeforeClassThreadTest - test.configuration.BeforeTestOrderingTest - test.configuration.ConfigurationTest - test.configuration.GroupsTest - test.configuration.MultipleBeforeGroupTest - test.configuration.ReflectMethodParametrizedConfigurationMethodTest - test.configuration.SuiteFactoryOnceTest - test.privatemethod.PrivateMethodTest$PrivateMethodInnerTest - test.multiple.TestMultiple - test.ClassConfigurations - test.alwaysrun.AlwaysRunTest - test.conffailure.ConfigurationFailure - test.superclass.MainTest - test.superclass.Test3 - test.failures.FailuresTest - test.mannotation.MAnnotationSampleTest - test.mannotation.MAnnotation2SampleTest - test.thread.ThreadPoolSizeTest - test.thread.SequentialTest - test.thread.ParallelTestTest - test.thread.ParallelSuiteTest - test.thread.FactoryTest - test.thread.DataProviderThreadPoolSizeTest - test.thread.MultiThreadedDependentTest - test.simple.IncludedExcludedTest - test.reports.ReportTest - test.annotationtransformer.AnnotationTransformerTest - test.jar.JarTest - test.xml.XmlVerifyTest - test.invokedmethodlistener.InvokedMethodListenerTest - test.testng249.VerifyTest - test.testng195.AfterMethodTest - test.regression.BeforeTestFailingTest - test.testng285.TestNG285Test - test.failedreporter.FailedReporterTest - test.attributes.AttributeTest - test.verify.VerifyTest - test.abstractconfmethod.C - test.issue78.NonPublicClassTest - test.listeners.ListenerTest - test.preserveorder.PreserveOrderTest - test.listeners.ResultEndMillisTest - name: Injection classes: - test.inject.InjectTestContextTest - test.inject.InjectBeforeMethodTest - test.inject.InjectTestResultTest - test.inject.InjectDataProviderTest - test.inject.NoInjectionTest - name: BeforeMethod classes: - test.configuration.BeforeMethodTest - name: Factory tests classes: - test.factory.classconf.XClassOrderWithFactoryTest - test.factory.FactoryInterleavingTest - name: Basic classes: - test.sample.Basic2 - test.sample.Basic1 - test.Misc - name: Exclusion excludedGroups: [ excludeThisGroup ] classes: - test.Test2 - name: Dependents parameters: { foo: Cedric } classes: - test.dependent.MissingGroupTest - test.dependent.MissingMethodTest - test.dependent.OrderMethodTest - test.dependent.DependentTest - test.dependent.SampleDependentMethods - test.dependent.SampleDependentMethods2 - test.dependent.SampleDependentMethods3 - test.dependent.SampleDependentConfigurationMethods - test.dependent.ClassDependsOnGroups - test.dependent.DependentAlwaysRunTest - test.dependent.MultiGroupTest - test.dependent.ImplicitGroupInclusionTest - test.dependent.ClassWide1Test - test.dependent.ClassWide2Test - test.dependent.DepBugSampleTest - test.dependent.DepBugVerifyTest - test.dependent.DependsOnProtectedMethodTest - test.dependsongroup.DependsOnGroupsTest - name: Inheritance classes: - test.SampleInheritance - test.inheritance.ClassScopeTest - name: Test outer scope includedGroups: [ outer-group ] classes: - test.sample.Scope - name: Test inner scope parameters: { parameter: in } includedGroups: [ inner-group ] classes: - test.sample.Scope - name: AfterClassCalledAtEnd classes: - test.sample.AfterClassCalledAtEnd - name: Triangle classes: - test.triangle.Child1 - test.triangle.Child2 - name: CheckTrianglePost parameters: { expected-calls: 2 } classes: - test.triangle.CheckCount - name: Test class groups 1 classes: - test.classgroup.Second - test.classgroup.First - name: Test class groups 2 classes: - test.classgroup.First - test.classgroup.Second - name: Factory classes: - test.factory.FactoryTest - test.factory.VerifyFactoryTest - test.factory.FactoryInSeparateClassTest - test.factory.Factory2Test - test.factory.FactoryWithInstanceInfoTest - test.factory.VerifyFactoryWithInstanceInfoTest - test.factory.TestClassAnnotationTest - test.factory.FactoryWithDataProviderTest - test.factory.FactoryOrderMainTest - test.factory.FactoryFailureTest - test.factory.FactoryInSuperClassTest - name: TimeOut classes: - test.timeout.TimeOutTest - test.timeout.TimeOutFromXmlTest - name: InvocationCount parameters: { count: 10 } classes: - test.InvocationAndSuccessPercentageTest - test.invocationcount.FailedInvocationCountTest - test.invocationcount.FirstAndLastTimeTest - name: Method1 classes: - name: test.methods.SampleMethod1 includedMethods: - shouldRun1 - shouldRun2 - test.methods.VerifyMethod1 - name: Method2 classes: - name: test.methods.SampleMethod1 excludedMethods: - shouldNotRun1 - shouldNotRun2 - test.methods.VerifyMethod1 - name: Method3 classes: - name: test.methods.SampleMethod1 excludedMethods: - .*Not.* - test.methods.VerifyMethod1 - name: Object factory classes: - test.objectfactory.CustomFactoryTest - test.objectfactory.CombinedTestAndObjectFactoryTest - name: Parameters for constructors classes: - test.ParameterConstructorTest - name: Excluded methods includedGroups: [ group1, group2 ] classes: - name: test.Exclude excludedMethods: - excluded1 - excluded2 - name: Parameters in init 1 parameters: { param: value1 } classes: - test.configuration.ConfigurationWithParameters - name: Parameters in init 2 parameters: { param: value2 } classes: - test.configuration.ConfigurationWithParameters - name: Individual method classes: - name: test.IndividualMethodsTest includedMethods: - testMethod - name: Method inheritance classes: - test.inheritance.DChild_2 - test.inheritance.VerifyTest - name: Method selectors classes: - test.methodselectors.MethodSelectorTest - test.methodselectors.ScriptTest - test.methodselectors.CommandLineTest - name: Test order invocation classes: - test.interleavedorder.InterleavedInvocationTest - name: DataProvider classes: - test.dataprovider.ConfigurationAndDataProvidersTest - test.dataprovider.MethodTest - test.dataprovider.TestContextTest - test.dataprovider.FailingDataProviderTest - test.dataprovider.InstanceDataProviderTest - test.dataprovider.FailingIterableDataProviderTest - test.dataprovider.ClassTest - test.dataprovider.InheritedDataProviderTest - name: UniqueSuite classes: - test.uniquesuite.TestBefore1 - test.uniquesuite.TestBefore2 - test.uniquesuite.TestAfter - name: InheritGroups includedGroups: [ group1 ] classes: - test.configuration.ConfigurationInheritGroupsSampleTest - name: Nested includedGroups: [ unittest ] xmlPackages: - name: test.nested.* - name: Hookable classes: - test.hook.HookSuccessTest - test.hook.HookFailureTest - name: BeforeGroups-AfterGroups-1 classes: - test.configuration.ConfigurationGroups1SampleTest - test.configuration.ConfigurationGroups2SampleTest - test.configuration.ConfigurationGroups3SampleTest - test.configuration.ConfigurationGroups4SampleTest - test.configuration.ConfigurationGroups5SampleTest - test.configuration.ConfigurationGroups6SampleTest - test.configuration.ConfigurationGroups7SampleTest - name: BeforeGroups-AfterGroups-2 includedGroups: [ A, B ] classes: - test.configuration.ConfigurationGroups8SampleTest - name: JUnit classes: - test.JUnitTest1 - test.CommandLineTest - name: Ant-ClassFileResolution classes: - test.ant.TestCommandLineArgs - name: Class Run classes: - test.regression.groupsordering.A - test.regression.groupsordering.B - name: Groups Run includedGroups: [ a ] classes: - test.regression.groupsordering.A - test.regression.groupsordering.B - name: External group invocation includedGroups: [ a ] classes: - test.groupinvocation.GroupConfiguration - test.groupinvocation.DummyTest - name: SkipExceptions classes: - test.skipex.SkippedExceptionTest - name: MethodInterceptor classes: - test.methodinterceptors.MethodInterceptorTest - name: Asserts classes: - test.asserttests.AssertTest - name: ConfigFailurePolicy classes: - test.configurationfailurepolicy.FailurePolicyTest jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/testng_convert.xml000066400000000000000000000006071475274123300266640ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/with-different-name-testng-xml.jar000066400000000000000000000027401475274123300315310ustar00rootroot00000000000000PK²qÍ> META-INF/þÊPKPK²qÍ>META-INF/MANIFEST.MFóMÌËLK-.Ñ K-*ÎÌϳR0Ô3àår.JM,IMÑuª ˜éÄ(h8ä¤*xæ%ëiòrñrPKz+ªÊ<<PK £qÍ>test/PKÇX“8test/different-name-testng.xmlUŽA‚0 …ïûµw7¼šIb”‹‰Ñd»p°(FÀÐâïwƒ™è©yí÷^Ÿ^/[^  ©e¦4¶8Þ™_[¥*?Ëzè{âþ–Æz#3Ùpƒ ¡oï:¿Ã“m€L\!¼ýX ÖæBXÇ„cH¸ÔOGäiQ_Ðè’7Ê=‚J¼ú1è¹Y.´š»„_PK²W“ÚPK ÜX“8 test/jar/PKúX“8test/jar/A.classeŽ¿nÂ0Æ¿ @Ê¿•¡[a¨Õ¹R„Ô)*Eì5ÈØRâô½˜ú<â*uè ß¿ßÝù.×ó€ c4ЋÐ0 „oÚh7#4ž&kBsn¿aj£>ªC¦Š•ÌöìЖ0ZVÆéƒZëR³™ctÚš’0Nm±N•Îì„ü#bÅÖ+!þ´U±QïÚ/ “ç\~Ë.šh1òS"—…HCÄ^ò–E–«Ã#>ØGò¬!¿Æœ‰skz¹ D¬áÝdm³u먦øßÖFç·ŽkòPÿÒ½PK¢bŽbÞ,PKúX“8test/jar/B.classeޱnÂ0†ÿ Ð@ +C·¶sQ%@bB µˆÝ¡Väl)qú^L•x qN‘:ô†ÿÎÿww¾Ëõt0F?FzB8ÑF»wBãùeKhÎí—"$KmÔª:¤ªØÈtÏe„ÁGeœ>¨­.5›Sc¬“N[S†K[d©ҙLÈ?"6l½âO[;µÐ~Y8åò[vÑD‹‘Ÿ¹,ÄŒÐ÷@ì%oY§¹Ú9 META-INF/þÊPK²qÍ>z+ªÊ<<=META-INF/MANIFEST.MFPK £qÍ>»test/PKÇX“8²W“ÚÞtest/different-name-testng.xmlPK ÜX“8 ½test/jar/PKúX“8¢bŽbÞ,ätest/jar/A.classPKúX“8‘ȾÝ,test/jar/B.classPK¯jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/withouttestngxml.jar000066400000000000000000000022771475274123300272520ustar00rootroot00000000000000PKúX“8 META-INF/þÊPKPKúX“8META-INF/MANIFEST.MFóMÌËLK-.Ñ K-*ÎÌϳR0Ô3àår.JM,IMÑuª ˜êÄ+h8ä¤*8çç”–¤é(xæ%ëiòrñrPKõ_FFPK ÜX“8test/PK ÜX“8 test/jar/PKúX“8test/jar/A.classeŽ¿nÂ0Æ¿ @Ê¿•¡[a¨Õ¹R„Ô)*Eì5ÈØRâô½˜ú<â*uè ß¿ßÝù.×ó€ c4ЋÐ0 „oÚh7#4ž&kBsn¿aj£>ªC¦Š•ÌöìЖ0ZVÆéƒZëR³™ctÚš’0Nm±N•Îì„ü#bÅÖ+!þ´U±QïÚ/ “ç\~Ë.šh1òS"—…HCÄ^ò–E–«Ã#>ØGò¬!¿Æœ‰skz¹ D¬áÝdm³u먦øßÖFç·ŽkòPÿÒ½PK¢bŽbÞ,PKúX“8test/jar/B.classeޱnÂ0†ÿ Ð@ +C·¶sQ%@bB µˆÝ¡Väl)qú^L•x qN‘:ô†ÿÎÿww¾Ëõt0F?FzB8ÑF»wBãùeKhÎí—"$KmÔª:¤ªØÈtÏe„ÁGeœ>¨­.5›Sc¬“N[S†K[d©ҙLÈ?"6l½âO[;µÐ~Y8åò[vÑD‹‘Ÿ¹,ÄŒÐ÷@ì%oY§¹Ú9ªC¦Š•ÌöìЖ0ZVÆéƒZëR³™ctÚš’0Nm±N•Îì„ü#bÅÖ+!þ´U±QïÚ/ “ç\~Ë.šh1òS"—…HCÄ^ò–E–«Ã#>ØGò¬!¿Æœ‰skz¹ D¬áÝdm³u먦øßÖFç·ŽkòPÿÒ½PK¢bŽbÞ,PKúX“8test/jar/B.classeޱnÂ0†ÿ Ð@ +C·¶sQ%@bB µˆÝ¡Väl)qú^L•x qN‘:ô†ÿÎÿww¾Ëõt0F?FzB8ÑF»wBãùeKhÎí—"$KmÔª:¤ªØÈtÏe„ÁGeœ>¨­.5›Sc¬“N[S†K[d©ҙLÈ?"6l½âO[;µÐ~Y8åò[vÑD‹‘Ÿ¹,ÄŒÐ÷@ì%oY§¹Ú9 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/badWithoutDoctype.xml000066400000000000000000000002651475274123300300620ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/github1533/000077500000000000000000000000001475274123300254715ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/github1533/child.xml000066400000000000000000000004471475274123300273030ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/github1533/parent.xml000066400000000000000000000003361475274123300275060ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/github2445/000077500000000000000000000000001475274123300254745ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/github2445/expected-failed-report.xml000066400000000000000000000015011475274123300325470ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/github2445/test-suite.xml000066400000000000000000000007601475274123300303270ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/goodWithDoctype.xml000066400000000000000000000002651475274123300275340ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/goodWithoutDoctype.xml000066400000000000000000000002651475274123300302640ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/issue1668.xml000066400000000000000000000013171475274123300260740ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/issue1674.xml000066400000000000000000000015571475274123300260770ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/issue174.xml000066400000000000000000000012261475274123300260020ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/issue435.xml000066400000000000000000000011441475274123300260010ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/xml/simple-suite-with-method-desc.xml000066400000000000000000000006771475274123300322120ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/000077500000000000000000000000001475274123300240355ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/1787.xml000066400000000000000000000016101475274123300251630ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/2078.xml000066400000000000000000000006701475274123300251620ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/2078.yaml000066400000000000000000000002641475274123300253230ustar00rootroot00000000000000name: My_Suite verbose: 0 configFailurePolicy: skip tests: - name: My_test verbose: 0 xmlDependencyGroups: c: a b z: c xmlPackages: - name: test.yaml jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a1.xml000066400000000000000000000032031475274123300250560ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a1.yaml000066400000000000000000000010601475274123300252170ustar00rootroot00000000000000name: SingleSuite verbose: 2 threadCount: 4 parameters: { n: 42 } dataProviderThreadCount: 3 parallel: false configFailurePolicy: continue listeners: - test.methodinterceptors.FastTestsFirstInterceptor - test.invokedmethodlistener.MyListener packages: - name: test.testng355.org.apache.tapestry5 include: [Foo, Foo2] exclude: [Bar] - name: test.testng355.org.apache.tapestry5.dom tests: - name: Regression2 verbose: 2 parameters: { count: 10 } excludedGroups: [ broken ] classes: - test.listeners.ResultEndMillisTest jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a2.xml000066400000000000000000000046341475274123300250700ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a2.yaml000066400000000000000000000021531475274123300252240ustar00rootroot00000000000000name: SingleSuite verbose: 2 parallel: false threadCount: 4 dataProviderThreadCount: 3 packages: - name: test.testng355.org.apache.tapestry5 include: [Foo, Foo2] exclude: [Bar] - name: test.testng355.org.apache.tapestry5.dom listeners: - test.invokedmethodlistener.MyListener parameters: { n: 42, p: 10, s: "a b c", t: "a,b" } tests: - name: Test3 preserveOrder: false includedGroups: [A, B] excludedGroups: [C, D] metaGroups: { a: [ b, d] } packages: [ com.example1, com.example2 ] parameters: { n: 43, z: foo } methodSelectors: - className: org.testng.internal.XmlMethodSelector priority: 1 - expression: groups.containsKey("test1") language: beanshell - name: Test1 preserveOrder: false classes: - name: test.tmp.A includedMethods: [test1, test2] excludedMethods: [test3] - test.tmp.B - name: Test2 preserveOrder: false classes: - test.tmp.B methodSelectors: - className: org.testng.internal.XmlMethodSelector priority: 1 - expression: groups.containsKey("test1") language: beanshelljtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a3-a.xml000066400000000000000000000006551475274123300253060ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a3-a.yaml000066400000000000000000000001371475274123300254430ustar00rootroot00000000000000name: a3-a tests: - name: Test-a3-a classes: - test.listeners.ResultEndMillisTest jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a3-b.xml000066400000000000000000000006551475274123300253070ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a3-b.yaml000066400000000000000000000001371475274123300254440ustar00rootroot00000000000000name: a3-b tests: - name: Test-a3-b classes: - test.listeners.ResultEndMillisTest jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a3.xml000066400000000000000000000003571475274123300250670ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a3.yaml000066400000000000000000000000701475274123300252210ustar00rootroot00000000000000name: a3 verbose: 2 suiteFiles: [ a3-a.xml, a3-b.xml ] jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a4-a.yaml000066400000000000000000000000271475274123300254420ustar00rootroot00000000000000name: a4-a verbose: 2 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a4-b.yaml000066400000000000000000000000271475274123300254430ustar00rootroot00000000000000name: a4-b verbose: 2 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a4.xml000066400000000000000000000003721475274123300250650ustar00rootroot00000000000000 jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/a4.yaml000066400000000000000000000001031475274123300252170ustar00rootroot00000000000000name: SingleSuite verbose: 2 suiteFiles: [ a4-a.yaml, a4-b.yaml ] jtreg7-7.5.1+1+ds1/testng/testng-core/src/test/resources/yaml/suiteWithNonExistentTest.yaml000066400000000000000000000001301475274123300317370ustar00rootroot00000000000000name: My_Suite tests: - name: My_test classes: - this.class.does.not.Exists jtreg7-7.5.1+1+ds1/testng/testng-core/testng-core-build.gradle.kts000066400000000000000000000035401475274123300246240ustar00rootroot00000000000000plugins { id("testng.java-library") id("testng.kotlin-library") groovy id("testng.sonarqube") } java { // use gradle feature // in order to optionally exposed transitive dependency registerFeature("guice") { usingSourceSet(sourceSets["main"]) } registerFeature("junit") { usingSourceSet(sourceSets["main"]) } registerFeature("yaml") { usingSourceSet(sourceSets["main"]) } } dependencies { api(projects.testngCoreApi) // Annotations have to be available on the compile classpath for the proper compilation api("com.google.code.findbugs:jsr305:_") api("com.beust:jcommander:_") "guiceApi"(platform("com.google.inject:guice-bom:_")) "guiceApi"("com.google.inject:guice") "junitImplementation"(projects.testngRunnerJunit4) "yamlImplementation"("org.yaml:snakeyaml:_") implementation(projects.testngCollections) implementation(projects.testngReflectionUtils) implementation(projects.testngRunnerApi) implementation("org.webjars:jquery:_") testImplementation(projects.testngAsserts) testImplementation("org.codehaus.groovy:groovy-all:_") testImplementation("org.spockframework:spock-core:_") testImplementation("org.apache-extras.beanshell:bsh:_") testImplementation("org.mockito:mockito-core:_") testImplementation("org.jboss.shrinkwrap:shrinkwrap-api:_") testImplementation("org.jboss.shrinkwrap:shrinkwrap-impl-base:_") testImplementation("org.xmlunit:xmlunit-assertj:_") testImplementation("commons-io:commons-io:_") } tasks.test { maxParallelForks = Runtime.getRuntime().availableProcessors().div(2) (testFramework.options as TestNGOptions).apply { suites("src/test/resources/testng.xml") listeners.add("org.testng.reporters.FailedInformationOnConsoleReporter") maxHeapSize = "1500m" } } jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/000077500000000000000000000000001475274123300216535ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/000077500000000000000000000000001475274123300224425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/000077500000000000000000000000001475274123300233665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/java/000077500000000000000000000000001475274123300243075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/java/org/000077500000000000000000000000001475274123300250765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/java/org/testng/000077500000000000000000000000001475274123300264025ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/java/org/testng/internal/000077500000000000000000000000001475274123300302165ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/java/org/testng/internal/reflect/000077500000000000000000000000001475274123300316425ustar00rootroot00000000000000ReflectionHelper.java000066400000000000000000000075541475274123300356730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/src/main/java/org/testng/internal/reflectpackage org.testng.internal.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.testng.collections.Lists; public class ReflectionHelper { /** * @return An array of all locally declared methods or equivalent thereof (such as default methods * on Java 8 based interfaces that the given class implements). */ public static Method[] getLocalMethods(Class clazz) { Method[] declaredMethods = excludingMain(clazz); List defaultMethods = getDefaultMethods(clazz); if (defaultMethods.isEmpty()) { List prunedMethods = Lists.newArrayList(); for (Method declaredMethod : declaredMethods) { if (!declaredMethod.isBridge()) { prunedMethods.add(declaredMethod); } } return prunedMethods.toArray(new Method[0]); } Method[] result = new Method[declaredMethods.length + defaultMethods.size()]; System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length); int index = declaredMethods.length; for (Method defaultMethod : defaultMethods) { result[index] = defaultMethod; index++; } return result; } /** * @return An array of all locally declared methods or equivalent thereof (such as default methods * on Java 8 based interfaces that the given class implements) but excludes the main() * method alone. */ public static Method[] excludingMain(Class clazz) { Method[] declaredMethods = clazz.getDeclaredMethods(); List pruned = new LinkedList<>(); for (Method declaredMethod : declaredMethods) { if ("main".equals(declaredMethod.getName()) && isStaticVoid(declaredMethod) && acceptsStringArray(declaredMethod)) { continue; } pruned.add(declaredMethod); } return pruned.toArray(new Method[0]); } /** * A helper method that looks for a given annotation in the current class (or) in any of the super * classes * * @param typedTestClass - The class to search for * @param annotation - The annotation to look for * @param - The annotation type * @return - Either the annotation if found (or) null. */ public static T findAnnotation( Class typedTestClass, Class annotation) { if (typedTestClass == null || annotation == null) { return null; } T ignore = null; Class testClass = typedTestClass; while (testClass != null && testClass != Object.class) { ignore = testClass.getAnnotation(annotation); if (ignore != null) { break; } testClass = testClass.getSuperclass(); } return ignore; } private static boolean isStaticVoid(Method method) { return method.getReturnType().equals(void.class) && Modifier.isStatic(method.getModifiers()); } private static boolean acceptsStringArray(Method method) { Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) { return false; } Class paramType = paramTypes[0]; return paramType.isArray() && paramType.isInstance(new String[0]); } private static List getDefaultMethods(Class clazz) { return getAllInterfaces(clazz).stream() .flatMap(each -> Arrays.stream(each.getMethods())) .filter(method -> !Modifier.isAbstract(method.getModifiers())) .collect(Collectors.toList()); } private static Set> getAllInterfaces(Class clazz) { Set> result = new HashSet<>(); while (clazz != null && clazz != Object.class) { result.addAll(Arrays.asList(clazz.getInterfaces())); clazz = clazz.getSuperclass(); } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-reflection-utils/testng-reflection-utils-build.gradle.kts000066400000000000000000000001531475274123300315210ustar00rootroot00000000000000plugins { id("testng.java-library") } dependencies { implementation(projects.testngCollections) } jtreg7-7.5.1+1+ds1/testng/testng-runner-api/000077500000000000000000000000001475274123300204435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/000077500000000000000000000000001475274123300212325ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/000077500000000000000000000000001475274123300221565ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/000077500000000000000000000000001475274123300230775ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/000077500000000000000000000000001475274123300236665ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/000077500000000000000000000000001475274123300251725ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internal/000077500000000000000000000000001475274123300270065ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internal/Attributes.java000066400000000000000000000013051475274123300317760ustar00rootroot00000000000000package org.testng.internal; import java.util.Map; import java.util.Set; import org.testng.IAttributes; import org.testng.collections.Maps; /** Simple implementation of IAttributes. */ public class Attributes implements IAttributes { private final Map m_attributes = Maps.newHashMap(); @Override public Object getAttribute(String name) { return m_attributes.get(name); } @Override public Set getAttributeNames() { return m_attributes.keySet(); } @Override public void setAttribute(String name, Object value) { m_attributes.put(name, value); } @Override public Object removeAttribute(String name) { return m_attributes.remove(name); } } ITestResultNotifier.java000066400000000000000000000016641475274123300335300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internalpackage org.testng.internal; import java.util.List; import java.util.Set; import org.testng.IConfigurationListener; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.xml.XmlTest; /** * An interface defining the notification for @Test results and also @Configuration * results. */ public interface ITestResultNotifier { Set getPassedTests(ITestNGMethod tm); Set getFailedTests(ITestNGMethod tm); Set getSkippedTests(ITestNGMethod tm); void addPassedTest(ITestNGMethod tm, ITestResult tr); void addSkippedTest(ITestNGMethod tm, ITestResult tr); void addFailedTest(ITestNGMethod tm, ITestResult tr); void addFailedButWithinSuccessPercentageTest(ITestNGMethod tm, ITestResult tr); XmlTest getTest(); List getTestListeners(); List getConfigurationListeners(); } LiteWeightTestNGMethod.java000066400000000000000000000331001475274123300340620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internalpackage org.testng.internal; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.testng.IClass; import org.testng.IDataProviderMethod; import org.testng.IRetryAnalyzer; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.collections.Lists; import org.testng.xml.XmlTest; public class LiteWeightTestNGMethod implements ITestNGMethod { private final Class realClass; private ITestClass testClass; private final String methodName; private final Object instance; private final long[] instanceHashCodes; private final String[] groups; private final String[] groupsDependedUpon; private String missingGroup; private final String[] beforeGroups; private final String[] afterGroups; private final List methodsDependedUpon = new LinkedList<>(); private int priority; private int interceptedPriority; private final XmlTest xmlTest; private final String qualifiedName; private final boolean isBeforeTestConfiguration; private final boolean isAfterTestConfiguration; private final boolean isBeforeGroupsConfiguration; private final boolean isAfterGroupsConfiguration; private final boolean isTest; private final boolean isBeforeMethodConfiguration; private final boolean isAfterMethodConfiguration; private final boolean isBeforeClassConfiguration; private final boolean isAfterClassConfiguration; private final boolean isBeforeSuiteConfiguration; private final boolean isAfterSuiteConfiguration; private List invocationNumbers; private final List failedInvocationNumbers; private boolean ignoreMissingDependencies; private final long invocationTimeout; private boolean skipFailedInvocations; private long timeout; private int invocationCount; private final int successPercentage; private String id; private long date; private final boolean isAlwaysRun; private int threadPoolSize; private final boolean enabled; private String description; private final int currentInvocationCount; private int parameterInvocationCount; private final boolean hasMoreInvocation; private final Class retryAnalyzerClass; private final String toString; private final IDataProviderMethod dataProviderMethod; private final int hashCode; private final Class[] parameterTypes; public LiteWeightTestNGMethod(ITestNGMethod iTestNGMethod) { realClass = iTestNGMethod.getRealClass(); testClass = iTestNGMethod.getTestClass(); methodName = iTestNGMethod.getMethodName(); instance = iTestNGMethod.getInstance(); instanceHashCodes = iTestNGMethod.getInstanceHashCodes(); groups = iTestNGMethod.getGroups(); groupsDependedUpon = iTestNGMethod.getGroupsDependedUpon(); missingGroup = iTestNGMethod.getMissingGroup(); beforeGroups = iTestNGMethod.getBeforeGroups(); afterGroups = iTestNGMethod.getAfterGroups(); if (iTestNGMethod.getMethodsDependedUpon() != null) { methodsDependedUpon.addAll(Arrays.asList(iTestNGMethod.getMethodsDependedUpon())); } priority = iTestNGMethod.getPriority(); interceptedPriority = iTestNGMethod.getInterceptedPriority(); xmlTest = iTestNGMethod.getXmlTest(); qualifiedName = iTestNGMethod.getQualifiedName(); isBeforeTestConfiguration = iTestNGMethod.isBeforeTestConfiguration(); isAfterTestConfiguration = iTestNGMethod.isAfterTestConfiguration(); isBeforeGroupsConfiguration = iTestNGMethod.isBeforeGroupsConfiguration(); isAfterGroupsConfiguration = iTestNGMethod.isAfterGroupsConfiguration(); isTest = iTestNGMethod.isTest(); isBeforeMethodConfiguration = iTestNGMethod.isBeforeMethodConfiguration(); isAfterMethodConfiguration = iTestNGMethod.isAfterMethodConfiguration(); isBeforeClassConfiguration = iTestNGMethod.isBeforeClassConfiguration(); isAfterClassConfiguration = iTestNGMethod.isAfterClassConfiguration(); isBeforeSuiteConfiguration = iTestNGMethod.isBeforeSuiteConfiguration(); isAfterSuiteConfiguration = iTestNGMethod.isAfterSuiteConfiguration(); invocationNumbers = iTestNGMethod.getInvocationNumbers(); failedInvocationNumbers = iTestNGMethod.getFailedInvocationNumbers(); ignoreMissingDependencies = iTestNGMethod.ignoreMissingDependencies(); invocationTimeout = iTestNGMethod.getInvocationTimeOut(); skipFailedInvocations = iTestNGMethod.skipFailedInvocations(); timeout = iTestNGMethod.getTimeOut(); invocationCount = iTestNGMethod.getInvocationCount(); successPercentage = iTestNGMethod.getSuccessPercentage(); id = iTestNGMethod.getId(); date = iTestNGMethod.getDate(); isAlwaysRun = iTestNGMethod.isAlwaysRun(); threadPoolSize = iTestNGMethod.getThreadPoolSize(); enabled = iTestNGMethod.getEnabled(); description = iTestNGMethod.getDescription(); currentInvocationCount = iTestNGMethod.getCurrentInvocationCount(); parameterInvocationCount = iTestNGMethod.getParameterInvocationCount(); hasMoreInvocation = iTestNGMethod.hasMoreInvocation(); retryAnalyzerClass = iTestNGMethod.getRetryAnalyzerClass(); toString = iTestNGMethod.toString(); IDataProviderMethod dp = iTestNGMethod.getDataProviderMethod(); dataProviderMethod = new IDataProviderMethod() { @Override public Object getInstance() { return dp.getInstance(); } @Override public Method getMethod() { throw new UnsupportedOperationException("method() retrieval not supported"); } @Override public String getName() { if (dp == null) { return ""; } return dp.getName(); } @Override public boolean isParallel() { if (dp == null) { return false; } return dp.isParallel(); } @Override public List getIndices() { if (dp == null) { return Lists.newArrayList(); } return dp.getIndices(); } }; hashCode = iTestNGMethod.hashCode(); parameterTypes = iTestNGMethod.getConstructorOrMethod().getParameterTypes(); } @Override public Class[] getParameterTypes() { return parameterTypes; } @Override public Class getRealClass() { return realClass; } @Override public ITestClass getTestClass() { return testClass; } @Override public void setTestClass(ITestClass cls) { this.testClass = cls; } @Override public String getMethodName() { return methodName; } @Override public Object getInstance() { return instance; } @Override public long[] getInstanceHashCodes() { return instanceHashCodes; } @Override public String[] getGroups() { return groups; } @Override public String[] getGroupsDependedUpon() { return groupsDependedUpon; } @Override public String getMissingGroup() { return missingGroup; } @Override public void setMissingGroup(String group) { this.missingGroup = group; } @Override public String[] getBeforeGroups() { return beforeGroups; } @Override public String[] getAfterGroups() { return afterGroups; } @Override public String[] getMethodsDependedUpon() { return methodsDependedUpon.toArray(new String[0]); } @Override public void addMethodDependedUpon(String methodName) { methodsDependedUpon.add(methodName); } @Override public boolean isTest() { return isTest; } @Override public boolean isBeforeMethodConfiguration() { return isBeforeMethodConfiguration; } @Override public boolean isAfterMethodConfiguration() { return isAfterMethodConfiguration; } @Override public boolean isBeforeClassConfiguration() { return isBeforeClassConfiguration; } @Override public boolean isAfterClassConfiguration() { return isAfterClassConfiguration; } @Override public boolean isBeforeSuiteConfiguration() { return isBeforeSuiteConfiguration; } @Override public boolean isAfterSuiteConfiguration() { return isAfterSuiteConfiguration; } @Override public boolean isBeforeTestConfiguration() { return isBeforeTestConfiguration; } @Override public boolean isAfterTestConfiguration() { return isAfterTestConfiguration; } @Override public boolean isBeforeGroupsConfiguration() { return isBeforeGroupsConfiguration; } @Override public boolean isAfterGroupsConfiguration() { return isAfterGroupsConfiguration; } @Override public long getTimeOut() { return timeout; } @Override public void setTimeOut(long timeOut) { this.timeout = timeOut; } @Override public int getInvocationCount() { return invocationCount; } @Override public void setInvocationCount(int count) { this.invocationCount = count; } @Override public int getSuccessPercentage() { return successPercentage; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public long getDate() { return date; } @Override public void setDate(long date) { this.date = date; } @Override public boolean canRunFromClass(IClass testClass) { return getTestClass().getRealClass().isAssignableFrom(testClass.getRealClass()); } @Override public boolean isAlwaysRun() { return isAlwaysRun; } @Override public int getThreadPoolSize() { return threadPoolSize; } @Override public void setThreadPoolSize(int threadPoolSize) { this.threadPoolSize = threadPoolSize; } @Override public boolean getEnabled() { return enabled; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public void incrementCurrentInvocationCount() {} @Override public int getCurrentInvocationCount() { return currentInvocationCount; } @Override public void setParameterInvocationCount(int n) { this.parameterInvocationCount = n; } @Override public int getParameterInvocationCount() { return parameterInvocationCount; } @Override public void setMoreInvocationChecker(Callable moreInvocationChecker) {} @Override public boolean hasMoreInvocation() { return hasMoreInvocation; } @Override public ITestNGMethod clone() { throw new UnsupportedOperationException("clone() not supported"); } @Override public IRetryAnalyzer getRetryAnalyzer(ITestResult result) { throw new UnsupportedOperationException("getRetryAnalyzer() not supported"); } @Override public void setRetryAnalyzerClass(Class clazz) {} @Override public Class getRetryAnalyzerClass() { return retryAnalyzerClass; } @Override public boolean skipFailedInvocations() { return skipFailedInvocations; } @Override public void setSkipFailedInvocations(boolean skip) { this.skipFailedInvocations = skip; } @Override public long getInvocationTimeOut() { return invocationTimeout; } @Override public boolean ignoreMissingDependencies() { return ignoreMissingDependencies; } @Override public void setIgnoreMissingDependencies(boolean ignore) { this.ignoreMissingDependencies = ignore; } @Override public List getInvocationNumbers() { return invocationNumbers; } @Override public void setInvocationNumbers(List numbers) { this.invocationNumbers = numbers; } @Override public void addFailedInvocationNumber(int number) { failedInvocationNumbers.add(number); } @Override public List getFailedInvocationNumbers() { return failedInvocationNumbers; } @Override public int getPriority() { return priority; } @Override public void setPriority(int priority) { this.priority = priority; } @Override public int getInterceptedPriority() { return interceptedPriority; } @Override public void setInterceptedPriority(int priority) { this.interceptedPriority = priority; } @Override public XmlTest getXmlTest() { return xmlTest; } @Override public ConstructorOrMethod getConstructorOrMethod() { throw new UnsupportedOperationException("Not supported"); } @Override public Map findMethodParameters(XmlTest test) { return XmlTestUtils.findMethodParameters(xmlTest, getTestClass().getName(), getMethodName()); } @Override public String getQualifiedName() { return qualifiedName; } @Override public IDataProviderMethod getDataProviderMethod() { return dataProviderMethod; } @Override public String toString() { return toString; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object o) { // Intentionally not checking the parameter type if (this == o) { return true; } if (!(o instanceof ITestNGMethod)) { return false; } ITestNGMethod that = (ITestNGMethod) o; boolean value = realClass.equals(that.getRealClass()) && qualifiedName.equals(that.getQualifiedName()) && equalParamTypes(parameterTypes, that.getParameterTypes()); return value; } boolean equalParamTypes(Class[] params1, Class[] params2) { if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return false; } return true; } return false; } } jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internal/TestResult.java000066400000000000000000000334241475274123300317750ustar00rootroot00000000000000package org.testng.internal; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import javax.annotation.Nonnull; import org.testng.IAttributes; import org.testng.IClass; import org.testng.ITest; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.TestNGException; import org.testng.collections.Lists; import org.testng.collections.Objects; /** This class represents the result of a test. */ public class TestResult implements ITestResult { private ITestNGMethod m_method = null; private List skippedDueTo = Lists.newArrayList(); private boolean skipAnalysed = false; private int m_status = CREATED; private Throwable m_throwable = null; private long m_startMillis = 0; private long m_endMillis = 0; private String m_name = null; private String m_host; private Object[] m_parameters = {}; private String m_instanceName; private ITestContext m_context; private int parameterIndex; private boolean m_wasRetried; private final IAttributes m_attributes = new Attributes(); private final String id = UUID.randomUUID().toString(); private TestResult() { // defeat instantiation. We have factory methods. } public static TestResult newEmptyTestResult() { return new TestResult(); } public static TestResult newTestResultFor(ITestNGMethod method) { return newContextAwareTestResult(method, null); } public static TestResult newContextAwareTestResult(ITestNGMethod method, ITestContext ctx) { TestResult result = newEmptyTestResult(); long time = System.currentTimeMillis(); result.init(method, ctx, null, time, 0L); return result; } public static TestResult newTestResultWithCauseAs( ITestNGMethod method, ITestContext ctx, Throwable t) { TestResult result = newEmptyTestResult(); long time = System.currentTimeMillis(); result.init(method, ctx, t, time, time); return result; } public static TestResult newEndTimeAwareTestResult( ITestNGMethod method, ITestContext ctx, Throwable t, long start) { TestResult result = newEmptyTestResult(); long time = System.currentTimeMillis(); result.init(method, ctx, t, start, time); return result; } public static TestResult newTestResultFrom( TestResult result, ITestNGMethod method, ITestContext ctx, long start) { TestResult testResult = newEmptyTestResult(); testResult.setHost(result.getHost()); testResult.setParameters(result.getParameters()); testResult.setParameterIndex(result.getParameterIndex()); testResult.init(method, ctx, null, start, 0L); TestResult.copyAttributes(result, testResult); return testResult; } private void init(ITestNGMethod method, ITestContext ctx, Throwable t, long start, long end) { m_throwable = t; m_instanceName = method.getTestClass().getName(); if (null == m_throwable) { m_status = ITestResult.SUCCESS; } m_startMillis = start; m_endMillis = end; if (RuntimeBehavior.isMemoryFriendlyMode()) { m_method = new LiteWeightTestNGMethod(method); } else { m_method = method; } m_context = ctx; Object instance = method.getInstance(); // Calculate the name: either the method name, ITest#getTestName or // toString() if it's been overridden. if (instance == null) { m_name = m_method.getMethodName(); return; } if (instance instanceof ITest) { m_name = ((ITest) instance).getTestName(); if (m_name != null) { return; } m_name = m_method.getMethodName(); if (Utils.getVerbose() > 1) { String msg = String.format( "Warning: [%s] implementation on class [%s] returned null. Defaulting to method name", ITest.class.getName(), instance.getClass().getName()); System.err.println(msg); } return; } if (method.getTestClass().getTestName() != null) { m_name = method.getTestClass().getTestName(); return; } String string = instance.toString(); // Only display toString() if it's been overridden by the user m_name = getMethod().getMethodName(); try { if (!Object.class.getMethod("toString").equals(instance.getClass().getMethod("toString"))) { m_instanceName = string.startsWith("class ") ? string.substring("class ".length()) : string; m_name = m_name + " on " + m_instanceName; } } catch (NoSuchMethodException ignore) { // ignore } } @Override public void setEndMillis(long millis) { m_endMillis = millis; } /** * If this result's related instance implements ITest or use @Test(testName=...), returns its test * name, otherwise returns null. */ @Override public String getTestName() { if (this.m_method == null) { return null; } Object instance = this.m_method.getInstance(); if (instance instanceof ITest) { return ((ITest) instance).getTestName(); } if (m_method.getTestClass().getTestName() != null) { return m_method.getTestClass().getTestName(); } return null; } @Override public String getName() { return m_name; } /** @return Returns the method. */ @Override public ITestNGMethod getMethod() { return m_method; } /** @param method The method to set. */ public void setMethod(ITestNGMethod method) { m_method = method; } /** @return Returns the status. */ @Override public int getStatus() { return m_status; } /** @param status The status to set. */ @Override public void setStatus(int status) { m_status = status; } @Override public boolean isSuccess() { return ITestResult.SUCCESS == m_status; } /** @return Returns the testClass. */ @Override public IClass getTestClass() { return m_method.getTestClass(); } /** @return Returns the throwable. */ @Override public Throwable getThrowable() { return m_throwable; } /** @param throwable The throwable to set. */ @Override public void setThrowable(Throwable throwable) { m_throwable = throwable; } /** @return Returns the endMillis. */ @Override public long getEndMillis() { return m_endMillis; } /** @return Returns the startMillis. */ @Override public long getStartMillis() { return m_startMillis; } @Override public String toString() { List output = Reporter.getOutput(this); return Objects.toStringHelper(getClass()) .omitNulls() .omitEmptyStrings() .add("name", getName()) .add("status", toString(m_status)) .add("method", m_method) .add("output", !output.isEmpty() ? output.get(0) : null) .toString(); } private static String toString(int status) { switch (status) { case SUCCESS: return "SUCCESS"; case FAILURE: return "FAILURE"; case SKIP: return "SKIP"; case SUCCESS_PERCENTAGE_FAILURE: return "SUCCESS WITHIN PERCENTAGE"; case STARTED: return "STARTED"; case CREATED: return "CREATED"; default: throw new TestNGException("Encountered an un-defined test status of [" + status + "]."); } } @Override public String getHost() { return m_host; } public void setHost(String host) { m_host = host; } @Override public Object[] getParameters() { return m_parameters; } @Override public void setParameters(Object[] parameters) { m_parameters = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { // Copy parameter if possible because user may change it later if (parameters[i] instanceof Cloneable) { try { Method clone = parameters[i].getClass().getDeclaredMethod("clone"); m_parameters[i] = clone.invoke(parameters[i]); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | SecurityException e) { m_parameters[i] = parameters[i]; } } else { m_parameters[i] = parameters[i]; } } } @Override public Object getInstance() { return IParameterInfo.embeddedInstance(this.m_method.getInstance()); } @Override public Object[] getFactoryParameters() { IParameterInfo instance = this.m_method.getFactoryMethodParamsInfo(); if (instance != null) { return instance.getParameters(); } return new Object[0]; } @Override public Object getAttribute(String name) { return m_attributes.getAttribute(name); } @Override public void setAttribute(String name, Object value) { m_attributes.setAttribute(name, value); } @Override public Set getAttributeNames() { return m_attributes.getAttributeNames(); } @Override public Object removeAttribute(String name) { return m_attributes.removeAttribute(name); } @Override public ITestContext getTestContext() { return m_context; } public void setContext(ITestContext context) { m_context = context; } @Override public int compareTo(@Nonnull ITestResult comparison) { return Long.compare(getStartMillis(), comparison.getStartMillis()); } @Override public String getInstanceName() { return m_instanceName; } @Override public void setTestName(String name) { m_name = name; } public void setParameterIndex(int parameterIndex) { this.parameterIndex = parameterIndex; } public int getParameterIndex() { return parameterIndex; } public boolean wasRetried() { return m_wasRetried; } public void setWasRetried(boolean wasRetried) { this.m_wasRetried = wasRetried; } public List getSkipCausedBy() { if (this.m_status != SKIP || skipAnalysed) { return Collections.unmodifiableList(skippedDueTo); } skipAnalysed = true; // check if there were any config failures Set skippedConfigs = m_context.getFailedConfigurations().getAllResults(); for (ITestResult skippedConfig : skippedConfigs) { if (isGlobalFailure(skippedConfig) || isRelated(skippedConfig)) { // If there's a failure in @BeforeTest/@BeforeSuite/@BeforeClass // then the reason is most often just one method. skippedDueTo.add(skippedConfig.getMethod()); } if (belongToSameGroup(skippedConfig)) { // If its @BeforeGroups then there's a chance that there could be more than one // method. So lets add everything. skippedDueTo.add(skippedConfig.getMethod()); } } if (!skippedDueTo.isEmpty()) { // If we found atleast one skipped due to reason, then its time to return back. return Collections.unmodifiableList(skippedDueTo); } // Looks like we didnt have any configuration failures. So some upstream method perhaps failed. if (m_method.getMethodsDependedUpon().length == 0) { // Maybe group dependencies exist ? if (m_method.getGroupsDependedUpon().length == 0) { return Collections.emptyList(); } List upstreamGroups = Arrays.asList(m_method.getGroupsDependedUpon()); List allFailures = Lists.merge( m_context.getFailedTests().getAllResults(), m_context.getFailedButWithinSuccessPercentageTests().getAllResults()); skippedDueTo = allFailures.stream() .map(ITestResult::getMethod) .filter( method -> { List currentMethodGroups = Arrays.asList(method.getGroups()); List interection = Lists.intersection(upstreamGroups, currentMethodGroups); return !interection.isEmpty(); }) .collect(Collectors.toList()); return Collections.unmodifiableList(skippedDueTo); } List upstreamMethods = Arrays.asList(m_method.getMethodsDependedUpon()); // So we have dependsOnMethod failures List allfailures = Lists.merge( m_context.getFailedTests().getAllResults(), m_context.getFailedButWithinSuccessPercentageTests().getAllResults()); skippedDueTo = allfailures.stream() .map(ITestResult::getMethod) .filter(method -> upstreamMethods.contains(method.getQualifiedName())) .collect(Collectors.toList()); return Collections.unmodifiableList(skippedDueTo); } public String id() { return id; } private static boolean isGlobalFailure(ITestResult result) { ITestNGMethod m = result.getMethod(); return m.isBeforeTestConfiguration() || m.isBeforeSuiteConfiguration(); } private boolean isRelated(ITestResult result) { ITestNGMethod m = result.getMethod(); if (!m.isBeforeClassConfiguration() && !m.isBeforeMethodConfiguration()) { return false; } Object current = this.getInstance(); Object thatObject = result.getInstance(); return current.getClass().isAssignableFrom(thatObject.getClass()) || thatObject.getClass().isAssignableFrom(current.getClass()); } private boolean belongToSameGroup(ITestResult result) { ITestNGMethod m = result.getMethod(); if (!m.isBeforeGroupsConfiguration()) { return false; } String[] mygroups = this.m_method.getGroups(); if (mygroups.length == 0 || m.getGroups().length == 0) { return false; } List cfgMethodGroups = Arrays.asList(m.getGroups()); return Arrays.stream(mygroups).anyMatch(cfgMethodGroups::contains); } public static void copyAttributes(ITestResult source, ITestResult target) { source .getAttributeNames() .forEach(name -> target.setAttribute(name, source.getAttribute(name))); } } jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internal/XmlTestUtils.java000066400000000000000000000014271475274123300322760ustar00rootroot00000000000000package org.testng.internal; import java.util.Map; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlTest; final class XmlTestUtils { private XmlTestUtils() {} static Map findMethodParameters( XmlTest test, String className, String methodName) { Map result = test.getAllParameters(); for (XmlClass xmlClass : test.getXmlClasses()) { if (xmlClass.getName().equals(className)) { result.putAll(xmlClass.getLocalParameters()); for (XmlInclude include : xmlClass.getIncludedMethods()) { if (include.getName().equals(methodName)) { result.putAll(include.getLocalParameters()); break; } } } } return result; } } jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internal/invokers/000077500000000000000000000000001475274123300306465ustar00rootroot00000000000000IInvocationStatus.java000066400000000000000000000005051475274123300350600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-api/src/main/java/org/testng/internal/invokerspackage org.testng.internal.invokers; /** Helps keep track of when a method was invoked */ public interface IInvocationStatus { /** @param date - The timestamp at which a method was invoked. */ void setInvokedAt(long date); /** @return - The timestamp at which a method got invoked. */ long getInvocationTime(); } jtreg7-7.5.1+1+ds1/testng/testng-runner-api/testng-runner-api-build.gradle.kts000066400000000000000000000001341475274123300271000ustar00rootroot00000000000000plugins { id("testng.java-library") } dependencies { api(projects.testngCoreApi) } jtreg7-7.5.1+1+ds1/testng/testng-runner-junit4/000077500000000000000000000000001475274123300211075ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-runner-junit4/testng-runner-junit4-build.gradle.kts000066400000000000000000000001671475274123300302160ustar00rootroot00000000000000plugins { id("testng.java-library") } dependencies { api(projects.testngRunnerApi) api("junit:junit:_") } jtreg7-7.5.1+1+ds1/testng/testng-test-kit/000077500000000000000000000000001475274123300201275ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-kit/src/000077500000000000000000000000001475274123300207165ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-kit/src/main/000077500000000000000000000000001475274123300216425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-kit/src/main/java/000077500000000000000000000000001475274123300225635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-kit/src/main/java/testhelper/000077500000000000000000000000001475274123300247425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-kit/src/main/java/testhelper/PerformanceUtils.java000066400000000000000000000034071475274123300310730ustar00rootroot00000000000000package testhelper; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class PerformanceUtils { private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); private static final Method GET_THREAD_ALLOCATED_BYTES = initGetThreadAllocatedBytes(); private static Method initGetThreadAllocatedBytes() { try { Method method = THREAD_MX_BEAN.getClass().getMethod("getThreadAllocatedBytes", long.class); method.setAccessible(true); method.invoke(THREAD_MX_BEAN, Thread.currentThread().getId()); return method; } catch (Throwable e) { return null; } } public static boolean canMeasureAllocatedMemory() { return GET_THREAD_ALLOCATED_BYTES != null; } /** @return amount of memory (in bytes) allocated by current thread until now */ public static long measureAllocatedMemory() { if (GET_THREAD_ALLOCATED_BYTES == null) { throw new IllegalStateException( "Method getThreadAllocatedBytes(long) is not found in ThreadMXBean " + THREAD_MX_BEAN); } long selfId = Thread.currentThread().getId(); try { return (long) GET_THREAD_ALLOCATED_BYTES.invoke(THREAD_MX_BEAN, selfId); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to call " + GET_THREAD_ALLOCATED_BYTES, e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof Error) { throw (Error) cause; } throw new RuntimeException("Unable to call " + GET_THREAD_ALLOCATED_BYTES, cause); } } } jtreg7-7.5.1+1+ds1/testng/testng-test-kit/testng-test-kit-build.gradle.kts000066400000000000000000000000521475274123300262470ustar00rootroot00000000000000plugins { id("testng.java-library") } jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/000077500000000000000000000000001475274123300203015ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/LICENSE.pgjdbc000066400000000000000000000024511475274123300225400ustar00rootroot00000000000000Copyright (c) 1997, PostgreSQL Global Development Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/gradle.properties000066400000000000000000000002001475274123300236450ustar00rootroot00000000000000# pax-exam uses Maven dependency resolution, so it needs a repository osgi.test.mavencentral.url=https://repo1.maven.org/maven2 jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/000077500000000000000000000000001475274123300210705ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/000077500000000000000000000000001475274123300220475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/000077500000000000000000000000001475274123300227705ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/org/000077500000000000000000000000001475274123300235575ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/org/testng/000077500000000000000000000000001475274123300250635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/org/testng/test/000077500000000000000000000000001475274123300260425ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/org/testng/test/osgi/000077500000000000000000000000001475274123300270035ustar00rootroot00000000000000DefaultTestngOsgiOptions.java000066400000000000000000000030471475274123300345420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/org/testng/test/osgi/* * Copyright (c) 2021, PostgreSQL Global Development Group * See the LICENSE.pgjdbc file in testng-test-osgi folder for more information. */ package org.testng.test.osgi; import static org.ops4j.pax.exam.CoreOptions.*; import org.ops4j.pax.exam.options.ModifiableCompositeOption; /** Pulls repository URLs from system properties and passes them to pax-exam test container. */ public class DefaultTestngOsgiOptions { public static ModifiableCompositeOption defaultTestngOsgiOptions() { return composite( // This declares "remote" repositories where the container would fetch artifacts from. // It is testng built in the current build + central for other dependencies systemProperty("org.ops4j.pax.url.mvn.repositories") .value(System.getProperty("testng.org.ops4j.pax.url.mvn.repositories")), // This is a repository where osgi container would cache resolved maven artifacts systemProperty("org.ops4j.pax.url.mvn.localRepository") .value(System.getProperty("testng.org.ops4j.pax.url.mvn.localRepository")), mavenBundle("org.testng", "testng").versionAsInProject(), mavenBundle("org.assertj", "assertj-core").versionAsInProject(), systemProperty("logback.configurationFile") .value(System.getProperty("logback.configurationFile")), mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject()); } } jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/java/org/testng/test/osgi/PlainOsgiTest.java000066400000000000000000000026261475274123300324010ustar00rootroot00000000000000package org.testng.test.osgi; import static org.assertj.core.api.Assertions.assertThat; import static org.ops4j.pax.exam.CoreOptions.options; import static org.testng.test.osgi.DefaultTestngOsgiOptions.defaultTestngOsgiOptions; import java.lang.reflect.Method; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerMethod; import org.ops4j.pax.exam.testng.listener.PaxExam; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * The purpose of the class is to ensure {@code postgresql} bundle activation does not fail in case * {@code org.osgi.service.jdbc} is not available. */ @Listeners(PaxExam.class) @ExamReactorStrategy(PerMethod.class) public class PlainOsgiTest { @Configuration public Option[] config() { return options(defaultTestngOsgiOptions()); } @Test public void versionShouldStartWithDigit() throws Exception { Class versionClass = Class.forName("org.testng.internal.Version"); Method getVersionStringMethod = versionClass.getMethod("getVersionString"); Object version = getVersionStringMethod.invoke(null); assertThat(version) .matches( (v) -> String.valueOf(v).length() > 0 && Character.isDigit(String.valueOf(v).charAt(0)), "Version.getVersionString() should start with a digit"); } } jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/resources/000077500000000000000000000000001475274123300240615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/resources/exam.properties000066400000000000000000000001531475274123300271300ustar00rootroot00000000000000# We redirect all the logging to slf4j+logback, so we disable default logging here pax.exam.logging = none jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/src/test/resources/logback-test.xml000066400000000000000000000007351475274123300271670ustar00rootroot00000000000000 %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n jtreg7-7.5.1+1+ds1/testng/testng-test-osgi/testng-test-osgi-build.gradle.kts000066400000000000000000000072411475274123300266020ustar00rootroot00000000000000plugins { id("testng.java-library") } val testngRepository by configurations.creating { isCanBeConsumed = false isCanBeResolved = true description = "Consumes local maven repository directory that contains the artifacts produced by :testng" attributes { attribute(Category.CATEGORY_ATTRIBUTE, objects.named("maven-repository")) attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL)) } } dependencies { testngRepository(projects.testng) testImplementation(projects.testng) testImplementation("javax:javaee-api:_") { // The dependency was not obvious, logged https://github.com/cbeust/testng/issues/2578 because("PaxExam uses javax.transaction.NotSupportedException and other classes") } testImplementation("org.ops4j.pax.exam:pax-exam-container-native:_") // pax-exam is not yet compatible with junit5 // see https://github.com/ops4j/org.ops4j.pax.exam2/issues/886 testImplementation("org.ops4j.pax.exam:pax-exam-testng:_") testImplementation("org.ops4j.pax.exam:pax-exam-link-mvn:_") testImplementation("org.ops4j.pax.url:pax-url-aether:_") testImplementation("org.apache.felix:org.apache.felix.framework:_") testImplementation("ch.qos.logback:logback-core:_") testImplementation("ch.qos.logback:logback-classic:_") } // val depDir = layout.buildDirectory.dir("pax-dependencies") val generateDependenciesProperties by tasks.registering(WriteProperties::class) { description = "Generates dependencies.properties so pax-exam can use .versionAsInProject()" setOutputFile(depDir.map { it.file("META-INF/maven/dependencies.properties") }) property("groupId", project.group) property("artifactId", project.name) property("version", project.version) property("${project.group}/${project.name}/version", "${project.version}") dependsOn(configurations.testRuntimeClasspath) dependsOn(testngRepository) doFirst { configurations.testRuntimeClasspath.get().resolvedConfiguration.resolvedArtifacts.forEach { val prefix = "${it.moduleVersion.id.group}/${it.moduleVersion.id.name}" property("$prefix/scope", "compile") property("$prefix/type", it.extension) property("$prefix/version", it.moduleVersion.id.version) } } } sourceSets.test { output.dir(mapOf("builtBy" to generateDependenciesProperties), depDir) } // // This repository is used instead of ~/.m2/... to avoid clash with /.m2/ contents val paxLocalCacheRepository = layout.buildDirectory.dir("pax-repo") val cleanCachedTestng by tasks.registering(Delete::class) { description = "Removes cached testng.jar from pax-repo folder so pax-exam always resolves the recent one" delete(paxLocalCacheRepository.map { it.dir("org/testng") }) } tasks.test { dependsOn(generateDependenciesProperties) dependsOn(cleanCachedTestng) dependsOn(testngRepository) systemProperty("logback.configurationFile", file("src/test/resources/logback-test.xml")) // Regular systemProperty can't be used here as we need lazy evaluation of testngRepository jvmArgumentProviders.add(CommandLineArgumentProvider { listOf( "-Dtestng.org.ops4j.pax.url.mvn.repositories=" + "file:${testngRepository.singleFile.absolutePath}@snapshots@id=testng-current" + ",${project.findProperty("osgi.test.mavencentral.url")}@id=central", "-Dtestng.org.ops4j.pax.url.mvn.localRepository=file:${paxLocalCacheRepository.get().asFile.absolutePath}@id=pax-repo" ) }) } jtreg7-7.5.1+1+ds1/testng/testng/000077500000000000000000000000001475274123300163655ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/000077500000000000000000000000001475274123300171545ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/test/000077500000000000000000000000001475274123300201335ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/test/java/000077500000000000000000000000001475274123300210545ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/test/java/org/000077500000000000000000000000001475274123300216435ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/test/java/org/testng/000077500000000000000000000000001475274123300231475ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/test/java/org/testng/test/000077500000000000000000000000001475274123300241265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/testng/testng/src/test/java/org/testng/test/VerifyShadedJarWorksTest.java000066400000000000000000000005311475274123300316700ustar00rootroot00000000000000package org.testng.test; import org.testng.Assert; import org.testng.annotations.Test; /** * The test does not look sophisticated, however it still verifies that testng-all.jar works to a * certain degree. */ public class VerifyShadedJarWorksTest { @Test public void testHelloWorld() { Assert.assertEquals(4, 2 + 2, "2 + 2"); } } jtreg7-7.5.1+1+ds1/testng/testng/testng-build.gradle.kts000066400000000000000000000073361475274123300227570ustar00rootroot00000000000000plugins { id("testng.published-java-library") id("testng.merge-feature-jars") } description = "Testing framework for Java" java { // The features would be merged into testng.jar as follows: // org.testng dependencies would be included to the jar // third-party dependencies would be left as regular dependencies optionalFeatures { shadedDependenciesFilter.set { it.owner.let { id -> id is ProjectComponentIdentifier && id.build.isCurrentBuild } } create("ant") { api(projects.testngAnt) } create("guice") { api(platform("com.google.inject:guice-bom:_")) api("com.google.inject:guice") } create("junit") { implementation(projects.testngRunnerJunit4) } create("yaml") { implementation("org.yaml:snakeyaml:_") } } } dependencies { // Note: it is enough to mention key projects here, and testng transitives // would be selected automatically shadedDependencyElements(projects.testngAsserts) shadedDependencyElements(projects.testngCore) } tasks.mergedJar { manifest { // providers.gradleProperty does not work // see https://github.com/gradle/gradle/issues/14972 val name = rootProject.findProperty("project.name") val vendor = rootProject.findProperty("project.vendor.name") attributes( // Java 9 module name "Automatic-Module-Name" to project.group, // BND Plugin instructions (for OSGi) "Bundle-ManifestVersion" to 2, "Bundle-Name" to name, "Bundle-SymbolicName" to project.group, "Bundle-Vendor" to vendor, // See http://docs.osgi.org/specification/osgi.core/7.0.0/framework.module.html#i2654895 "Bundle-License" to "Apache-2.0", "Bundle-Description" to project.description, "Bundle-Version" to project.version.toString().removeSuffix("-SNAPSHOT"), "Import-Package" to """ bsh.*;version="[2.0.0,3.0.0)";resolution:=optional, com.beust.jcommander.*;version="[1.7.0,3.0.0)";resolution:=optional, com.google.inject.*;version="[1.2,1.3)";resolution:=optional, junit.framework;version="[3.8.1, 5.0.0)";resolution:=optional, org.junit.*;resolution:=optional, org.apache.tools.ant.*;version="[1.7.0, 2.0.0)";resolution:=optional, org.yaml.*;version="[1.6,2.0)";resolution:=optional, *;resolution:=optional """.trimIndent().replace("\n", ""), "Export-Package" to """ org.testng org.testng.annotations org.testng.asserts org.testng.collections org.testng.internal org.testng.internal.annotations org.testng.internal.ant org.testng.internal.collections org.testng.internal.invokers org.testng.internal.invokers.objects org.testng.internal.junit org.testng.internal.objects org.testng.internal.objects.pojo org.testng.internal.reflect org.testng.internal.thread org.testng.internal.thread.graph org.testng.junit org.testng.log org.testng.log4testng org.testng.reporters org.testng.reporters.jq org.testng.reporters.util org.testng.thread org.testng.util org.testng.xml org.testng.xml.internal """.trimIndent().replace("\n", ",") ) } } jtreg7-7.5.1+1+ds1/testng/versions.properties000066400000000000000000000054561475274123300210610ustar00rootroot00000000000000#### Dependencies and Plugin versions with their available updates. #### Generated by `./gradlew refreshVersions` version 0.10.0 #### #### Don't manually edit or split the comments that start with four hashtags (####), #### they will be overwritten by refreshVersions. #### #### suppress inspection "SpellCheckingInspection" for whole file #### suppress inspection "UnusedProperty" for whole file plugin.com.github.johnrengelman.shadow=7.0.0 plugin.com.github.vlsi.gradle-extensions=1.74 plugin.com.github.vlsi.stage-vote-release=1.78 version.ch.qos.logback..logback-classic=1.2.3 version.ch.qos.logback..logback-core=1.2.3 version.com.beust..jcommander=1.78 ## # available=1.81 version.com.google.code.findbugs..jsr305=3.0.1 ## # available=3.0.2 version.com.google.inject..guice-bom=5.0.1 version.commons-io..commons-io=2.11.0 version.javax..javaee-api=8.0.1 version.junit.junit=4.13.2 version.mockito=3.10.0 version.org.apache-extras.beanshell..bsh=2.0b6 version.org.apache.ant..ant-testutil=1.10.9 ## # available=1.10.10 version.org.apache.ant..ant=1.10.9 ## # available=1.10.10 version.org.apache.felix..org.apache.felix.framework=7.0.0 version.org.assertj..assertj-core=3.10.0 ## # available=3.11.0 ## # available=3.11.1 ## # available=3.12.0 ## # available=3.12.1 ## # available=3.12.2 ## # available=3.13.0 ## # available=3.13.1 ## # available=3.13.2 ## # available=3.14.0 ## # available=3.15.0 ## # available=3.16.0 ## # available=3.16.1 ## # available=3.17.0 ## # available=3.17.1 ## # available=3.17.2 ## # available=3.18.0 ## # available=3.18.1 ## # available=3.19.0 version.org.codehaus.groovy..groovy-all=2.4.7 version.org.jboss.shrinkwrap..shrinkwrap-api=1.2.6 version.org.jboss.shrinkwrap..shrinkwrap-impl-base=1.2.6 version.org.mockito..mockito-core=2.12.0 version.org.ops4j.pax.exam..pax-exam-container-native=4.13.1 version.org.ops4j.pax.exam..pax-exam-link-mvn=4.13.1 version.org.ops4j.pax.exam..pax-exam-testng=4.13.1 version.org.ops4j.pax.url..pax-url-aether=2.6.1 version.org.spockframework..spock-core=1.0-groovy-2.4 version.org.webjars..jquery=3.5.1 ## # available=3.6.0 version.org.xmlunit..xmlunit-assertj=2.8.2 version.org.yaml..snakeyaml=1.21 ## # available=1.22 ## # available=1.23 ## # available=1.24 ## # available=1.25 ## # available=1.26 ## # available=1.27 ## # available=1.28 jtreg7-7.5.1+1+ds1/univocity-parsers/000077500000000000000000000000001475274123300172635ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/.github/000077500000000000000000000000001475274123300206235ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/.github/FUNDING.yml000066400000000000000000000011231475274123300224350ustar00rootroot00000000000000# These are supported funding model platforms github: [jbax] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: [paypal.me/jeronimobackes] jtreg7-7.5.1+1+ds1/univocity-parsers/.gitignore000066400000000000000000000001651475274123300212550ustar00rootroot00000000000000/target/* /test-output/* /target .idea univocity-parsers.iml univocity-parsers.ipr univocity-parsers.iws .DS_STORE jtreg7-7.5.1+1+ds1/univocity-parsers/LICENSE-2.0.html000066400000000000000000000253661475274123300215440ustar00rootroot00000000000000 Apache License, Version 2.0 - The Apache Software Foundation

Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

  1. You must give any other recipients of the Work or Derivative Works a copy of this License; and

  2. You must cause any modified files to carry prominent notices stating that You changed the files; and

  3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and

  4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

jtreg7-7.5.1+1+ds1/univocity-parsers/README.md000066400000000000000000000030571475274123300205470ustar00rootroot00000000000000![thumbnail](./images/uniVocity-parsers.png) Welcome to univocity-parsers ============================ univocity-parsers is a collection of extremely fast and reliable parsers for Java. It provides a consistent interface for handling different file formats, and a solid framework for the development of new parsers. We have finally updated the tutorial, please go to our website: https://www.univocity.com/pages/parsers-tutorial **Bugs, contributions & support** If you find a bug, please report it on github or send us an email on parsers@univocity.com. We try out best to eliminate all bugs as soon as possible and you’ll rarely see a bug open for more than 24 hours after it’s reported. We do our best to answer all questions. Enhancements/suggestions are implemented on a best effort basis. Fell free to submit your contribution via pull requests. Any little bit is appreciated, from improvements on documentation to a full blown rewrite from scratch. For commercial support, customizations or anything in between, please contact support@univocity.com. **Thank you for using our parsers!** Please consider sponsoring our project or [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JKH3JNHLL4Y42&source=url) any amount via PayPal, or Bitcoin on the following address: * 3BcmUPTPfLDuYWWSBxGKkChkq5WMzC94J6 Thank you! The univocity team. jtreg7-7.5.1+1+ds1/univocity-parsers/images/000077500000000000000000000000001475274123300205305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/images/uniVocity-parsers.png000066400000000000000000002342511475274123300247130ustar00rootroot00000000000000‰PNG  IHDRˆ£_‰gbKGDÿÿÿ ½§“ pHYs ЗƾtIMEÞ Ý÷¼ñ IDATxÚì½I¬$Y–ž÷s¯™¹û{/ÆŒŒœjfWUv =W‡¢DM$‚VÒB $J qAh'P €€i!A+A ­ÄjA‰D‘Íf5‡.v5;³«²*3«²ºrŽŒˆopw³{ïÑâ^37÷çoŠˆ¬ÊÌ2ã îöl<ÿ=çÿÏ0.ó’KâõrÎ!"„>ü?&óöþCù"‰Î{T3CP’ ˆ:º°€Tþ;ãeùoº¶{Ößfg}pËM$矑õc)_Ëy;:úÖNù½!’Ï“ˆR¶ƒH9î”6¶Ï©ùPÈÆ®ÊÚU’¯Ö¿>ý¡³á}vÓ`[Î×Ed;ÿ•;PÖ¯­sŽc¹y{ªŠsÌåwÞ{€rR>çÞçç®ëÂèXò¿"£‹d'þôÉ=6CD†ë7Þs[;^Ù¸Òëç³ÿ¾ß–œ¸†lÝÎæýoÆêÊù߆!ÃÞm;¸õ¿o§ž€¼m†­öwãúž¯Î‰\ìê_ì“ ""B]×t]GJé# ý-¤åÃiuA Lò{T(h~˜bJ%x/Û‚ó(<žˆòÀE6BêFà쟬Ϧm½UAÕ ‡™   RN è} Ëß)Yù™]ä6ß#'?b§œ/‘-›ú0,»Ô•²SÀà´g§àm‹. Hø*:º‚ê:x¯‡@ÙÔeãDµ¿ÆÛ.áj §ŸÛòä!Ÿá³®Àywš¶¡þíûc—‰÷ò˜ˆOX4Mƒ™Ñ¶íG XÃ{)ÞV™CJÄ”HIQÀåÅVY¹˜År‘ÂvNWw±±âzT€ØrÖ–V2¬~¶Ÿ¬qðµQÏû«ªT•#&#•«HY­‰B ÙzöÕ“ÙfŽpþjíôÇZÎ8?›Û=뉻ì“o— 1‰Ñ5‘­ØæÊxóÕg¸)¥á=Ã*Úlkž<^GwÊéVéÀt³³ÎÍE" œrî/zßۃö…Êy_sFfs^¼—‹Ç­GŽù3ÐPUêºf¹\žú<*2ä ÙÎÌÖ‘²’¸ÍdU&Ã9OSטõ«ˆÜC°µ•s†T.ÊYÇVÀÁÆû2ÞcÛòñDz¥Œ¶íý£ŸmÄê*%µ.¬­Æe”Œ¬•™l#;z,7¯ŽÎ³|<†s2…“AýâŸ}ôgKV·­2‡ˆl•¼>œgûÃZIÚÏñ¯È³[îçDz‹ƒÒ”÷žÉÒ‡öPmT;·d ¥¤¼0.5WÑ’PX‰#БŠs5"¹îëœÐ¶máRâuœ ÈFæ`ÛsîÇUbÕïe+ï §—dN”2”ºªèBG ±ñ¾Û,T¥”<Ò°œ|¼ qñܓד×/†ä”GNmãÆöˆÏ܇Ä-}8™ÃªÎ>^¯ö¸­+#), %1íëã9ƒÈ@ %°+1õ ü ¹6 ˜r± eºvam  Î*Ól‚Ã)Ùƒœã\0œs4µ'¥DÛRŠûZT—Éþf¾}ei±º“Çx³?y=y}Ø!ëwç™|“<†ÌØñ‘¸/ø‹zÙCãDËEè‹H« +Ò—s´”?úØ,CIJÐ\?7Ë ªr8ïKÍÞÕœ>/ÇAÑŠRDÚS.Œ°Î;3•–ÿpÆ 'ëÔA.£Á@d#£0)<,•ra…÷JŒ‘¶m…ÍmxÅ b £ìì2ÇuŽâ H㾂Ueß.zQÏ¿#¦`[ÖÀFO„¬ïïø7%ƒP)¤tÛÑ.N…hF+¹'¤j<{{»,»–ÃÃ9f©š1Ôôú½±•jk•µØÚn¬)ômóþ8“xO^A€85kØìç9-N>,OgçÇŒK?2r¡8éÁ‡dhÐx…OjZdãKY½}k‹I!–ÑÐmLR§›r ÑÕß,AOTz™~þ;ÞW€£‘’°l º§.'ÉHtXƒÃÆ>ÊŠØÎ²sº„5Iý-‚:‘qô]'í‡ÎÙž“YÝŒ†‰vÞróÖu$Áუ,c5#ÆH8Ž,—-W®î:çòž¬«ìó?ÙÑ–euמ¼‰Ï[)]Dÿäõäõs.1‰žÒ!§dvNè=«ëßÎøÅj ÿЉ<ÒIèË'zâ8eˆ×"€V°râ$­TEcx(ÁWý¨óyuü+î¡ð¶ÚGDÊ)RDbÉ´RV#‰RWŽÝÝÀ±X´¤(¹A.Z)Œ,k5ë€ncÿ\‘Ð:’ 'd¬§pk i¹@r¢Æ)ÛV'k«Ê]ãßk¥ü&Ò÷B÷g21N¹õÌMÚ6ðÁwYΗ$ ’ˆf8§\»¶Ç|¾àøx‰.gý°6Ëg+Ò{û`[>wÞƒð¤õäõQ ·fr¹ûö´…ש@1zö.ø<<š ©ï..䫬Ê7k “ý†X‘Ï"£ 'k¡aPmø½ˆÇÄ¡x(õ@ÿÚªémPõ™Ã°+~JÁHf8ÍÇR7M) )ÎyD!BKèt]‹1[²ê}è³·Z¡oö:Ø8ãØÆAØ8¥9Û g-›:ÖV)²ê°E‡lALÐr D ijvwwpš#†ÈñÑ1!v¯í±³;%&ãx¾`Þ¶ÄiêÌËìï±X¶gð ¶Æ-ÙÚ¹áĹ‘5)¡äQÀâ H6RQÚÉ  ÈHI³Ê¬»ÙPÆ2"HÉDGq¢å ÊÖ7@ÒXrÖÐgù‡c‘Ò-m%ˆª*NA5ƒDÛ—,¢4ÈYÎ2¥#;‹þ‚¦ ÀK+c»dý4ã½m%§M€PIJ”%W¡Ñ„ÙlÊSÏÜÄbâøðQÇtgÂdÒжï¾—GÇLgSš¦Æ{G²Dè‡sÚÒa-²Í '­—åÆà?ù´qžÌ.¶æÈö˜$€O^O^ ÜXÅ4&I7üh¶•™FUÛ’a_ieuÁín W2ðf}€æÄAÙZ†c+¾`M›?êgšÐŒÜ‹Pax_œTû¾‚ü·{?PÔy§GVΫ q'Žä¦YÛ?ifˆËA>¦H×bL¨Rì0ëHt,àsEMU 2¦Å›´~iKqòd¯‡Ô±G©mɶƒ ¹ö³žpî?©‚¢lÄ;ˆpãæu®Þ¸ÊO_ÿcBƒOyǧoðìs·Ùß?à‡?zƒ”ªnÅ5¥ª°W+)V22:4ÛÂëØ){¶] u!°Ç>{‰'ÊÝO @ÈH*8ZA!ëef9ëþ߬m”‹ä¢å#³S±éñÝÌ’EêWÊZV§= Èh¥ž³Œ4rôÌÜ€®léÁ!•wÖˆVˆxD|Q)–V5µ\>r ®¬äûŸéh±i¤lÚ¹À;e:Ý!™±\„Á”Îy¡ë:óRj¶|¦—¶æR—•,BÖìŽK¶0¬œ¹HÈ™èÜ/@t4tõéââ9dS¥„”ó4E¥|Zrˆ$2žºò|þÅ/°\´¼ö£ÓÆDâQk0›Nøò—?f¼üý×h—!_k•!U´ùïÿbÔg©\SƒÁÜpÔ½niÍ–çl?ÁɇêB@ñ1ŽÀO@ãã kÙÃi«îóšB/blyÊïÎã&.dPpáZÇZM-+Š ˆ¸^È!yõðçRyŸ2•¢"f±ˆ6=¦™P­Ÿy„>™üD]t £×÷Y†ŒDK“ €L§“Üì"– „W)»;¡]pp¸YWÊK=#âVD¹ lëWÃiTb: 8gõ=^qèés†JO: ŽñìÐ|¥dÕÛÝê[×FêYÃ/ÿêW@•¾úîíÐ.Û’ålãW¾þeÀøÁ+oÂJ˜Ai^«ì©½ÅU÷yáol휤rýÓ:'±µ?ĶŸÎ9å›ÁÜù¸½üæM&ÛîÀ;¤-ê<9o‰VÖ «Œä;5£Øl?8³¤tA"¢'>l#Œ1¿ÀH'³^6±Ì_;о¾Ÿ]HëyŽ!Nj)#õ j}vÂÈp¯³”J( «ñå2R×Óé³Hè´µžNûXºÒËàVzÿ"§=lFÔû0deL¸ÚqÔFœÎ "늭r(‚“Q¶ ‚Zã d4f¨WnÞzнk»8ï98:âý»÷ùGßýn=}“ÏásL' w>¸Ç;ï¼Ïááï=¾ª©œ£®'„ é­ƒOU.ã%Dú,°ï•Ñ•ûg$•;£ç´ül$“†uN‡õŒ‘5wQÛ¢+¿X™èaâ#é`*O㣓AlÔ«ßêæ>-ðÊà¿=:G½&s’‡ØÌÚ/ÝôÍhya¸±ýñjò ¼ï†î ð$a1‘%¤”l¡Fµ­sg´è0_@ÉÁ_ÔaV Êj_FFÈV)D3pͦÓ<­«d?‚dµRhQ ݤíŽËê7Žè%ñ– %Ø dôªŒ²: i$6ÿÝèrîý¤Vj,YŽe† ®”’\¹ƒR©ì“:Ç/}å—¨›†Ÿ½õ‹®ezu—›7nâœòýÎ{wîòÔë|öÓŸbgw—ŒªòÜ¿Ä_{“ããeiXÌ ¼š'2¿Rñ­ŠÃÄ=[+ŽÎÕpo¤r¥‘’i“Œ>M±aû@œM”ìÌN©?HØÇ Ž?˜ÇÀA0ZÌóˆSBñ‚˜] α$\ˆÌXãÔO¼]×kàešú `Íð-­J %ÀJIÂú2“QÆwJ*«ôï&ˆV uæFþ&fºZ™òº¯ZˆºAQ“¤Ån<æf®É¤f:k8:jéBÂ;‡óJS íbÁñ|Ÿ{©Ê1«Îl)d«õpLLË6;oÛžŽ‚ÿZ¹¦ÏT×ÊH}åÈ›"‚·•”0g¤hJF$qý©|áKŸç{øG¼ÿ`Ÿˆa)—Þ^øÔ üÚW¿Êîòÿü/©« Þ×Ä ´¼«sYÏõ|ÓxAT uå\ÄbóÞ—˜Ê`¥57Ü¡/¶Ê*ÖL ÍNy@¶ƒÄ0ä!ÜZÀ)O‚Þf䡿ãl&ãzä 0X2DKw… êkf“){Wvè´mDz]‚—tí’ùü˜®Û]õ`¨+ÝÕÙ×ië [³?Ò”§Hzó1þEKÖå<88‡¨Ç\þ™Vâ¨æ9 •µHþW…Jïó€#§Šºü7’*I!ªÑ©r$¹’ÕÈ|9çgo½Å³Ï<ßù­ß„ƒÃcB40OŒ µoøÚW¿ÌO~r‡EõKJkkTvou±®æY½aB?L'ØHo~—1¶Át§;8×л â(Íó ,e¿¤L^ëð`8õ…”N9p«X_)yZ¤©•ºVœÚö˜Ã£}RˆE-UV­ê‡^K¹~žzr5Åá8mÓOHF«2&œ £¥ÑLu”aô‹Œ„j¡•H¶þ`$óUრÁŒ¥$––ÂRÇ?ÿ­oðÍßøu^zùe^}ý5~öæÛ TKׯÞàÙ§ŸåÊÕkx_ñ³·îðö;÷Jàq£»«'–ÇÁ~\Vê¿_}=.+ÙàcUT]¶yŸ¬²’A1â´ìT€`gÛà6 yú 6JGgÔ—V0=ŒÑoж"(ls˜ø¤Äº2qC»}Ž´Õä1ô­£.ÇÍaé4*áR@1|k§½QJ1Î6û/êÒ íŠ4’€èÁwQÙÁéWl4b!5A/¦z¹«:ðé0SDó*ߊäÁy÷fж±” "Kbìp’%™!tÅÞ;—°Ô;œdß¡žˆí³…ï%º›9”¡†ò\¹T…Ës-D  Ša^ Æð•¼Ø cY)úg) t –Ëè,‘,bd¨_úÂçðêxpð€¯åkìLg¼òÃ×xéå×YÎ#•›åŒÎ2/$š‰üܽn£K9"åÙˆ¾´T²ƒ|þàPšç{3¥r-F¾3}Š:ȇ×ÁNãÆl=¯üUWs(lÔ¹*H< \èù²'ÈÁõñm^NVÚÖŒF?àó—?*1(/·œbao늌–­½Ûªûwûûí<«³va£ ¸oDzáÃi Xõ’ÔTö¯]­üP”+8ÝA´€Î *8:wN÷)Ü@o&Œæ>'´pUUó ·pN¹wÿ€ù|Éb~LŒsRlKwuVø†"êÉYVêdUNVkýª*!;OIî6Á¤¨’QrOЉÐc®ˆÄ²”4F$’²ä´RGˆ Æ´šñÂsŸâOó[xWó÷û÷øá~FU5ywÊ]×¹rÖÐ>KZu<Ëpì‘A1±•Üu ¦{@ØT- bk³@Vé'áD‘õn}ë·7Ö¡üÃö’˜²ù¾Ç×wAÓ³ ™tÚÇä\êe5à“’A¬Ä)üÃ8hœVïœ 1|¦'kÃŶk[D™±´éo4¼gÝah½9ÎhòªYg‡áÄ)STw@&x­r2H¡Å9mJ¾d½s¬¥@î– Úá\î”Nf81vw*D#G‡‡äÌAJö ®ÂpXO —’’Fs0ˆirZ)ÂàmáJÆ ¥»[ É­ùïy§Ôš3-„Á—\Tr“`¹FÑŒ`Ab `]„Ô‘b@bæTsY,ÅÉ!É£æA¨ý¿ö«_á¿õk¼ñÆÛüÓßû#îÝ}0"Ö[dô¡âÆDÜ,@I+õ’lü» –ÖÁAV–îƒû­­VúëóAXsý¶ÓÆ·n–E…­± Vçgfù > ­p€ø {DPµëÖèÀ|²H Q?î¤>…؇ ^Œ ­ÜÏ|ùÕŠÍÎç¶ýî2×KÖä;r¢&Ÿûï*’%RZËÑùñ»¹ïA&¥ÄÉ2qœËMSÔ5¹¯bTŸ¶Ô›ýNs×t6¥s9#èK'bD HlÙÙñìì6ìïr¼˜ç2DQ¥¾;¸”Fl ¤ÓPºl(-õ%%éA3Ç9Ís›5Ï£§TÞá áœËòÕJ¬4¾•óêòöz£ÁÎ`‘`#‹:èræ fܺ~ƒ_úÜ繺{A¸wÿ?}ã-ÞyûÝ2¢:E’#„ÄÕ«×ø³æWùàî>ÿü~@a´Ê/]lc…3.¯…" ͼȸ«ÜÎB†¯) Þ÷O”LÁF `ë%";QbºÀ´¾ÑÀ¢¾4g›6âÛÄrzÙêrÑõ¤·Ž]Ô’ÿBÏ»=b ùð2…mY‚#ÿHZ—|è!§&Å×Þ¨@:÷Æ;w^ü…ëž+õRñm-¿ìW‰£Á‰Ï£?-aiÚN×'{¨Û)=‰˜:$•Q–æ7A½®=|yâ[V䦈ãÊÞŒ›7opx4gÿÁ¡kI©+ά!Ûs;ÅTP—½ŸR’A²Û›Ì¥Q“×*p¥ÌWôý Zz4ƒ…©!Nñ jï²¥¸Ó Nð*TÎð’ÿ“’aàKPÓÜý’°HÂq0bk¤.A‘®#†º1B0®Lwøsßøwïíóúk¯3­§MÝ@ÊĶŠQW.—¨ú€Þ»±Â¥°l—ÔòÔ«ÔSÏ<-&«¡ Ÿm4Ô—‹ˆIÌ`'–ƒ¢æ2‘8ÉMmÞeª§W ®êÆ1m*f³ Õ´Ffâ´f9ÉÿN&žÉÄ1)“Gµ#èn…î*2óȴ¦}ÅÂ+‡ ÇꆦC±„¤IÕhÐ@:E‚!AIqïý¾ýgþ,Ÿ~þ³¼ñúˆ±^{ý-¼S¾öµ>ªM¬ IDAT/òÎ;wY.:´œ;ú*T*•3@hÌßk@% KY,Qi»Dåï]ÜTÛzÃ;K£ÒݪSÚÖè’ipÖž)]¹Óž¸Gäôv›õÓ9£ÏÍ.ö€m雳óسûÅ€ƒ¬¹-_]y44A~"JLÕ»®/¤íþá2Çÿ°^[,8Øx×j¤—ö†YhSÑÛläîhYÙ-HÊMqÔ¨xÄ)!,Q9)¬v®áÜl4è;eçU)Ù…ËÜ…møð¨‰„$#‰áÔÓ4MÓÐL&¨mrt|„I¤š*ÕDiƒÐ¶Œ¦ÔQTJ¥´$½\ÓŠÓ…©*Cÿ…sà=xÎWPÕÄʽ'ÔÉ;\å¨+˜4P{+¨8A\Q_ÅDÂ2ó]H¤‘6`m‹-#,"2O0Ø"` £ŠÊÓ7žby¸äƒîcÑAòÜzêÿê¿òm®^»Â½üc~òã·9>:fgoÆoýÖ/ó¿ÿ oüäÍÜ’aVøƒ,÷ƪjÈ|H6àËÜ{&û] Ô:(´çóÅv¹Ïœ²Â{¬@pÑUú Ò;‹£ùü@Èy~L8¬ÂèÊÀÎúd^#·üŠí9«˜}·zv£4ô®®"u!;z¥‹HÊõ–!ÍQIÌ‹²éª×æ²Qï+ÙúY´^e$NU“¡ëŠI`/µ,þFÓiÍÓOßäp>çî½èRÇdWøÌ§žæÝ;w¹»?ÏÕ¥Ï!I0£™…Ð$¨Î9*ñT>ÑI•P)÷˜¯±¦Á5L*´™RÏ”¦Iex¯h RZ¬(4 t™W^´Êqh Ë@j, –‰Yv„ã€, ZƒEÀÚˆt:ƒ(¨y>û©O³·s…ç_xŽgž¹Åw¾ó2¯½úZ'yïñJ‘éڶ˳µ5äŒIBÌY“¡+ææ9Spœsøª*>Q> Šc€”1/ bŠ#pÈÀûl"åæ¹dëó§7ËLVd¾ãѽf}æ±ņÃNåÐìÂq×{E]¬s";¿Hжs~xQõ‘]¦Ä ¶€Ú,‰ÈÐó(ÙÁiçêO@œ¦^ú¹„ǬçØ(„ߤÒP–hÁº þ‘†ùdyÊ›™Ãi]ì)Šÿ1—”t‚º¦8«.°¸(àpn†¥«¸z+Žª e°}n†ëí¤¡®#Î)B‘h §¹<£^i¦ {{;™ðcg§B5ÑÉœywŒÓšý‡ìaâ³|Ô¹bE¾j¬K¸bm!êUOtJ§Bçs]Ij‡ŸÌ`6Eš 7à›Š¦‚¦j§Ùl¯µ\ž‘…B€„åæm"-R.!µKRÐe"µ‘´\@LÐF4Öè M0ñSb aa8©0ST*^øô³ü ÿÒ¯óö›ð~÷e‹! $b òâk‹Dµ+àq,‘âûä­ætW RÕ+[ÅÖ—“R$Ä 1@bÈÀ‰8 QËZÇ= }£å RÊWH óm)‘6”=*eæ¹e{Ùjøµ]>àm·ü=»”…þå|1.cÏoPÛ)eõrôùÁýI± dìþx~n±v-µX&ŒÈâKÖƒCþI$Y²¼àW2ûüó|þ3/0©¦t­±ÿ˜7ÞxŸ÷ß>ç°dì̾ù§_äÚÕßÿþëüøÕ?¦].g9‹€¢ X¢,qD¼ùm]áê ïsÉ,–€SÄÒ*ˆ±d b „þëÐ- óÇæ¶hƒG¯^’qi©'³¬ ½Þˆq3“`›Çújm­›šñúér!l÷v:7ˆ_ÔvÃz®‹d f'KHÃñÛÅ3€OšLõã[Öóäeæ ¤ òÉ– 2¬r(ÑsØæøºv£**Œ*»Rã4w#:N“Éb¡B\MŠ™H&aáLq²ƒTWÐf·€`-!´™õ&ŽÚ'ê:Ò%£kûu~&¿Ëýü-æí’÷¼KôÇÌfžWn°X,yóƒ÷H8Ð u.τ뻖ÕÊHÑDÒ2?A•èæ =Q´ñP{d:Á5;øæ U3£òBã'TÞ¡­"]]”E†OŠFheëé’@ˆX»„ [Ös„¶€B ¡Å›‘HÌŠ%Kðõ¿Ì×¾öE¾÷Ýòþ»‡ìí\á¹çoóü ·øÑÞä?øcBHhqO½}{ç_¸Éë¯þ”û÷ Ú«Ã: E¤ÅË'‘J…ºvTÍWÕ઒B,ö"ÉòXØ8*#…‰±£ë]ì]GdäÇÔ—¡ dR9K˜‡±¬ƒSîJÙKV‘½¸ÊûÇì²6[f8ØCŽ•-òf@µÓ¦Kx*Ù¹îÍãù"v‰Sq2[÷˜Ü¿L‰èOÇpÞË_8»{\£å쟯ø£ÕÌ…¼2ÒÌ<‚,kݳ(Õ }³gm_p(I28ˆÔYÕC?e¬ï–͆t& f.[>8#ÃY…×ñ7°zq“2×8Ë(½Ÿ`ÅŒog&8×±èr0—H³S)#™&¤¤w?àéÛ{|éùç¸w¸Ïý8Z3›í2]ì± Ðx‡SÉóš%‘¤#X¤#4¹IÏy¨Z+R+Z{h4Sêú*•ß¡‘«qs‡šGS…,*4¸Ì˜°ì”@EìÀºDóÔ6 é€"Ú%bÌ+{ ë,϶ˆyRœ†.—ïbhØ¿Ÿ£G¼óöOøÉëðí?ÿ"×®ïòÿá÷IEmôþ»÷¹wç^èãrg½q²ÄIK¥-U¥T“ U3E|]ùâ÷ÔûNYq²æIç B m—´±+Í„†¸|§ä’R)ûôe$XY‰±ØªƒÅü}1/f‡1”Ò£ñAf'ABΉ¶òÁó 7ÕëWý)%bt¡ÍÓ÷bÈòSgTΑ¢}”ž†4ê^Žef†:‡ª0ŸÏ 1•ûJ Qœ1¥ÕÐñÔÏaU+#ûŸ8Øz°!x>}ûY~vﺈ*9WÒbÁkeþ³eŒ¦fc%,(N„Ú JÍ”Š¼Nõ¨)rijBttQé¬BÒήâÒG…EC­…H©%v ÌŽÁæ`m.ô^NæJ)¥ÂTqæÁ*övžá_ÿ×~•wÞ~Àßÿ{¯p|8çå—ÞäÞÝž{þ*ŸúÔêÚS{Çáá/½ôcB·¤Ò§Kj×QO"Õ¤ÆÕ»ˆ¯Ê„8ë£ËÈw©ÌòNF×µ,»¡”Œ šy‰­ð‰8ÈX3ÇQ7ªJ:º¶cÑ.!&‚) Vl4¢¬ºâSJEÅ&ØÖZ¾¬/„¶„sž¯Mbk‡õ…bã¨,³­É»÷›ZíËX¹ÅËE§ñ ãýß6s»ÏÈ6y‡Óà 0Î;nî]ãg÷ð í@I(µô´*§ôÓÙHMÂD`’s.<‡"–3/%8E££fažEt8™ 6ÃÛ¼ÜÀÙMTòˆT ŠY‹qHJGXÜ'Y‹Ù1C™c²PÀ’£æu}•¯}õ>ó©«|ÿ¥{8Ÿøìgw8:šóû¿÷*÷ïß§]rûvßýöùÙOÞæåフÐÒÔõ4à' >bíU*ý”=R>–˜–mhéBKˆm‘šRr˦d¹ Ú²º(wFç>vvgTµg¾Xä áxɃƒ#œ:ªªâøx1¨’ £ªsÆ™KI¹×!Æ"k-תwa탞œ·´¾ Hœ—=Ø ¡“\¸ °x«YÝëÛOR݆4+ž@Nlã„RIVÕªµŠÔ9™„=Òô¢'¯ËÆùñ(ÜBïJªº’žßšm~`Tˆ¡FÒ )z}m9ïž2)£=VÔK²H?ï“f‚«ò°ž¶UºåS@ƒó â¦`•˜Y‰©œ0ÃS¹šV`žZ–vÝZÝZ_¡šÞ`woÊlÖ±L‘ùR VáªñÙO¼Ç7MBÐ) †i&Óg“†çnÎhÜ·î¿Çáò{Ó“¦qì/;Ž£Ìrcž¤áÁK¨Ñ2áîLhD˜FGm  ©p(š ±D0ciÐ&8$9„'S”ë(7qì L€ ±ˆ¤Ø’h H‘”ŽKXl« R…c±›¨M®âµæW¾¶Ç­Ûð»¿óûûûÌfK¾öÕ+\»¦üãß}™÷Þ|I ®^u<ótÃï‘t‰úÞ2{%‘”ÁI4[•Ä.Ð…Ž¶kI–=¸D3ÇäJ¿ƒ%#$#Å\2ê§Ãu]7d ÁÞ{ö®^åÎ{ÌqÎ3›N1qxpÌdR‘,²X„ÂoålS=¹Ñ± Z †f§D­ÇkóŽÏÈ l“Œ¾Àöí¤}Åðßÿ þÆóstÿƒ­‡1PÊcuÖ˜²Ü·È)!²å\¨sëM„}žö“×åKLa×}¡ É u®y)Š18”&8K¨ëWÆzb[J6³›xqÌ-›Ó%éÊjÄhêŠÙî.V䈱ð4ÉöpÞãëYÖ×[Ì­r12a¦ÉÕ©°Œá´7#ù+ì^¹Î­gkÚ®ãÞa—ÖœÇy‡ºH”ˆ¸ ©+‚DRq „ä¨|Å­kW ÖñîýûüÑ»û\™zž½ùÆM^{ÿ=¨S•YÅáÕKBÊ‚,ÝÏ@0Ç4MйÄ\¶G²ÿSʺª j#{j§¸Ô ra§ Ê]Ðê  ,e ¢T•”eb ÊbÜCÒ *wƒ_zñ7®ïòÒËsÚ¶åû¯®ÝØá›ßzš¿÷ÛÜÝÀï~çM¾þ•ë|ñó×é¼èW/¸w¡Î¡&R2„"Bèo Ã躎åâ˜`ñà+G%e~xʳ3ÚÒÈ–,KŸSŒ¹«Ý"×n\#Yä÷ÞfÙ¶„Ψ«)u™FRTbL´Ý1»;5“YÍü¸¥™8œWb×Ûñ:È®Tœ[׃ëÅÀá¬Àý…oü˼õÊ÷˜ï°¡Ò9»T´¹Ê>FåܱÃ,ÏéWQW­½÷ähML6‹ }Öq–Sù¶âÄõg?Ã7þí¿Ìßù_þÚã îòó ùðþ€üüϯ<;åëG¼ ½Â9OÒDêÒÉ—Þ³Æõ^H”€§ƒñ˜™Ò4RÑ „2!L‹Ýòl6eº»3tPîß»Kèžb6}Š˜©öH8mñx|êØS¥ò5ójÂ!JG@h©êDr&Ó«ÜzæÕ¬áþ~d¾\_ìü_Ð<üFë:ù©rÖ 1x|SóÜÓ·òÌ”øâgžáÎÁ}~v÷t ž»~ƒçn†7öH–‡öĘÌk,ÑÙ”pÀŽ)SŒ:•á6æ aí‡ég‹”8RX%‹ɦ¤Üz˜¨Pˆ$[ )Ašc) a™'ÕاÒQ¡ÔÄ®¡ì`v›ªÚc2™1Ö|æsžoþúŒ=áŸþžpôÀóÛßyŸoý&ü…¿p“ú;o³8<`6­ÙÙƒêê)c¢)Ü4®‘”îæårA;Pð^h|V¢eÅP?Õ¯8¯šáTI±#´Ëì³dy^Çtw‚:ÏÛïÜaq0Sbkxß2™6´RéÒOÌ‘¦QD•ù<à+¡n„²Rªï¢^ͦîI´Òø¶ÑK°MŠyÞkïÖóüûå¿æoü—‰÷úê¥D#rb¨‹ª:­Þ$"„nÉæ\í!ò ü‰Ç˜Þµ\N/ «ŸþÜ‹üÅÿô¯óãïýÃ?^TDsæù’­€½U#ð8ù„ËŽ[x’mÄr‰¿+£rd_[¬*?”ºÔ•¿'Cÿs_CN±Ë 1û£˜™b♋à$«PÔ);»Sf;»$‹t¡cÿÞ>–jêÉÓ$™"uCå|L¬¡r-3ëHõû~Ê¢òÄÐA8D«?iØ»v…+7n2 wîÚñÞ‘|MU»¬£ЦFÍ-ô­`šç(ÔuÞâ’?Þ¿ÏûKå O]c2©ùñÝ}~|?â}Àë.–ò G@ É©>ÂÓÜ6ˆÐÏ[^y1uIé0Ž5pLÎ:´”et¸aóÄ<1G2…Ø’b—‚µXâãLp©F¨‰Tˆ]E¹Šè³4“Ûì]ðÔuew/Pibÿ òý¿û<ÿ\ůÿJÃï~ç]|ÀoÿoòË_R¾ñ§¯€V,–‡¼úê+,ã}úémý ’­³òˆÖ‘ˆwB3­qåÈ÷FñR¢øY¤ª<·o=M]{–]ËÝ>à½;ïq|¼ r5¯|ÿ ¦Óvw®s|$¹Üdptܲ»[3Öφ£ë²Õ»ª#tmD].1õszKõµ‡¦X{¯œ{OÂE éïýíÿ{?{¿ü?þ-þ×ÿäßâοz1.¡7 ±³Iá­óèPÒ 8:‡·Š¬s"“UIøbKßë·øÿç¿Íßúë•üÎÿýѨ±l=_²ýmrÎ"ÿaÁÁqÍ8¶ ‹Ë„¬~àÎQ?lÍ mˆÿ¹<$•½]´ª]ÇÁÁáÈb`efÖì¸ìW´ÜAu3Š‹ì!T¾æŽ.dƒ¾ººÏ•«Õ¤&YâÁý}ó9F…÷_ÆW7Q7¥©êбã„J13¯+溋6BX@¸CÓqõ¦ÐìÜ`os4÷$–„0ªIE”܆Oø©G¦ŽhR-Y/ûü­§©|ÅOïÞgRÃóצ$ïÜgÖLøô[¼úþÞ;è\‘n°ì Ô$£Ž‘™(•H–iZBRWÆ¡zBö,ež:æÅ‘Rî[À GY+Á8&…¤Hò¹ã9e5³ À& Þ*½J%Ï öU}›7¦|á3Ÿù”çÊ^N¢Þ¿øþ—¼ùn u_{1ÒøcþÙw_âpþ#Äݧª:*—èÚcBX–YÏ‚ !ƒºYD\¤òŠªÃM½¥U#U^`tEÑdCoà Ï?8嵿I¸qã1$~úÆÛtm.‰:ž¾}¶ Ü»wXLÀ ï…éDi»ŽvÉ¢‚® … Ny1`½EG2ƒUз ÕŽ\¸´´U¼SF–~åÛÿá/ýçüÍÿî?ã­W¾w&9Ý—˜ä”@bçÌR¶F´ÿâo¾Äÿðï}“n~´µÛz­„´6³ùÛòû§>û%þÊÿöø›ÿÕÄËïÿü Â…¾=;¦?&uÚÚõ•G8$»|’q)™«ô.¡#PJiôõû–̈!0ÙÙÁ©²\¶,–Ër³”,¢ mÕižÍ ÙšyfF­ž}ñˆ÷(K¦uâêõœS9<8"Ä0¦“Ï£õç¨ýŒÉdÆ^{Œ× KŸ¸æ,ëkˆÛÁMv±tÄîôˆë·üŒýƒ[/ž!#±D¼Ã‰Ã|îZo¸„›LHÉÑvä™Ó®Ê¾N>Oƒ»±7£j„¼õ/½}ÀõÝ)7w¯‚Uüàí#ŽZÉ¡$º”p¢LE˜ˆÒT£œÓ% IDATy°P#>Awœ37cçP!ÄHKú Š ©¬^Ku*w¤çý“h¤$ —rs¡ax«Øu†j‹³ { Ÿ"ê/qóÆÓ\¹.\ÛU¾þË “‰ñú ]à™5·oW¼öÆB|Ÿßûþ;üÆW'|óÏ5|÷»‡Ü¿®]ÒY‡Jìvmd¹héBD|Ä{¨WÔGUV±÷?J¤X‚oŠL§ö®^áþ½}îÜeÙvYosÿƒÜyï$Çý»gŸ}š›·žæ½wïC2Âý-{{“Ù„ããœt!:œ7ê:‹ºm42Ámåc‰µJHsØÖ¸±¦òmïåð·i— þÍ¿úßòÊwþ¿óüOÄOý¬çì³ïÞs®9¿o~ß65} é>Q„dí§Xä©ç¼˜/ýÞŸâ-?øJþÐû>ûI`×bøŸ Lpãí§ÇH×}ɾ,¦ëT’©j)Û­ °ÅíJÂï–§Ei¤XXXÀ Æôûv(›! I[Q ë7‹u¤Læ#É È|I#Õ´gÖÈ‹1ëkë㦌)O£ž=Ÿ,­QKç¨tªàÉ‹M’z /kÄi›XlÒiŸE¦Ö7#ÆÕ<ÍöI ëˆä:N”x©ðqB× dbK°Âã”G¨¥2J¨,4ÎUîµXhÆ<¸²ÆJ 2Eˆµ¸†u EX§ÎÒ”¡Zç£$Ä]z„ÅR¨”‰o`œFØÍ s᪠íd§+3çÀé)Ø<°ÁSx .ÝI‘Ô¥&Ù2aÆÍâü!´|ÝÚqžu{—[OJj™d}½B*ÁÜœç¾+î?]QT†ñtX[^ãž{ïÅUçrÙYMY®1m€ òæUi0: ®Å‰$I$Jª0)ïÅN0õž8Šp60Àã¼ÁyÃÒÁCÜvÛíÜ{ÏÇùØÇïEØÐ_Z:H£ÑæÑG/a´Ã{E’Æ,,ΰÑ3VlM§)d5ÁxØP[•ÓêÀo‰ûawª²)í§XÛšA~_ΞJÂïü÷[^¯cß™?ÈK¿åu$µ&¿ûŸ¾««}W“â1œ¿z)z½ÖÅ”ð#ï9Ï}ÙÑÀÖâ1d¿wGÃÇŠž“Ÿ÷bN=÷¥¬ûyço³pòvÊñ€þ•óŸõêà)µ¶ù§0´çŸ‹éñN©á‚Ä…’Ó‹Û§.3MvŸÏ”Ó‰W­ UYÐètÃêv õàÆ!Eƒ8k‚è’©˜Ô{ÖED$( ÍF/F\¾²B1 T„PJI=Z¢V{>µèI£K¥Çld-´²è|™¤u(nSkÍRW—qr™•MM^ÎÐlßNg~m'dÙK7´·¢•–ˆ¸À¸ÖD§qh„ô "Œt[MnZšáÑåU^飽æþË#&³3éÍã\AJDH!‰ñdjR¡D"ÆË&BtðÂcÍ PT“%*ÛÆ!‰ýï–)œ'ÚjÑyÚnZ6øé·Dò<‘¸E¢J¡s55Eªœdè•k‰HqœZzŒV²ÄÍ'Ûœ:!8s±/9u,âÂ%Í꺥U÷øbÈàÒE.u-·œòœ}äA6ªóx7æò¥1ΕXS…ä-CRÈê ¼ÝðN€Ûµw¥"–,r`i‘¼˜påÊe.]¹Ä(á½à¹KT…£YoÒiô 1kkšV+¡Ýžas³À#p^2Éíô2ŸúEã(K‡‚`p\輟Jˆ{·KÃÉNq°itô»þÝWÚ‚aý¾Ôf‹«Œ|öo½á®0ßN¸åÀ,¬¬1.=gÖ+ÖÇC„HI¤$ÑyO‚ ºL"šÃ‘2ñÖÙÁÊãà›Ô”¦2—1v„µåÀÛ oaí¶VI¢ R’Ôú)MÖâ•ÃKå<¹ žk.ªáTT¥¤ržùî)Ž8Áåå&ƒo¦Š9β¶^ñèiËm7I–Ï÷¹¬WxÚ ËÍGÖi5súÔ6Ö¤(óЖóRzâ²4BÉxjò´³B D†°:Å;„‚ÃGi·;|òÁO2MXZ8ı£7óÀý²±ÑgDŸÕ+#nºù&>Aqú2á«K–W&t:mœO郴‰µaVAÊà¢%ùd«RÏ-=¯`¶Míîw¿ó³¿Êýíꕺ”;&CûÅO±OŸy²Àôaª‚?ùÅ×ñ•?ð3Ô;=Æ›k˜ªØ·G½W.)ôÿöËï¤wðùpƒ?ø –/nc„û²@­ÅYó˜ Í8«£¢˜3ÿÀãÙçxù÷ýªÉÿçÍ?…³š—þÛ×ræž°qéÌG4à=6æçbPþlNH?‰j"Ú¬Ú^)]G3ÞÆÒΖ}ä@:(ÜN£ÑM9€-´™Ì Mêågsµ.>‡×®‡J¼a÷%¦cñBÈ`vâÙ3)yµœtaŪäÔ9Ú]G„ªé«=0?7KeáF"D†J¸˜FãNÚ­`Hi4Z4ë©D›þ` ßC^þ 9 Ì AG‚P3_Å(>†žÊ[ÔëUm°¸”!ÒCä"e49K9~!ÖñQFï…t<ÊyDTÿè´Na%I<"¯,Yk‹BÛ!õz›¥ÙÖíFƒH†ùˆ³+WЦäøBÁ¸âB¿D›ˆ¶ÌèzAÛYb盧ŒAJ¼‹™ˆˆ‘ˆ™èë=±è’©ã$â ‘•èê e±‚5C¤ËAäHJåi&Њ-)¨{Hl˜ÉKÍÈDŒ}R¤YÞÔP6"šxêFò…·ÞÎRz„µó‚8o`ú1Þ7äÀ^¬¸táQ.]x”ÆÜ|Ó˜²ü ‹¬[å‘G?ÉFÿ ëý‹Tf™F¦©'ŠXÅ(©¦âÓk Ó+Á,%¥©Hj-¾‰µ•1›ëÞ*ÚÍ6q³¾¶4\J¿_2;;‡'c<ȨŽqA·ÕÊÈ‹éÕ%<ÖjòI‰÷!ù”EH@`ð^‡±Õ>š "¦XÍvÒ˜nÛMÓœ.óÅ–áž»`K@îÜ'âÆ)ÛÏ'Èf°Æp×K^Á¹O~˜2íA÷÷ôýÏ~⃼ðë¿‹õKgùèŸÿý•‹ùy÷½ÿ]äÃÍënOmžÿªï¡åãåÇm]]räŽçqä¶çpâ™/àÂ}æOíG¬^Ú9Ð-iÿm…à½çé3¯~~&ƒÿÕïû™þœÏòC )Þ°û¢rGîB¨$äUßõªÎ&Ê âH $ÛŒç·ÀéW†{L0;ÛÅAP"D(©7^ÏÓ[x >í¡¢/2q5¬ÙÄlü5 ýwÌ2 ƒ$–‚RJúÑIòî×"G‰„ –B­nI£’¨Ýc³ì1(F”ùÃèâEܸ™öÂç5RšÑTsÈc„؈ •I²•¨È“eV¶¨ÕÛtš-6'Uµ‰"'U3õˆv’шSª¼FƒŒ®WdÖ Z8ð"[yÁÈ*FHJJy|LCºƒ$¾NeV¨Ì*¯ÇRÙ'‹FÔ¥¡© .E–sëC¡9Aá¬R}RC¬=óYºõ¸ÍЍ¬Ñ‰çyî·pä@›áêÉ„8`ô Eq‰ÛnS8w–ÕÕsîÜ=L&XX’ôW8ýð½½J£^ÐL»LŠh{Q!„œJ€{”’tf:,,-§«ýºŒèµç8vø0RIÖÖV±Ú`¬c~nïcÆ#‰ŒZxjÄI“¬Ö$/¼¬£Tбž8rHe1Z#Dx‚Áè k4Îé)-ÖîT Øé¿n§$¦ž>T~ÏGìÒÁÚ¥¥Û’ÓBøZ¬~úÁn÷ ›—Ïrßßü^ð5¯¦õm®î,òö¹g‹qŸ¿ë­|ôÏ‹>î§½úWÞÍßýÁo\w{­Õái_ðr>üŽ7í›dsçK連Œ(F}LYpþ¾ñŒ/ý>üÎ7ó§¿öc{Ðg4<™¤ñé¼þç;®ªrB±{Õ#‚?rð;–AãFÉ0»ºË:Rî)°±'P3E ZÚm½ÏÐ0Å+™ëbœb80Dq™FH×dþЗ4¯%à½Ü?Kºù:Õ_“’£eÄG_Ô0õR[¼›Nç‘TdYŒO$•oQˆeU ‹³Øü¤¨ˆê¨õî$jœÄË«Çà Jy¬a¬CER(œ«ð8Ò8ãäÒ<µ¸ÉúH£üˆDô)&+´SO•O0¹ U]†ýicboÀ‚³rDå"J'˜ )½BzÒˆIU›Z´@Œ aDì/’±NCŒh‰ ¿AêKRÊ ¼±^Rؘ±UŒœ§2’•g±‘1_O©ú#̨àÈL—W¼ô9éͳv¹¢¡d2åâ¥5²šãÔÍ Ö7Ïãìâøãñà †—™›lôÏ3ÉW—Y_½Àpxé Ò8BJB!e¨¤RAVvPXG»;G¯·ÄÙsËH±´°Èh8F—%“ñ•ÕufgçqZ2K*b]…ÅEŒm¡m©ZÔêiª(J¥4RW8g+¬­÷Ó¤àÃtuÀ^q?·õó6±Å\Ú© <;Æõ»= … ‰Oª@¨Ø²Ý¸ÛîGm+¹î—®ùÛžëbËOÁ‹=̤ВôÛÕÆî¸Tæc¾õçÿb4àÊ#÷mÓG÷{˜ªÀ;ÇÒMwÒš]`¼¹rõ Åvéñ¢oz-ïû¯ìZÍ‹ï$ßüKï⽿þ£Œ6Vvéô;\éè]ŸÏ+ä7Y=ó ëç¢÷ùÈ;‹sŸüÐvËqÇÌëñ™X7çãýv\íöù^׫2¶*±­}Åõ™câs=S<^2ܵM %Þ°‡Ç<5QrÇ€F*…ŒC¢Îm·ŠÄ®Õ >HêDQøcû]IB‰j:ðÑëu°$  ã˜DE4z_Bgæ$ÞÆx—‘•j—þ9x+¥~€° ¼$âô³¿†ÎÜÝøxžÒ‚)F(œlÃùâLyÄ„´;GÚ½‹8;Ô¾š®ö4Â=žÒƒ›ÀÓª): Ii2Œk0)­t€¨–YY9Kƒ!‡;™O(Ê…;E¥›¸Jãu…wë‚i˜TV(Q£&êHš@7ªÓMÚ4£ˆ¦(BBPcjÂPRû ïc1ÖE”FPEQ9F¥ ¥Ê!&%©wÜ|xž;OæÖã9<3K±V›=6,-ÍG1yQ'Bô Ïsà@ÂLÏpéÒiFù–œq¾Áx´†’%qY¬ˆ£¥2„¬#dŠT)Jex™ â'nº…´ÑæÌÅU&£ [Yf»38£9wæ›#Ú­.³³@»ÚuHÓ­™%Æy/Pè&Ö¥,-Õi6í–¢Ù°L&9ÖVQ …ÆÚk4ÚTÓ¤TZ³Óg˜ùp~7 ½5u·›µ´P³Ë© !B¢¢iE´«ZØb ]­Ñ÷x-¦kI©bš öÊV„J^ì˜÷. »Ÿò„¿ê8¹ös¯>þ'û|Âï¹í®#·jº¤.YYEÑžkÇ(¥pºÄTËŽy• M ±ôÔ"0Zà„ÄO „Tà%ÞG8«Â°Œ¨uŸC³yFž¤Z'~˜¼ü›ÅǨ¤Ç(EgÌö:¤µgb›ß@UÂ'¬¶Å(U`tN1¼€ç‰9*žE¨£Hy(xQ‹ o$"I¥K„× J*’,"Ž…qøÊ¢j ½¬†²šµÍ‡©9ý~Ρ¹„f,mH6ôa|:®F›eÖp$¨8 XtÝ– !£((€&ÔdŒq¡wßy%Ç Ñ´“Œ«‚j:q\XCe5‰‚»ŽÍqêðeiùàGë¸ùÀ]á•3<çÙ·ð’/|6¿÷"WÖ¡qiÌ¡CÖVÎPTx[0[î¹ÏrâÄÚ½jþ~¡?¨€:q,¶ô¶ƒß3aÀmœ{P]VÌtZ$‘¤ÙጊèÛ¡bŒ­ÓlÍÓj×)WÖœ:5Çá§XÝÒ%D–V ŽŸl0–Ó* `0ðıAMXQäÎU8[aLÀ¬ÕÁhê眙Z†ç– i`x…9Ç4Al1”¦„ !A µÍleÑôZßšèf/6wC‘]ï#®åÞŒW3¡nWÕeÎýì÷ó‚W~'ÿæ?¿_ùÖ_ÿXœãͯýZ^ó–ò/î~5ûû¿¶ï~sGnºî{ÜúÿŠ·ýßpÝí/ü__ó¿üß’Õ›¼ûW_ÏÇÿìí× ÀWÛ„î_y‰}íD÷ìÿ@àë}Þ5–7‚9<ö"ž`ây’ÕÒboµsÉ{!á÷‚×;£ú‘’DQ„Rjp­ÂãË’ª2»nO ´€V’FnC‘ ‰aÙzÁ‰ãG¸´Z‘éˆvëÒÆÍøª ,/SŒOcÅHªéðYD³=OÜ<¸¼ }R6~„5çK¢dDY.#ü€¸¦‘qW%® Š2ð1B–i0Þà\TŽF=FGåíºäàB¾a}Pwtk†Ù¶f°Ù§*&ÄRPkÎ#³Y´ªcMãj ѯN`ÖŽÅM"·B¥BEcD”#DŽ.K„O²Ô‡QbTƒHx¼-ð®DE–ZQ¤(«RJ–fZ”•asP@áØX¶Ìu ãrFýMÒ²¢^Äô: &Y¯zÈt™$¤ àòP„ ˆ¤tH!C{Éœ-ÒÙtàÊá]8æ Ker¬/)­fRiŒÕëÈ­ÇKhµk #ÊBsÓ9IL3‰ô¸¤¦ µJ2ú3ŠC‹·0)áÈñ듳LÊ¥rˆ¶C7 Ç}§/ÑmÅÌÏ·0º*¹N­¨lE…ä€rÌÎÎPÏšT•EÅ <|ž¬ÓÅWu>{$Ž8qâ6–×JVÖb²Æ1ÈrÇ­sÜz‡'K#šMM³fHâ‚<Ï)JOž—Œ'%£aEžkdáÈ'¡U$•ÆSá\‰±šR´.1ÆbŒF›ÀFÒÎ?añbÊ<! Îj„p¯Ci ž @Êh •[j£>`ÓB`ÝÞ–ü-ÄÍ9vÉKø«r¿.Å]ìÙãú+¿' Þ÷ß~]¼îñ[ß7—>õñýYJýN–NÝÉó¾êÛøè{ÞF5]µ2½VrÿÀ-Ï䎗ÜÍû~ë§öÒ]gæùòïýIjíð“ßÍ`õ?þåÇ>7ZîOð<ïWÅ}ÎÈ7\¶ÞÀëý´˜®rvÚm$hª K“$1Io÷^e’â©òjû5F†" Y‘¡<ØéÚ)«5™Œ,,"j÷ÉÒu´SM©+F#‹³uÒä*{:ˆF'¨x…(^AÅc%h¯‚x“¤ƒŠš™"„{™T |‘¥)^ÅÔÒ36ÞG4çLÆK»uæE1¹L¤‡ô¤ÏPJðDÔEÆ=I-ØuJ ”PÅa@VH¢X¥¼ >@”z"YÃø kr¬¡mN¡ûcÉ£ÒÆ•hQSiC^y:˜ù^ƒ4‘^LY[ÙäÈ|‚4°¶¾Æ-Ç«Œ(Ê8ìg9{Ö±’wX:1ÏéWY~x£Çë´š ¬É­]¡M‰3±:öAô[ú€Åž¸QG)ÅòÚ€á âÐ%ÙãÞ{ÎO Ž^äØáÛ(‹)R´gâ°ßÉ3Ÿ3C=Ë8r°Îá‚VÛ#…Å{C¥¡*¡Èå6¨««ÝÇ‘¥’ï ¬ÕEI‘W”ÚQx‹ö§,*¯2 榅 "fœuc°Tø)öàã 'ï„ÄyoCM0ôtÛ×yH~»BØÜ#>'ü.R«ØE ÷{~ÞnUíá•ïmV_|ök›\ÝÿtÖÞþF.<ðQ^öê×sÿß¼‹þñ›®Ù'Îê¼àUßÍí/úJâZƒ÷¿õ¹6ÕíÆE$‹7ÝÅÅ>²gvañÔ|ÍøŠQ¥Ïyù7ò¾ÿöóXkž²¶Ê§S\}¯gaº_[ë-Yˆ§ðµ7ð•¢í„pé>áˆæT¥ÆYG’¦ÛK*ÉH<è²Ú¾Y´€‘‹HDD,!ò"ÈDÄ),bqœ0l7™ô'c…RM²úmÈì0>šE% Ôˆ¤U!|®úÀy>ùè-u˜ïfBJ0“ •ɉTD£žQU’þdZMѬ9ã 6&c’Äp¤;K=K¹÷bI¦"Ò,e}s§ µ·Í/qîÌ £ËŽÞr~sB>Ðô×r-Î3žX†Ã”Ë— †¥…õ$bsÓ‘RâuE3âÀBFóèýQ‹‹—FŒ­ ×ksüH—áƒË ÊR Z”‰¯³ØÍxÆó3úeIKҺ͌CK]nûÔ™n‹ÙNç3mI'±Ìd¥ª°´vmÂ|A˜-A×yì>ñSPØ"pÓ¹„à±PT!…fœkªÊP–€öÎbqh£‹ï¶<¨-R`9ŽÂÚàMmŒÆ:sc=ÖLgðÓäåöz!ƒÈ¯}‹¶½Ûÿ|_Ö‡`;iì D;Iàj?á÷F‚ 47ºßË^ýÃÜþE_ÁŸÿæsÿß¼gôžíoüÖ/âUox3¯úÑßâ?û¿“Ö·M_ö½?ÍÝ+³‚xÅëþ/~îîfS½Ýãë~ä7øû?ø ~ó_I{n‰Áêå}ÛTqšÒí-p覧ñ•ßñ:NßóþûOÿГ ¨5 æ¯mãíGg}¢ÿ3RIücvÝž ôH´GÐq—¾»ÜâK±—⻵rrž¢¨pÞ“¦ Þ{T–¡¤ÆVö„!*§¨Ï6ˆ³ ï:à»HßÂÚ:Þe(Ñ ® ’¨ŽC¡dX¤ˆÂPK Y¦(KË$Çgôst¡™meÄΓÅ1U]!ª’¬nÉ¥!¯N5jKîj(QŠŠ[ jx#¬Ãø ¼³hg±.ñ±¨a-ãÒÑmIZ-ÉÚ@3œô: i£B%†Ëù:Q3{ ËZ5 ×&ÞñÀeíGæ8ºØ¢WÔ„âY'pîÌ:>÷Ì·›ô³ E+«šFk–Ë+}>ö ÍÂ|)%{Ôã:­Z›^/£×œ¹0ÁyDZã)ËʵQÅ-ÇæhÕ\XÞD5À5á–gu™ÛP(å‰bÞ2·(™;Ø`y!‘(•¥-Zí.Ýn„õ‚NCÒ®{fj‚vÝ"a±6¬Ì­ A×MŸ¡ÚsaÇhƒ1;¿Ó•a0Ô¬ô'¬*ƒŠÉØRVSÆ’ôï+*]M¥¾Ã5%1ÒÊéÂ1ÐUµÙrw“h£±&0´™úQo+³Nõ‘ÄÖ°g[pwKiGGizgì£O³e¡»õZ±‹äá¯êâ³³ =þ¬b½çEÿæ¹rú^¬®Ø¼|vÏ>oÿ㠾þßó¯þýæýoý®œ¾w{Û[~ðn^ð ßÇ{ýG)¦ÓÍÆ˜=ÉáÏÞ¸SHñÕ?ô_ÉG›\xðc×$€Z£É³_ü¥¹ùvê­.Ãþ&oþ±ïã܃Ÿx­¡I¢âjM ±7Y<ÞßáFðžO;I|®ÌÏ=CWBò±xb¯.“ßÈbë ›©y‰”x‰Œ#0á%‰ÊH£ª‰|µnïê „¬¡âBÔÈj-²Z‡¼0a OX„PUCEpÓ½FFKEøqEê=5Îk*Ú Zx ïxIU¯±V V*A.Sl\cl%£ÊSIƒH-£ ë“+% ‹=ˆSÖGKÊÉÃ-ê ÅÅõ!qb¨Õ=Ë›}’ÄÐí÷¿„Ê<í®äÌú*¥.‰#‹+-8¥AÊá™KÝ.ÃMÇdd9°Ðca~Ž8©s~¥by ¨t†uU™!\,®©KK³Äõ6¹Ë8zªMÜMùÄê„qä8x÷½ù'höyÙ«„ ÷˜´Ñ⽿ù¬_G¶ãë^û¼üß}ùhÀ'?ô~þî=ÄGþâ]ô×–Ÿ4¾ruÀÞon{@Žý‡î®4Ûï=Ÿ(3jßkà³­ÅôdÖWs´m¶ëð~WßOl—á[ Z ®,Kœ†jAÄu|)0ªÁ@ÔðQðx*!‰-qRC›Qv´Ö¤*+J#ˆóSÉGæ;u¬Ñ¤EIKÔ‰ôk-Ò§8 c‘Q‚ŠÒBVO)☱vdõŒ¬– .eƒQNS)f:—ׯ '%óYÄL+£( e)Ñ:£*#êJz˜ä9+ý’$±”®D¢UÊåÑ:5­8ÑêáhÔ%Æô=ŠF—Ì'ŸaEŽ Î …"ó’’„þÐ28=da¦Åhls½fëdÍ'$Ëëc¼ð\lsq¥d~±N§éHø_qqM­kÐkƒìú`"¹pE³¶¦9²˜2.«kŠ••u¢³-6ÖKb•‘f)JÖ˜k´¸íˆ¤“z3ŽnÛШ[„ 7€µlî=‹Të-ÆX¤Øš3°Á–Ó»àp§-ee)µa<6 †%ƒQA[mŠ«WNß»§"xã7?Ÿý¿ÀÓ¾ðå8c¸ùù_Æï¼þ¨ò1§?ø^~ýÛ_Ìk~ç¼;krÏŸ½ €{Þûv<žÉfÎø¥WÝÀí/¹›¿úíŸFHÉ3¾äë9pó3yáÿòÞýÆ×ï{,Ý…ƒü§?ü0òë?Åó|JÞ âWUÛU{+=ÁuÚP×P™¯ówüÇ®ü§‘ ƒ»x¶Á]Ol•åb§%¦-˜í,+#Œ %JÕi 6Ç{ÏÈi  p¤iBw¦‡”Æ&ÔRÈÒ›L¥©ëŠTk²4£!!w4b¢ kç†F=£´ŠõÒÐn×QJYcd”P¯+¤R¬ö Šª`®ÛDIÅúFN-©a+N±¹Y‰ Šœ£*F¬oºÈ]Ÿ±Í9»fXìeÔÚ–ÊT8¯8qx†(VŒ*‡"âöãI”b8ÑÔjMµŒ•¡a½T83Ûm ²…tz5ÂL3â¶[Û\¼RpæÒ˜Þ\ ™J¸<¢UOh5SÖdžµMÃÃgƬ\Ñ,ôRÆ•&Q‚t”“†ŒBð,Ç>ÜBtõ¤,k V+l™Ò¬×ˆm‹Z*™;sl!¥Ûƒ‹’V#&M Q<”ðŒÆ/Ui1:ØšV•Á[ˆ4IäIS‹¶!p•¦(‚ô¸¶–ÁP3žh £±Fcª‚µãñSޱ:'òƒU‘”(™bL˜€.+ƒu޲°¥ ?›-n?Õ ç@ …3-œm'%UÀä[)xs³= í÷ÞSb—¢Û@öV‹jߤpƒ7åõ¨¬Oè9M~ò3ßGRkðy¯x5U>æ¹w÷¼çm”“ºœð3_}Šoùå?Ã{Ç}ù‡ W/±òèÌŸ¸+}œrÔgþÄml\|„Í©_Ãxs•´Ñà¿û«Sl¡Æì¡,Ÿy€SÏ~!_ñÝoàMÿáùžxÜ–Ú¾­¡§*q<–ûžxìvàv’Øïû|.É.=Ç"¢Xî±Úkxà¼k˰­6” Þ*AŠ¥ œ¤uDQጤR1±LITN½Ë\·.¨£ÙI§ŒÆ•J¢,bl k#º³êg.®Ð¨'xœÈÍëk9¨”ÞL!£Üa=ôºMT1žhŠN«ÆÆP3* GõXß,™ä%BJº:ÍvÆêf‰q–N;¡Ó”\Y!•¥ž¦ÑDJ+è5šÌuë¬ôC€nd)ÏÆÄPYÇ\§ÁsO-pa¥âáKšV£ÍM‡:\ÙôÇŽ[&\^ÎYß³0E–O>:`¡!™i)>u¦Ïpb¸ùX“4’ØB³²ZQæš#‡Z\^¡”¥Ým™ëdÔ ¯fQÉÍ(i±º¤–Y–æëÌõ<󽌅9‰ÇÒjB£.°¦Bëm,eåÃðÚ´¶8ã0"e¨Œ R&XêõŠFݱ¶Y²2Ô¥f4®È'å”ïîÁò²b’™mFPR¼7¤¢Dø2ìCY•ŒrCU&¹¡(KŒ)ƒ–I^N[˜ŽHÖ†¢¬¦Ô6|¦ ÆÙÐ^rÞámÐa À¹›2޶LÔÝ.àí*i‹«&åü Çdÿ¤V¼OU¨wç8ñìsÿ_¿ƒ»þå×áœeæÀIþßßù’Zƒ—}ÇóÐßÿ9÷þÙ[A’¬±­å¤âP¥oMM«8ÁêŠzg–›žófœ¢3¿Ä{~íÿăÑ%¦*Ÿ’Šà©H$OôoúÏmÊZ¨Xú­ñ/‚ñ=bŠVÛ½^Õ;â|S,B*¤ r!eL%dµ”LéYMš&8£ð¢8¦Ñ®Qš²t$õq»ÉúfΰtÔZ-*ãHâ”V§ÃdR!¤ Ý®3˜LŽ&¤‰¢ÙJè œˆè4Ûh«Xœí‘¦5.,0^17Û"‹#6'£ÜÅõ,¢¨ ÆZš”v3Eƒ®,NF¯“2ª Ö fgô: J븲™ƒtš)ÖyF¥a#wšoÓÊb^ãMDÅZèPO3¹œÆMî<³~Ù¢'‚Ã-_0<|¡`®žÓîJÎÝ`R 9v$¦œŒÙØÌ™›­qùÊáa¶—Q™’bRbsÍÁ¹·œº…™¹y´kQ”I\qìPÅÅ„Cbf{ÄQ˜ùy´õT6 ­å¥Ç••LÆž(ö”#Ëp<½³šGz‹6‡%W–KF¦b<¨(«’8Ò*FÑ¡¤Dð».µ&U†Fæ¤ÂzÃQE^V †%›Ã’ªÐTU‰šª ï|ì4áØéät ºVUØoGjÃNe6lÀ@ì£Ê&•³Û?‡.ÝN[®vWkïøÇ¡¢~¦Äcº§2IÑY<ÊÜÑ[X¿øxO9îSŸY`ùô=7ôw¼èÜõÅ_ËÇÞó6«—X¿ððcúF|¦’ÃS,ö«ôn¤úùŸ:AlUrÚ.ò[3~ï<õN™ÔYj*ˆ2 qBgMºQÂb½IDYY´TÈ8eThòª"Nëa’Õxâ8€ÖÆ)Í‘RÆâ¬@)‰–H-ÊZ’4¦ÑlP”ID½Õ¥–µHÒ:—–'ÈHqòÈyiY^‘&‚‡gpΰº1AJ¸éø€š6ˆ» $BƒNê¬x ÆRo5Ñ•CWqVÇÉ„v³…ñŽÉ¤"IÒ¬FGSâED*,$­VÆòzã%³³3”Ú£„ R µ–"Š"œs¬.¯Òl692ßAkH0$™@v‘RH癟验¢täÅ uÄN‘ Ë`˜Ó®ÇÔO«™2Û©##CÛ%ÌvÚÔk I­"ׂF#Èg[e)mA³92ÌÁa'¹½ s‡K‹ $D Œ…óçÇ\YÝäÁ+c–—s†eNi N%$ÎÃJ•0×Z`©ã˜…T5“ÐbJÛG¦’ù4â®[RnyZ—Ö 4kžÁX‚×H)ðWO “&Aš†¿£6IAá`RJ$0.4«N¨ŒE‰ŠÑ8§Ò%Rzê0ŸF1GH²,8Ji)ŠÀ"ªŒa<.W›IE%Ь‘¨(B¹ ã$¼ÄébºÝ£+ÐHá±Îc¬£Ò–I9e)M“… ·>¸ÄIo‘ÒmýlÍ^8‚—cw{ioÅО?HgáHËý–&Ó.@z›ÜOˆO åŽ|ÈnôÕ^òbdzâZ}žð‚¼¿F1`Ê|[ŠdgIœÕHë-ÝyäßÙ>>¹u.Ôãd¿ï!ìðëýcžGï¯=Ñ×ßçZôÖ_sþ÷Úû]Eègg äêÅĵÇã÷¼y8/r—à ûBVþšÓð8yy×u±›iµE ‹¡Puû0´¬$ý+綉O, "9ý ¥Ô¶ŠR2Ì?ÈÞYm1•ãAÈ=_\Lý{… ­)) VUIšÕÀK†ƒ1qR'IRÌ”il‰ÕƒT…T:ø[K‰T ­¢( B8"©0FS«§c±šµ&­V%%smO’$¤IÊÿÇÞ›GÛž–õŸwú {8ój¢ ¨‚*@A‘)¢¢(¨mLCb4+&ÚYIZÓ®¶CºCK¢Ýi—1q"jHp@ ¢ "È$ÅP5×ϽgØÃoz‡þã}÷pÎ=·¤³zõr×ÚuÎ=ç·÷þßð<ïó<ß¡kk½2âÜÅ;E.4}åP™cµ§X*ò\Òùœ²gX_‡µ’I¿7 ·±FP%{­æ|eÉsÉZûSØŸt„62†µš[V N®ä\sB²±âñ]ËÇ??åmÜft¶¥¤fýXΰ”¼ìKVA_ƒwE š6<òPÍ—û¾ÁË)È@µßPf ÙSŒ§ -J®9‘ÑWžFhNŸn(/ . ¡×³äÙÌ:S µLºB˼¹áÙÛL-\ºÔ±;öTmE[w™ÅˆŽQÕâ û†••‚Öõö3Vˆ¡«£©ÃyOÛXöÇç3:ß%[ÓTÉÊJÃF°´mƒõ5·LªŠª®i›)u-™L%ÓiM5ut>&­(¿%½µtäÒ"èÒ!¥Ëy뤂륛Ïf‰`Á˸2),}æW~_ñÍ—z¼mÛH¸KUFôžNšNÁÇyYbhûYýEQ’eybp‹yÛj0|”™ƃ_A!Dg:)£]«T(­0Ú F+‡îº®cow—K—..­b¡À<— S¯ùÇÍåÜÈB •†_:G5ºÄ…?ÅgÞ÷¶ùÌ!+ú<ó+¿‰“·ÜAe“µ×!•Ž6²R¢Œ&ÏKò<'Ë2”R3|éÁ¨7KÀaŽô3eÝD¾]œ§%]¬Ù9 !©ñF»Ê’eðÌ_3ÓÑZœãÅïü”™0cH>Þq[)Jª¥€ø™®¯‰ÙþÇÝñâ¢%]YžQd%J/%Mæ`Ÿ9LbI%xùïËZˆhT%RK´Ô(­1FGµítÍXg©ëší‹h»÷È>ôÛoæSïzËãf Å¯I^ !畃’é{)ÑJ"”D…Æ!çtÜÐU¼Xr‚’ÉmKQ=Ê~/²bÛ€íë‰w­±Î¢”¦µŽÖ ´.0¦`T#DÇÉãDZ607hlÆj?Ã(C¿`TÁpµàÚëŽQM-—.O)³’“9MmÙÝŸ¤ÀY‹T0ègä…Äd“¶%Azòȼe¨Á+Ò3‘ uŸi»Ân»ÎŠ.Ø4Š;s‰ähç5–V[ !ñNÓäK áˆÙÂQ¨¥M"ËÍÝ8À aÁž)1c‰‡@+$x0™AJ9GA…p¸…•‚@ð3[¥»qÆ/’ÈÔ¾UJ¡•F«˜$ŒÉ’ä~\¥gÆ XïåK1Gt--TÈSÄÏi™,¬lždõøuœ¼ùNn¸ý+xû¿ùWÿÃ7±zìºø™[Ê !1Æ`²œ"/0Y†rI›ðÊ%sXr´éøù1sôX˜óOÄBž=,a ‚§ƒ¬Hнඦ¥„{\Cˆ¿Ÿ/üƒÃIx9%¢å +æÁ\Ä÷ž{'Wœ@œ‰9mZÚ 0!Ck“ÞÆ/!«Ã9A Äâo_Öçš· ’ѸM+…Vc Z´TtμG+EÛv‰¸J=¤p•S ò$)ä˜$´Š™J¥Ê•Açš••ªiC5©hk‡ðéb‘’²(Y[[Eª ïâM›—=¬ ÔuÃêÆ&Éþ¨¡?"eFgÆäy^Zäº (Íúµ9e¿G×B–e¬ z ÓIKÑË©ª“å ‡ã‰eU–?±Š*3B€Íc+¬­–ìO[<ž¼ô¬¯÷ie\×X]ë#¤âÂnEð’²¢Ô*¥b›Éšò Wmݲ? YϧÏ7\žZzeÇmFÒ/;¾ì΂۟z’k·†”¥¦¨Ø‚ð-ãŠ8Œµpþìmk.oO=Ó*°%¡ÔQkAÑŽ[ÖŒ¢;r­P@UWô 0ÉÓ¯ ŠcšÁÐa›Àþ^à:êZ°½ç¹¸×Ò¶ñVÂQ–  …®«¤Š¡à±Ö#EGãv.y¤’©¢+X]ôúš"s 2M¯ôl­IV†c¢U§µ‘äÖu-ÞE†ô íQ7-M]SMÝR75uSÓŸŒ™VSêiÅt:¥T¬­O™LÆL§uÒiªiÚ†®óŒ¶mã@¼S8ïèºØVóÞc½M7éÂh™ËàýA¿‡Ëgà̽wQíïàºnž|–[³¹…NZ1!y?¸Z+L2Ò:(èZX‡p Ù±<á[´#âý'f÷ ’±ŠÐ©’ng©ªŠÑhDÛµ8ëf„¤Ã0Ùª˜)$¸®¥XÝdãØ 1úZËpó$_ù·ÿ +[§è 6ñ¶Cªè9ºt–ÑÎy”RdYž’—œk: ñD‚P¸²=Gæ`''­Ôç|Ù£cñïYµ¼üûÅ6ÛLó î„𔂅<‡*’pàýæULxÎCJ‚¸èž%w9s|²×©…—ZyJ¦¶sª*gr33®OÓ¶ŒÇcê¶Á4{}œ¶Õc\+e/3])D,mFiIf4&Óä&Ãd&zB( –É´b:ih&‰ ×°²²ŠV:BåLÁ`8Äù(Z¶ŽQi°²Š’92Zç„k–ü IDAT´-x/Y®°·_WlnmRM%Jõ(Ê kau5‡ؾ¼OQ*6ÖJöF5E/c¸VPM->(ú««k}j«©;ð¢eu­³Œ& ]ð z9 Á…&ú+£ØÞ!޳º¶Êª—ôeàÆk 'Öc¿¹×“1ÓÛ@¦%Zy†«¤a:ç}ì¡·  è•ñÆ)r÷дéØ2{.íxâÜņñı3êÈsGÕv8ï9¾a˜T^–Óï)ò,ã– ޝ)NlIÖ6 Yƒ”÷®HíPŠ”˜MU+PÁsî‚çŸoM;²<®–v÷#IQJÉêÀ`„`sÕ0H°µ©ØÜ”}®€TqQW("ÍYù½`V[eâÛ.¶Û¶¥­›ù÷MSS×5MÓ$¯ˆšºª©ÒϦÓ)U•’G]QM+š¦¦ª«$î×Q×5]BQu62ª»ä6|bt/ÍæCë«´žžÌ òpEòd‡Ov@ûÅBT]íso~Þ+¹óeߊÉJ¼³q˜t턽ã׸ÿcúÅ¢hüwb‚ýõã¯<¤–B Ò\A¦A´wÀJ‡ ’ E,idÜ.†ÞZ‰[uŒª1ãK6É,8Ö¶¶è¬#Ër”1xë0…Fªë Ú”ùjjHÅ0ú@‡¥ ½²/ÑYŸa ¥ E> ×ÓL*(ŠiZŽ©€Ée©™ÆdŠô°tmGÛt {§r¶§5RwXáA0,2ê©Æe'nèqÛ3J®¿F±u\Ó/:Íy”´ Wjú}Éx%š))Ér‰V‚᪠_H1¡|àEŒ~„HÆ‹?z!Ãz.ÙØÈ7‹ndjÛø¹W(“°c!"È„'£üÉ 77´™ß„rþ™ÇNf?•3³Ît6µ\:û¯³ÂCx´žÙ9 ‚Œ=ö…z©8 j±ÌÈ,Àj­“GƒÃ8³ÖÞØG%ŒYÀŸµ—êªfZOS1K©]•¶9œ(ÚT¡t]7ÿœÃ‰Â¹E¥quhð½<ç8¨"Þ] Iu8¹.+ÍN(2]C‡“ÐS¶º]fwû6¯¿¤äÒé{i«ñÁqxþ,ŽP‘>ä¤Ç!éa´ÌÑÿ¾²jøÿ¬èÿ_„##ÞU+…ÖŠLkr­ÉdBS䊡ìãC éZBh…£¶ }0ª`µ—³»;¦,Ròb©7°(Êþ'®»‘õµMŽ[¡ 9—÷t`»ÍëoÅä½pðWðGŽJv .C,ù»fÊÞùGæûÔ_?ÁÊÖ5xg—¼E<çø,x÷¸•šÉ ¶®»e2¤è,cïÂ.Ÿ{x^}I¥ÉËyoˆÛÖŒÒù?ÜöÓ2DðÈPA`„¦Ðš"3˜Ì$x@ˆ@®5Ã^I¿×ChEÓµø0åøÖ—.î°>œ<Ù§×Ь°uüEƒáê'NgcØgu¥Gfò¸¢„Ðÿ­bà•2õù;‡VŠÌæ äbÉØ(ø ‡Tõ1òL¢µÄè˜lŒ¤yy©/?rl“é:䬲{ébn#fðö®`æOì(SÀ^Þv¶Ïjiµ&"¸ö-mÒg/”'—`‡ÜÏŽX|ÍÈ4ó6„£ÌpŸ0ðà‹Ç´ÆäˆªB.½ñ¬š˜ý|yu.¥Ä9‡R k-Zi¤ó®ÙõçtÄ|ǧ™/¥ŒßMf2ªÚÐ4 Ædäm>o-5m3ÿ~6ؾùëv:‰Ê°B€ |î‰Ë|îÈ6Ô,A\{Ç‹¸ñ߀o[‚Þú1þôÍ?L•n²¾_(ÍÓ^üZ®¹ý…4£‚³H1Ü<Οþò?cûOÍÏÉáB ¿¶Å7ÿãÿc~Ü­mø½Ÿÿ1Î}þî+æëüçlœÂ§¤S úüÒO¼ž>ù‹ó#w¾ü›yî×|Õî%‚]|ä÷ÿ=ùŽß˜#rîûÐ;¹ôÐg !°sæÅy‚Û_ôµ¼äu?„s© Õþ6oýW?BwæÁÅü%,î™›îxÏ|Ñ×qÝ3¾”Þ`c!’®1!%õtŸËgäcïüO<ô©%¿ë' ôV·xþ«ßÀÚÖµœ¸ñ¶8ÓBI¤Ôœýü]œ¹ÿ|òO~×]]/êºÛŸÏK_ÿ£qeç=Éðø5¼é;ž}`»Ç?feëzªÝË´M…ïº%þK8Pb‰ä_/d”(RÆ ó‚éÞ6ïûÕÿ…ÑöY°yýSùÊïüIðgÛÈ· ù­ÿùï\áïqÔã©Ï})¯üžŸÂä9ÃÁ“iþó›~‚KgN÷¡á9/{-eƒó|Ž®­9qÃSqÖò‘ÿö›W´ò´‰ìæ8 ­Ç…çs²P ‹^ìŠs‰²È1ZáñœÚ:NÓ5L&—É2EOkŠL²¾6 ìõY–¬°¶±J¯g"9Sä乯™ ~Gi²ËÇÍÆ3tPYúYô¶~"2¥<+ä;•Z0‹m¯> {²O­r…õå“h>^+a™ùúXûõ…îïãõÒ—?ÿjê¦Î¹XQ8G&³¹ÉlÞqX4röU)Ÿ‰É«u„þi­iÛ­5Ƙ+¾÷Îc›¨:+•BjE–ôûý­¨Ã‰BKÎã“¡N[M1ÚÐ¥šJs©4ÁlUáªo;”qT»;¼øÛœ·ýÜwÍÅ ª»|\¤”äe®dÐÙ )Ô‘í–¼PôÖ°Ö!¼¸ùÃø÷à™^>Gi2²•cX!Â'oº åtM…‚ÑÅÓŒ.ž¾âüI!é­l @IÃ¥Ó2Ý»teËxþ×'ÏûÚïD)ƒm;êñ˜e†`˜ñ„âØuOç•ßõ“Üןñ'¿ö¯èšj¾ícÝs›×ÝÂËþö³ºy¶©˜îí%ÁÙ}ì“Ã¥`ëš§rì¦ÛÙ¼æ&Þõ+?{ÕF$ÍI¼oR ºé䈒E8«PÈP3ÁHçŽÈ!ˆdG)2&a`ëÚ[¹áÎs÷Ÿþ„ÀÅ?ËΙغæ©ßF~FÝòâ×ý~ÿçô±ÛA&ã¦;_H–õÉó’Õœ½ï.øä‡çÛ<íK_†í·<û…ÜtÇKè­ ùàü2:+yù·ÿò–}`$•J豋.¬µÔUÍdŸÉ¥‹Ô» ÕÊN]ƒ–Pš ÛÖ z=2‘#ƒ ×Y®É³‚^Ñ'ÏJŒÌQ …N+üØÆR*¤Õ½ø+Áhs™ìæƒzÂ’·ÞËÄŒ®“/–ÃÕãõœŸÌðpÁäŒxï« G¯6,^ÌWƒv>V÷jˆž/¦yø¹œ´dBÉÍ9)ðk­çÆ90&’„Š¢Hó²<¶Ê’<Ëéõz”eAYÆŸçy·É Š">mÝÐNÇ´ãídL[Ç@?Û¶,Ëù÷3¦pžçH¶šÐM&ØéWM#©-íÓlÿ¤’ÛÐNGÔã}šÑõÞešÝ¼÷œ¼õ9¹8>q/¬ÇwÛ4 6ô¡sÙu×:lÅ'õWÄ¿gîý$“ËbEÔÅyó/¡è¯\q½,?¥”è,§¿~‚f2ÁVm5åƒ÷ÐV㈀\ºî|ùßä…¯ýpÐL¦¸¶‰m“¥6€ï¶mè¦S|ç¹õù¯ày¯ú[©—nKO±pßÉû+¼ôÛþ!+§h'ûtU³±•'•D¨¤%Àw]=ÁM'ÜøÌòåßø½W ÎÅ¿o<¦›Œi'cºº¾r»YKI,ÌÕpßuغÂVSºé[U„¦Ivºa´B’…9yësÐYÀtïÝõ~l[áꊮšâÛ†[žõåè,Ìûkeëwþ×àÚácr»ûÏÞÁÎ…31d§n|&æÃ¬Ÿ| g¼‹?þõÉÏz!}ç[xÖ‹¿aiaœæ^ZKŒIè%­PFƒÖx­è„  IÝ1íì2ºtžÑöºÉ.¾kcåÑ4Á34+º DÐ×9=]Ò=©Yd JC™KrÝÁ”ZhŠ,èžG!üb%–}^<"Èd2‰Ö.ë”$D8Èn=М÷ÓÐÖÍP+ !”<= 8O´ÕòXCµ#a•‡@g#›8ø0wDóÁ¼C4c¯<\m<*…Œ¹Zâ8 ½s¸rµduToýj­¨£‚Ò£›ÉŒœ¼é6^úº¦G¦¼³-Ašj—û?ñ^>ýç¿Çg?üßøüÇßÃøò¹Ôb´tuM3óÜW~;'n|úR§@¸cgqáy_÷]lžº…f„­›¨¿%$Û§?σŸþ Ÿý‹?äþ»ÿŒ‹§ïMkë:šÉˆ;_þ:NÞ|Ç¡H­Ô¨6`›†¶©±mƒëº…wyÚgÛ…Ä‹ˆlîÈî·q[T!xP ïÚÏd–çèÚš§½ðUl\{óüo¼÷Cï ©'H¥PB“™‚̼á§ÿãÁÉŒX|Às_ñ­Øº‹ÒLö¶ùÀÛm¾]–˜Ü0Ú9o,ë[×ó”ÛžÏ#ŸùBÀ_¼ý—¹ó%¯>pŒµÖ ­$FÉhÞ"2‚¨îêXmÐYÉÔÆ—F ZXi<¶uSGQ ðÁ²_°ûšÝóð¨žÐ[Ý"ï­‘VÈÊÇNmpêúuVW²xb’zl– ´‰¨™ˆðYô1•( (™‚gm(ë={#Ë#vœÝi°Î³±jØhzCͱ5M¯o=‰!y+‡ÔŒA·ëJx´žÙRÆÁ±™ î¯Ö묕ø“­‚%¥¢ýåxÙÁýA†1 véâ6Xæ\‡'Bö «ÇòÄIb‡Kÿí¤'ò¾ËóˆÃs ç\ ’\)gŒYJ.WÚNÎlj;Í©”’¶m‘RÒÌü³]—@±Èó|ð»nñºY›IJ9ŸIgX³¶ÖìopÎ!’¶O˜­½%x‰ÒYVÐ/û<ýË¿šÏ}èG"”æ³­¯…¸ú<ú:Šk,q°=zÄy˜ìnsþá{XÙº>ñT,²í¸ùÙ/æãü–ǼN¥R±’i;0Ð6üÄŸØoeržÿêïÆÖ ]UEÂ]–±ýèçxÿþ·\xäž-âknâo|û?bãØSèl¯bxåwÿ~õŸ¾þ pjA§æé/øZn{á«™^¾ŒíÚG¤æ³ü}>ùÞÿ2×’Š쌛žóR^ôšŒ³çè&¾ê ?ÅoþÌð®]Ȫ,!ã¼Äá$x›"ŽœIùñßz3YÑÇÛØ® Þœ¥¿vœg¼àëQ‚wHmÈzÞû–7bòÒµ(”DH…)zLvÎÏy5ÚáóñG|åßü!dPh“còœâæÛ¹öiwrúÞO\‘$ÖN^Çó¿ö;¨'S²¬ /sÞóÛÿ»Ï. ÈŠk-RÖßȹã9¹îÖçògoý…‰X+­æ‚RR¥ÕZºàTºè¤Q”EIÓµ˜<Ǭiêšý¦BxÏz^bt‹´ûÈ®†º&t;` ¬?Me4,Å`…æô:d•õÑ…ÐF¢V†x‘!²Eõ ¬«º¢·ÁÚú&&Shcñ.ÐZ˜L%£qGp%2”x«èBŽwÑ8ªŠû äâbBb-L'ž¦sL|  d#”=AfB”¡°‚`>H2s%¦ûjIâ â 2 ²4cÅþ¨å"#ŽÏY]‹T{! ’‡‘G_¬ÇQ ì0Æÿñf2‡g‡[K³Ä0 ÂËIbþW]Zé#Ûg³VcÔ«‘ó×Ï¿ I£›yÐ×ZѶ-{ËUPºíM–áó<%‡n>#³Ö!e„g뤋çwq5¥”œ#³–EÖ„(­ÉÊy¯O^®0XÛd°ºÎÊÖ_úU¯ãÌ=e¼wùÊc7‡F/<,¢ÒÑpP©$ÒJüytTûIJ·}::BJ>¶TžûŠ×]5AÌÎÛÓ_ð*œs¢¤Š‚z¼w`›­ëoeýÄSh« ÛµH©Ð&㽿ý&.Ÿy`>Äž=.Ÿy€wÿæÿÆ«ð_"„ÄÙê)ýÕ-žùÒoàSïýÝ+€MÁs^ùzÚñÛŶ›Ò9m;á/ßùWì»ëZ>ÿá?Æd%_öußmZ‚µd倧}ùWñÙ?û[gáGƒþ² Þ İýÀgŽÂ)áƒÇd%AÇ*SfYoÀî…‡žð½÷±wü:¯ýþNž¯`»¨±¤ãÙ/ýÆ böxõ÷ÿ lÛ!„$ÏKвä¿ö¯lÓÖõtÂÚ±k¬çÁOˆÏ}ì¹ó¥ßD3qÍSïàÂ#÷"ÊitIOE |ê'ú„¡W™FCž wF*\[QÂ(„é‘¥$ëxè­Dx¬“„Ô¨R Ì%¦då,Ë H”–H»‡ÖZGíþ1(-È”"XM¨öØž<„u6Ý:JL8D¡3Ñ`¥w\ž(.Iä_`Š"¶$”&H‘ ¥Š¤âè) 3 •“19 ÅÊ@£u@3#§‰ûS.ùe,ÁgPÒ™^L$ÈÁ²rÚÂÎpfp“Pð®ñ4•ãâ~Ã#gm×2ýlMÏd\{B²¶š1ÀpÅÐ당qììÿ‡cõ‚ýŽ 9‰¤N™’èÖÏAð{l/Éy…üõ5Cm·9׃tÓÔ¢Y òRÌ™´±•¶ˆ±½¤ðA€:ì®[ÂWÅ ÞÔ &Ëм • éÚ6•X!T&æ ‡< Ä™Ñg‡ÚžaÞ† !¤…TP›©/Ên±ÄÌŽ>+Y^Ð/”ýU&;gYß:ÆúñÈÊ -žÎ`ý8“ýy› «"Ω22 öÉ+2®n¥RˆäÃ}T+àì}wãm[e"öfûëÇwóœ¯~=õÎn¼ÿ¤ä®wÿ×CçQqÃmϧè­ÒŒÇ<2ËùØ»~ƒs]•T·söAö¶O³yüF\ÛàÚŽf:幯üøÔ{ï‹"pÇ˾…^o•j2ŠŠÒ˜²ä׿õtþÔyÁk¾C SR±¹ÔÚ™_ƒaqÞÃá¹ß ÝÄ‘x¨”FçylA +€ØþxR·¾ùÇxÃ?ý’®kžñ¼—óÁ·ÿ*—Ï.’Í©›ogóÚ›ã@]JŠAÉ¿ýG¯¹â>÷Öò‰÷ý.¯ý{oäßýä«Ù»t6FU#^÷£oæÿþ_9øVRÇÕÏ\*B±ä¼7±A•µQ%Ð9êPQd%"û©°"ÊK ÀhÉÔYò‡Ö“kD&ð´©-A%ŸéJ!uÔz >BV¥˜ ©JOA 0@é„4P‚‹–§¨˜\ð¡ÚÄáüQIl­hÿ9{£˜œ÷ìu êG¡4R¬¬¬á!Ë¢:¢ &“Z$ÑŤc]7—$¶.F]éc‹à,…ë<>hœ8ëAšF£†ý‰eRIv‹Ï¹ŽûÚ¹ {Îsi¿deM°²8u¼¤—{2 YOÌA¬óÕ:„#™4”â6B„9’yKó!?'àÉ9AO%Hn ú1¹4¿€÷bc ³ND·:ÂÂsÁ§À+Â6«à¥Vr ïH£D½Ç[FàZoâ§ùb°9“´—B µJ"°,œ6CÔ(©ÑRã”Çûè5¢”NÁÞ¥÷’©‚P©'¯…ÙpL$ñ8/b9¿qüÊr@Y¸ûþá®9ÉÚÖ ÃÕù’W|3ïøoÄuÝÁ€.fm¢+‡Çsxt:ÏZI”Q¸@ª 8PE-WpÞóQ¬m0fˆHÞÞ:nzö‹xà®÷à ŒxnÜbb2>õž·DõhÃÊÖµtMƒ‹øq‚‡ÉÞ¥ùüìj¼íßñÿPÇ@æÚXñm]ÿT.>rï2Bœ¢¿mk»ÄåPŠó<Ù..RÚjÂÙûîâÆÛ¿ï<:/¸öÖçÐ_;ÎxÆ _÷Û_1|,0ŒiÌ|y!µFeæI'ˆÏ}ô=L÷ÎP OÍUb‡§¸ö–gHw¼ä5dÅ×4mØß>Íù‡î¹‚ذ{áQ~ãý;¼ê»šéþeïmLB\ìÒB)„V)£&’L¥gRŒè‘(ÔÐ,Jç8!ÀK‚R4!âe‘Äà}†w‚à8Ð"™9Š€‰ì`çA:”ÎQÚ`½C:|lLIQÓ/÷VƒÇú¨:êEÀ W‘w€E)ÖQdPû€Ò:¾ÆEH¯’\œ÷H¢¢­‰ï/¨ ÖQ®³HW°]çâ¶*êÕ„[ "@c;p~Q‘…NÒYR •Á»(ÅÛµ¤$Ó —†Œ‡Ò«CÍæºÄHMg=ÓºJÐKÏ¥=ÅΨÀùœOÞ»A–­ÑëÁu›šµa xK¯ßPÎà) ƒ6ù}€6‚®¶ÑV\)œõh-©÷,Ö:ª:¶ñƒ<é'yš¦RÆ^’g9ýA‰ŠúR…`Ðr"KT d`F)ãdf$üÒ ˰àvFú ±’‰Wé@¹$í­Ð™ÂuÕµX+Q]\=k£¨e@h%1VѶ2.(h”YT'M^ !áÝ!õ…Åòk`ˆ(2—V”1IˆyBuÎa]Äø»;RÀ`¸Â57ÜDQÂѵ#ÎÜûAî|Ñ “¼ <ÿ•¯åÝ¿õ‹L»Ý”`’‚'ri?Ä<ÐäB™ IDATÉÍþ›3¬…$Ë$y·³V!ÕÒ<'ZI:ÇÞöiN\÷Ì´°‹°Ìç¼üÛxàãï_’å^|Æ3_ú‚µÉŠ^á\ûaDÌŠ!'o¹#uEIÃx÷§?ÿÉùâчpȧ'¾öüýŸF(•–ƒ®C—%Ço¼mž B"±m]w+X—`Æe2Þ÷[oZâ*†·ÇØ®¥™ìS®­ã¬EiÃÆõ7“÷‡óq%;,I ŽŒºG ðed¶ÆÎŠPI ôÉ=ªÉ>þ{¿Ì×Ï?ÃY¯,Ú”Üñâoäž¼›¶ž0Ü8εO½|@H…2‚wýú/0YÀ±›m=åm¿øc<>€ŽÃ»ˆº³gÒf"Í%"r#úJ“!e$)ƒµ5ƒaôƒ({E‰Ðš"+ÈŠ<–[YFžÈÔyŽJ„'©#Ì6HËg¥ÑzÆ’q"%!­UZÍÆ–M@‡4è$jˆàæ4¥q¡BÍYÊ.áð‚‹ r¢™‡ ’ˆ›HÈ ¯Î :’rªÂù í%…³q%êd”àµi n´¤µ!–ü™D¸´”:k(Š—œùlÓ¡t‡V ¥AÊè Ý4JÂêJFÓ)BëÈË‚ÌdŒG M÷(Á>B=Ó]Îùs‚ÑdŒs,OÙ댦ã¤ÂêÈ3Ã`¥@"ØÝ3­Æ(ßá䃜Î:¼¤Ãª©i:O¹1Ù#×C¼5(4eÏ`JÅpE±ÚË(óŒàÓI‹ ¦ t!PšµÁK#ÆUƒH蛓§6(ŠŒ¦±ä…Âuž½½Öu()hZKžg ‡%ûû{ìï×X×ÑucE¡ØÝpúôEòB°2,ØÞÞcgw—É´¡mZD…f4sþÜ>'^y[¬ô| ÈhŒu×Çfrñú¥fo4¡®+†CÃÞî„imRoY}ë·Ì¬wcIsþ“˻øTA“„MÖ£?\%Ë Fw˜ÌðÎ_ÿE¾ö[¿“õã'â±>u OÞKùË?ýÝù(i™(%ù—+»˜Ødò_Á3ÈaЋÛ4m¬âfT0œ ÝýžßåÔîLPÜXAö×¶æÕçòlG·½èÕ“žÔ†üѯÄVÝR S™ Sô©÷vñÁ!ÑXÛâÚzñ÷Š³Ë½ÿ½í³ä¦LòÙÑpÆËÊå`—$å¥RH¥°msRn1§›õ>ÿãÿÄýw½àh‚0¸Tk©Ø\ïƒlïäØ.çYtkâªpkm‹ÝÝ Nz6Ö†ˆ ‘Hºé„½}ÜŠ@kÉÚ°Ïúê Ûûûloï`C%ÆuǰßC Ád—G÷'4m+!pÎRä ¿/ çýÈÜ>‰ºiq¶#xKf$Ã2cûò>“z̉å!uš¹Y1Af{uË^5r#AŽNTxH‡œ!°²Å…šÆMç÷’uT†6Š¢ÌÑÚSÐÒÑ´ ï¿››®=Iê@ò½ÿÓ/ðÝoÿíy2pTÓÎ iBš=t£jºùtb6ðê™À ˆ÷¬ž¶‹“6iKͼ d²ýÄ{—W}ïOÓ¦Àå­#ﯲyý­\xðÓ‘? gbK7Kó¦xm>rÏG±¶] Æ„¤¬âÚ6¶—fìï®Æv Þ»ÌþY»kv ñ>ù~žñ¼¯N6Ç–ÐYŠÁ:BªÄ¡ˆI(Ò¿=Aª(ón[®ÔyJD¹¥ÇþÅÓì_<gia–7®‚øK~ bN¼{â)žßCð…Hùü§øì‡ßÅs^ñíÔ•„&Êå¼öï¿‘ßü¹ïcóÔͱd¹áïø¯œ¹ïÓ_<-¦™œœó ’`Û<ÀlgÓ 'D ·ï[Μ>‡±Jè÷†S MŽT†,+Rµ‘QöúéU”ýþœé)u”ÚèY²Í‹ö¥½\ÇùaET?õ>Ê1d&µcRðW2â~‹~Æaîæ’7q,×vA3MZ™¤bðf%1ÏE2تñDb­ÃÉ:0­Ö9t&)JÁ}tËôa_e”'Ï=ZIV’^o•iãqÖ±Ò<ŽÎ— É'"ó´ÖÒ’!Ì £&ÚÄ™`o,hl‹-ZXÆcÇÎÞˆñdJÛÖXÛ’IA+GcF“1x‹·–K»#Ú&9Ñu-ðŽýIEÓ68bçÐO¢‹F½Ý}vv.fúK!$/jwÉsØÚ¤ž8#ZŠHëÚ%¤Z°Ï³Ñ‚\‚ ~¾àú7?ûãüƒúF¤øšïøaÞó_~•ý iÆv<:s󨜓X˜Œ'¡PÐ餾;ëM§jÃÏí¨%ø½Ï+ÿÖO š( | 7XKÇ$’¿@pìú§¡ua”RñÐ] ©ÆËd%¼÷”+ë8Ûb»(]LF;tmµT툹øàœ`— {Ûgæ.m>8BpS õbÀ›å=ï»ØòF—Ï©­4¯x„$ˆp`nsø³'‰™šfðˆ'‘!däXÍZöùÇê½ë÷ù†ï»‡Õã·ÇÅà;Ë×}ÏÏà¬C(PFqÏGÿ„{?þÁ/Zrоs¸$>É@]øØCƒùà.‚V|ônõÑHÈû2 ¼ mÊx¬wt®ETÆ(d Beå‘&ƒ—¨qˆHÛatFž$º­ñr“‘ë@ÓF´’Ö‚~ÐÚ®ÁAß´–(¹(ÿóÜ@p0Úa[‡t.ÎÓ‰×y´ˆ&BG^š(mÞÚ8¸. º—c;OÓ8¤ ©]0¥h»"ÚJáÑI|NÑ‘„æú'ˆ(‚•%…¼,[BX$ï»4ÉQcG^H” ÔÉj3HC„ûUc‘xR(œ›`”`4êè¬GJKY䬮 hZÏhbÉó‚ã[k¸àhG¯W°>ÌqÞÑËuäb„¸]¯§i:Ç@Fc B‹8.%§Ž)L2Ä›@«‹\HÍ̵¾Âu¶…Æ9&£PަrñxzKk-=]ÛQ7 û; Z´ìkvÆÚzŠï ã™LÇìŽ'´uMÛ6há¢íâtB×váæcõ0©ê¨Þšôrâï %»®¦©¦IP.¡«’RçœY?W9¡ªf +h™ß±øŒ*aañ™ïþƒ·ò­oøAÖNÝ ¢*ç¹/{-ïþÿ3¾Ú¹ÔÒm0•ìgZC3ÔYXêçkZ%¤Ù’Íê"ä-îþG?÷ñXÅ ‰#VÚ×Ýú%+Lö.Í·Ë{Ã8ÈÐ0ïÆAò!3Ÿ¢¿ŠsÛ5²8°ïº„{ µ çúLø… Ÿwó;O½!BiBÓÌçõx?îÏQ p¢†Ôÿç'JáÏgHµ'G"J3ªÄ—ù+R”~éŸÿ=þÇÿû}sB¬÷Þ`3z’#É‹œ_ýÙú«{*z­¶]\]¡\P¼œ1O#„LI‰o#†Qè@‚„ÁJÉúÆ*B&ÒõEŽÒY ‚¤4iâ*@‚R ‡³xdhpVQ¹†iÛ`mÀµŠx¿5ˆ ÁÅ B†€26[ïBPöZBçȤÀä’•A”ÄÎtÀmÛ(6ØE¤–t–¶³èÒBem†·"%'Ò‚<ÏiGÛzeŸ,L¦-y¦”ÓqÀ3<¦Âӌڈ>É$ºE[gqGš8‹JÒµu…È1y†Ôï"Ü5ÈØGöº.ÙA#B\I9áÙO>Óž<¶%H]ëÂÓ¹xt`±Y3­ê¶CV#:;bc}@5­éÃ… –Ë;cŽmÈ3ÍÎî„^™a2Åöå­í°9ˆçüÂö”ñ¤#ïõ¸æÄFeìOãusb3g}oÎ,K½oÿÞG9ël\qÛe[tèð¡¡ëhrß0 -²«mMÓÕt“š0mh§Sº¦aâöÆê:Zš6M…ÂÒ¶ UÝa}¬"pÁÒ´g-ÎÙðDl*×RÆ’¤¿Å’ïð²‘üŒh)çAC^õ.KúmQÂÅ̬ӊyg›?zÛ[ø–øIªÆcâ™/|}×[Ù¿|>¸´Jžé˜Í,]û±¨4B‚¤/äh»Wˆ£ŒL÷wØ>sÃÕ“ÑtÊyŠÁJdû¦‡'¸áÏOÒQOöxô³%8w$¼S¤ãÔY‹ìZºfºL¸9Ĉ¾E3³…óÏè:œ»”Dôù1e¶Ã•šIá C‹£¬qv t–<ŸŸÝU‰Ä'“’¨!ÿJ â¡{îæÑûîf°~㬾›/T²2çÿáç–Úçô^:lÍqˆð'–AD•²¨ Á±:/Mµd…³¤g/4ÊÔëA9D”nЦB´A¤Bk‹[Å´!y<*å=AÒ [b-}ï3C_–Ö1A[DO ’ãiQ"¤"€ÁXGŒ£ nƒ• p Ž¦Ò¬Ö…ù4î‰.Pa }èñ! ª˜™[G®§w_Át/0™8¬±¬­ 8<œÓ»Èút Æ“)ƒF±¶±ÂìÆ ‡m?g8¬I)CiÚ€ë[ša†8—n»¾£uQ†õÕ!UUÑùžÙÌ—÷ž&jÁjS¼Š4Q@…ü|ú h1$—“ªs‰ƒ’ó1'3zß36Ž™Î{$ wöÙ\1\i˜ÌæÌstgŒ %–q;eoºGß9&í.®ßãìÖGcǬôÝ*_µìu˜¢Ì?»YS7Âᤥë{ˆA-¸¶g2›ØÅ=óyKÛõŧ%†ç;ÚvNh;ÒOà)€D!ù G•k‚ž¬’E!3б0U²º·fSµ(EÀT‘•¶"„Á£$0XQ‘ÃIOŒžVõóÏÔš;‡ìîÌ3Ÿ^àhܱÔrnkë·ØÛ›1Ö¬n4(Övw'ˆQœÝÒE…Ñ‘ùt®íÙØª Œçs¶Ï¬¢Õ!mçYYop½g<îPFsn{ÄhP3›vô}D´ÁÚ [¨LÖ˜$©0v€RZ èrzQ’CéĤwèÃüü#=ZE‚ï¹sÐ"Ì3”!¤"I"^Áî|Êá|JH1Ùrá =¤Ý™°12Á»»Lçs‚Ë,˜˜<>ŒP nÜÞeÞÎÎ3¨+åöÝ]ÚyÇ ±týœÝý mÛãƒËÙ1*1™åĸ2^K¤w9ç!6Sô_‚2¹³ªˆóEX"ùhʘ¨Õ« ^lÁ™Êª°PÞÆP¸Ë'ÜM̰–Q€èK¦2Ì\(6 щ¤„}b4M± :Ó3ö=H¨$tõŒÕºÉÙÓúŽHc› ”‰¬¯vv{Dµ4µÅN‰$f$&;«æPJ³?íØÛkiE£ª =EÃÄGîÞ=bÒNÙ:3dó̈›×öè|À]Þb8ªyóí»Ì{‡(Åêú€gŸ;­*^}kÎ[T5`mP±¾²ŠK ÚÓÆ0ZVW*$ ­dr-¥°ŠB+GR -BRÙÐNãIâóŠÏdÚ³sÐfz"}±?|Ìv÷ 8æíœà„Ì£öÅ+(žØÔ¨Öªl$ˆŠ'²HdIÃSe©žm?‚:QÌIêˆÖZò.Á¦Èa¬ª±M¤OÐI‡m1õ¬œsÕam`í’a6Ý#´¤T±¶¶ÆæÅ!Ñ)ÆãC¦Ý˜•µ56ÖGt­Æè†A£¹uû «†+[Dc I/yð"ÚÔìïMð>³§’ìNyóÛìíg Ö‡\ÙÚä­¯½ÊÕkû<}åžØäê뜿´É9í9|ã:k+HxóÍ}BÌžBϾ°ÍSܸ۫=á•×ÇYô¨*ƒ!—.¬2ŽÚ-­:¤ÀÖÑu-.ͱ#¸1ãéóÙœ¾;¢ë#!\ˆ$4)šBé̶!±œþb̹ݡøÐ»Q>Oö.A‚NÅê$ÃKAIƒ²ã–¤–§¥5D‹®ª\´B²ÙJ²18—õ Kçâ·t2o!;zÇSÄXN}Þ¨´Ìº¾÷ò»ÿûÏñ£ÿîßÎÖ(½ã»>þùò§~™n6É ôS‰‡÷_&Ó„L"³I s!5T5;ÚãðîuFkg3Ý{ž|黩«8™rþÊKe¡¯è&|í³¿^Ì Ó öT¾oû·¯f‹*ƒ]Jèz€ÖÕ‰l÷‡?ˆKïùÈrç!Í|r”uåâ]ìü[jÓ¹§ÞCUégãw,xÕ`…f´z*”iv´w_ƒ­mP)al••Ë(¾÷áýéx/µ´FyXJ廂ŸÒÒ; 9 3¦c*ñÃ7ï÷/¯ÓC ¹…"”:Kã²HÊS‚**Sµ”Þ AÀEØÈ(,`!‡hKJ=ÚATUÎ fNR+BžÄ‚P†Ìœ'©Ä`d9šõL[ÇÆJÄVÓ¾e¥±ºR³w8ÃùˆµBSÕ£±Áç7y›ÝǬÈô)fß"]Ÿp}—ñè(ˆ?áÜ1Ž*lÆ©EÉ–üñeSc¥UcuBú–6y:Òb´#(…At1ó3“•­0µ¡JÙgªJ5„a“H¾#ª=FM…ó­[¶‡È˜4\ãéóëtܸ³ËÔÍIZ°v@UGöwqý$ÃÅeÔmc³Ù\ekÖ7Öóòü ¥Ò†‹—6Og¼}ý]×q{'²¾¥¸|ÅÐÔs^ùú nÝ:àÌ™Už{î"s—;·Ç¤¦!Ž#“»7™ßÙ!‰au}ÀK/½€¨€÷‰ç.¹qs…ÆNØX‡ŠÌË IDATíYA]k¬Í4¹kžÝ½šÞoàCÏt>çðpÆí)“É„£ñ“£9óÖåÜóØã“Ëz|.Kø”÷$)› f¯ŸÌ¡ÏÿÍ^T) Ä"RLùBöãQä¨QSYšázvHÙ’Åh2,#J ‡eö‚(\ß.™4é^M xïŠÏ×ÂàþËçã—øîùÎl_!‘k>öÿcºÙ”z¸’sBax7i#2ñtó¼/SVkfœO¹sõë<ñü—¹ز®rîÒ‹¤QV£eV\gOV‘E± ®POµ&¹´Ü ÙyÔÚ¾üó½Bo5$­èf‡§nãûïæÔ£39D)ˆáÑL¦Ó÷{¿ÿGøà'~×έ™Möù­_ø/8¼}í¾‚*¶î¶Ê©…¢ÇÞWüÕ±ØX4\r?ît¿Pv‡Å~¦ ;éq ª“ß‹s™Î;‚VT1‹Í‚H´¥‚_§JIT&X%…NÙ•ÕÚ„2ÙäN鄘T ¦ü5Ÿ§2"ôIiP–at¬V6 Ù¢gP ¶“hÛºÄÎ3Qó¶#%aÐhÖV*îM™w«-Jt^&"Öa2+Æ…!]iûlŸÝuX†¥2– 0+S·—µà´Õ!z‚*Œ²h]Q‹EÄ‚Òt±ËKwžÑ=$¡·šÖD¤Ö`Šõ3 ­T¶M7“<‡Þe놵*û6ÅÄ4ΙÆ9aÐ3¸Ðç!*¾¹ÁAÓÎè"¸¬Ä=²»»K×Ï@4V¬®lb«l•¢ê£ÑƒFcõ*NÕŒ†#R¬±x88š¢0o½ï­xÆó#Þ¾~•³ç+öön29¼ƒ­5ϼïYâì*Ÿþƒ×š|ôyRªùÂË‘Ñê6ïy~‹—¾Ã£T¤$µ(­8³e°UOßuÌg–‹ç†d¦RZhBÖ+y7•Š˜,¥Å{:Ú~>aЬ!(lÓ`Œb4\/ŽÁyiÛ»>CRÅÉ4³˜Ô1Ô¬„n6y(ÄS$DOôñ”ù݃.¿üßþ§ü›?û‹™êÛž-âòþ»nÎÎÕWXÙ8¿d2ÕÃ6.\aºûóQ¼sx×R@KE ƒÛoŸºÍtÿ;o}•÷ÿ@.º)›hn_~žéÁÝwX¸Öœú½ŒÖ¶£u´©3Ëê÷Ka« ¥,õpD3¾k˜jÄ(e¨šæ›Þ‹,R\Ð|3Óê‘Ú‡oÖ2sï0Aè”Cy³äƒ‹V…Ý 1ãõ*hTÈ’î#GóŠä¢s°ŽÑ‚² ­ ŒCÛBC¡LIªÓ*ж3D< e«k«¬ˆâp’S¨6W‡¬¬XÆÓ) e4+Uƒ=©sTA°$¶¶´mààpFìÅÎÂìOk¬@50Œ‰´nèú@Ÿ ³™'Œ©¯I*\ž,“OÇÖÍnñ!‹DˆÓ/³,vS •Æh‹5–^¬QTfDT„Þ‘ŒƒÎçŒñÌtÖ$m²Äd‘„¨ˆÒ“&%,«‘@% £")Ì€ÈgŠHH%ñj¤›‘.¶4[t¤ ¶ÌSÌŽèý]z¸q3rå© œ;ß\Å3Ïœçí«;ˆÀÅ'Ö¨ÅÐëŽ 6¨¬a29„”Mõ6פMˆ’X]k®4¼úÚUÆã=ŒMìíXV5G7ßdçšæàÎe$]a8rëŽB‰°½e8ÖàcÅÞž%±‰ÑhHŒs´é g61DÖÙÛïÙ?Lçq½gÞƒw3Œ $:úù”Y;!ú–³®ÅÇÿȆõÑÿ÷p³)ÑåÜjm-1xn¾ò…ûa±É>Ú¢µÙB¥mùø_ùÏø…ÿè/<òþ5£5.¿øaæ‡ùT¢êÈþ7h'G÷w£•²MÐ"gü]‘˜‹úâ´PÙê[¤n.(ñ4þmh Ç'ˆèË©AÄ!1 È’V·HHÒÑ !¥HÛ{´1ì¤ÄNÐQ:bt^j›©±Ú$ŒMh“Ð:¢m…2 TDue³eî§N\>]$¥ð>0žvÌ»¼OhŒÂÃä¨çPZQ 4U˜O::ŒΞâCbwïˆ"Ê’D´ÄfÏl¬ i5ç%oð]"Í¡7„9ÄB,feI“b‡÷* Šbv}E{#h…×:7B•ùõVYÄ6Y‘n"IÀ›HR™*›ŒËÌ*Ñ[&›¢u’ЕÂH…Ñ ´G ˜”PÚƒ8 `)i»ÉQÓS鈗œw›RË,½ÎØ Õw UJvcÞb—Ëï¿Htðʯpkw‡3kkœS†§^<ƒVÛÔºâí·oÑM3Ìf´áüÙ5Ž˜Ïfh£F£pîí iŽ$ÅÚše2™Òû#bôÌö¹ùö­ /¿|“éÌóüóçyîŧxíµ]ÆcGeWh†5—.¥¸³S!ŒH±çÂX_vö&5gmébeY[ÙÀÖyƒÜv=7nLh[OHŽà]Žu=1e˜'›2BÈùÅã}.>£ñÞá<è¤X?{£"!C$Q²ORŠfmƒ ϼ7‡ÂKÞŸMv ÞÝ“®wì ´vå`¤tbâ;=úµ³1_þ½_áâ¿ñç2_‘œÅ ¤ö`†‹'¸,B„ìl𸆳£½lvg†Ë`×·<ÿÌŠsá±ÜHSŠìßz“"ÊØ|"è;¶.¿ˆ©¸vúÀŸÓ¶fóÂÓ¸vJˆSÕØfÈõW¿øÀÛ¿ù¥ßãÏýàOdvT‰rõó9Ï~èc¼þ…ß~èýûŽþ0Ñ\×¢´ÁjÃo|©°²8ei¢M… å„R¢fßõÄ_ O•(Ì7Û –"üã=Øqž•œÞ'| /¦+SЍLåÌA,¥ sm¶œ¨êL[ 9QŽÂNŠ!»6«9nÖÎQºÂf»S” ¨Þ£­E‡ôe²)Ÿ2) ¥-¢=J›ÌPÑ3÷$¥‰J l Ì:&Ó–ÞAcÕÈpwìØ›O@ ƒFÁŠÐNæ8:6V†¬ †¹ÙŒ[Úì¾L* í‚ªXx¼u[+^“\3Mš(h³;kŒ9{"^—}M Š—€+ð…W-Á D±([åºÖ•u .‚0e{Љ <E¨N'°%˜F«çª[X%*cJDD÷(* FZ4QIä{j¤câoóº;@R¢½Ø³v|˜òºÙå“g bxåúÓÕ9§ÜR³qyÀë-Ô+‚sa¥Ya?òÜSçY©+^þÒ+D?&¥ÈÚêÛÛÞzí:ÝäÁ;¶6·è&7ùÆWÿ0Chêá£.st4áÚµ1)6Dàðé‹lŸ=Ãk¯÷L¦`­b4€'Ÿ¬pÞxcJï/(Ξqýú”è=µµ˜FSÙ†f ˜Í<½ëq®+ù=;¯¿Å{þù‘Ú>g(ÅSïý^Þ~é«Üzã$ybrøÐeFOœóÜ?Ææù+™V« ºª˜Ü=žö9Î]Qæ‰ÅÚC Ô¥PEÿvðÚ׿ÈÞ·¶NÁ jÊÔï±’B ™rF‚Šú˜xñK‰“ß{õ‹Ÿäýßÿ¯ekü…r<ƒhÍg~ùx¬6»óæËíÞ`eã<¡o αºy~â/ñùÿó¿àϾï";÷ó¬^®T+«üá/ÿݪ>&{·yãO~—ç?ôqRð¹è·sþ¹ûëÌïrûõ?½ï±¾ð‘Oðýýtš¡F›áò×þè·ø˜255?ïÞ÷¥ñ¾‹b¾u*zŠo‰õE:n1†Sú›o×Å,¼^È">1àB (!á“'Ĉ÷=MÝ’ÇD3hðÑc­f°Ò Å˜†®st]¶‚V…*(Æ£Œ+ì :;Šòˆ-_S¥#Iåe—Òš$:ÅÞ´% $N5˜yäðhÊtêP•pvÛòê΄»Glo®3ÜòÖ´cu¥Æ³1Û«+h£ýYŽD”„NɾŻÝ$`£ˆ¬xð z;˜ze(îyaJŠ\±hð‰ˆ"*!J öN g()¼”Xâ‚-¦5Q;„P¼š ÿX’Íú¤EªóJå6ä¥XUƒ®H¶Á&RÌÔ²ðHÐhÓ#´f0+‹_Ï49vûëùĸ`+ûtij¼ƒÏM¾Ì´öô‚ä„;iÎ[Ã]>𯼇ó·Ï³:²|ýW9z¬Z'¦£sf”˜¤#z;ÃØ„gBJöPÒ“fÐxVšŽ«¯¿A7Ù'¥„­*VšÈîWÙ½ú&ˆÅ™uÎ?÷$Ñ­ñÆkSfó̰««!ÛÛÎC;·ÄèØØ°œ»`p®çæÍ)³yO΢J9·—ßÍ­H}‡s m5ßÿÓ…[o¼ÂçþÉßg>qëçŸâÃ?òÓl?ñ4Áû /iMð-·ßx­P™ZšÕ×)ÓS‹X.•ЙtBt÷ B°wãM^ûÂ'ùÀÇ~ŒAùX‚v"*=|‘Š™`.ꥸ§ô.ÉýïóÁýÔ©“Ââ¾*£yýK¿÷ÐìõSKï£=n|㋼÷û~ŒPˆ~Jhçœ{ú;ùø_ý[|ý³¿Êõ¯~AXÛ¾Ìûøg­máÚLŸ5UC³¾Á§þÁßymõøoöýw¼ïœä<>Íò®É{>ö—þ&oüÉïñÙò÷òï«|ïþÛ<ó¾ï£ŸN³#´­¨šo¾üŽvn<"ZF øÌF{Ø‚úÁ§‡"’‹9¢ö±óéb‹qò‹7XäÏ–{ÿîÄRXJ![íúŠÕFÂõŽfÐÌæ-I„ªªé}Ï@5ŒgG¬­žac}…Ãñ”ÉtÕZPʲ¿?ATÅÚ¨bÞy:ïÙX_ÇVŠñx¢©¢UÙ'''Ôç—Içœ$gKä°uÏ=“ñA)¹y¤”…Ä%ÝM$¡b™‘„$=ƒÅQP ùDJ™õ’äfBöo‰´xÉÌQ^':Ó5•äe¢N #©ÊÓIÒVƒn‘J“êMBÕ†d4XÉ&gµôˆÄDèUéуˆx$%• GO¤­çp¦GB^öúäø²»Îµ5ÖGk|õ`Ì´ñÈóʬœcãüSt£ Üù'h „–éªå™ Ûlï_áæí[4µæ¹gŸÃKdÒL‰žäj QÃÄôð€ž}H‰ŠC”2Üà`ç®Äd8-¶Ö.¡Âít†è†£CËN3"Da6÷¤(ÙýV)ê:ÒNxë Ÿå™þ@Öæt=Þuˆh.>÷?þ7þË¥Ø-Øà3ÍRê;póõ—Ù½ú&Z79ßàD–±6¦ @…âX&ÓEÐϱÄ8-Ú xýOÿ€ïüÁÇVA…l"VÆf[ïD:™àó..Óƒ»™êkmöŠÙBZ[‹Ö†¾(uÔ`Nfd‹_ùþ!—ÞóaÖ¶ž$†ˆëZ¢w V7ùÈŸÿ·øèþõü¼zëfø.#ºª¨W7¸õêsëÕ/žjHjNÿðg†Ÿü›?ÁµD—Ÿ«?ü ^úÞ?_îWÈð[Ÿw3ÚªÁ©4ÿ÷Ïÿ­‡ˆ KR 1¤ä‹R:µ£ˆ ã_ ôâä r¤A|õÝì§ÑE£¥ùv#Lv¤L'Ô RØ%¬†ŒµÆ6§BŘˆ³YV´–ØÌªn2‡>cÐŒèú)“é”­ís(ÉlÂ¥K—¸pq“o¼r•5ÖWG(›ùü(ËÖÖ:uÓ°³7áÎ4¦ª­‹/½mò‡Sg÷T‘E¨çhì™Í}ç5 } W7XI…»GsîŽ'¼ðÌ9L#¨‘påÉs¸>òÆÛ{¸>ÒXËÆp@ÛyvçHÔ…`º€àÑ’ÐUB™¼ÈÒ)`º. ;P^PK|0Ûñ¦Eœ–*'6J3LŠ%ƒCÖX¿ÄŸ k3/<¥4’b»€ ©ü#ŸBR¶0 ¶,YI›E‚Q-¬>ufàYAšr Q17«‰¢ÀÞ5@”e­@‰DOJm‰éì¹ÛwìŒw³–¦TrÉôè7Üu®îЮW˜Õg°Â-¥XWk¼ÿ#g¸¸w“Õ¡Á»ž¯¼ú§´ÃU"užf}…®ê9äˆx¦˜²YðÏt:¥îm„¨V5‡³ÄÁü:}t¨¨I é»sÌfžÙdBŒ™?¿µ½ÊÚJÛÜþíORmnqñ…÷äÅpŸ§oïxÏÂiA+TJ£¬Æ4 {·¯óÅ_ûø®G)s ‹O%ûD´AY a‘aY(• œ#©h @ˆ\}ù Üxã+\yñ#èròbe—‰n¢¬‹R(£Ð1«@ż{óŸ?ùÿƒ÷|Ï¿\è¿Ù‡¬yù3¿žó‹¥Xâaù?ÿôçþßÿ—ÿÎ?ýÈÜ‹ûj,Ù‹ \’`l Õ`…ƒ»Wùòoý¡ëîƒÈî½>ݽÍïÿ¯ÿ5ýñã,¾dBx—Åv²`# †65v8`r´Ã/ÿ쿾ðg:á%EP•!ù"¦´YféòŽŽ©¢UÕHÉÖQÖ¢ù–lQ m º6Ë×\äÛÔ!RáûÈ"!Ña:q 3WØ6"!bcI";ñÆ—âU•i†Å9G2^-%Çwaë¼ ¸YN©…Í@Þ‰DŠš<«Rˆ)+Í›H$è,úK*gC«–Êò¤s#I¢À$(\ú¤ ©Q9!°Ü£‹ˆ°AéB‘L¹ñUò¢q‘Ü`u@›PQ5/ïy6ªU¶ÖžåÆt½=ÚÁì¹ |¿‡ cΞÛ%TSâ$N%¼R¥ñµˆ¬®­pöâ×oÝ`ê÷H:B€ºòøXqxt—®;"EÅ`0ÂHàÆ–ýÝ) ç~ñâû¸ò¡ï£^áû>ÃBqa«}©Œ¡oç¼ü©_ãµÏþ³£´Š8— è¥Ù‹hšÕuLÓd³;c¬of°…ØiI}Í ƒbòö?ÿ·ù÷î7³U™ä«Á:¶–aîX!Àú¹ hU¡tv?ÕU†Q£ž-/úû¿Ê?ñSˆVDïH(Ì !÷@qßI^ý)¼rýÓ¿øwxö#Ÿà}?ô4ƒU¢Ëš¤…È.G¨TUSä•Oÿ*¯á·òN§LÜ;1-ò^ùì?¥ŸOùÎü1Î?ýÞüÚ…Ì“EëR: L놯î7øãßü_˜÷P¢ŽÅe'Œî£U†›ø¶Í™4Fc›f©J'Í…©V¶ÎÓMÇ™Ú^Põ7¿¤ªÑ f8@´F´¢ލG«ß’fð 7Š ªQ’%k÷8$]«œEc•€ѪØçÍÖ›gWrWS­+T±Ç5¶ÎG¬¨0¶†¤™[Dž½r-¹0G#^}ý‡ã–矊f8äk߸ÉÙ­5^|á)¾ôò-ögTÖpöÜB‚½Ã?¬Ù‘“¼¿’’qÔìtšLç·ÖyòÂæ]ËõÛ3ÚYÏsOnc,¼vmOD7š [^|f›k;‡ìîMiŒå™uªJ˜Ï7o2¥l BæÕÇ¡GR^t£ÉôEÄ¢ÀyÄiôÌ¡&Õ&l„Ê{Œd§uCDç[£Ô¾ gm,¤ûÇœTÙœ0§aÑX(1¬å5*Ø÷‚éË&”WÐK  ²y]Š Þ$¢¤œ:¦!*O2 6M›²7‹J$“ n2íWâÀBU¡$h‚’ŠHŠˆÑè$®ˆIPI¢BGCŸBñrrç ¤0aw|Òœè'øÐ²=ÜäÒê9®ß½NÛ¶\X;Oß;^¿ñ&¡à3ô·½¶E­+nÞ¸Žk{¢O¬¯­±²ºÊí[·iÛ¶@$†ÍMT½Êè쓼øÑbý‰ç®o¢”Î6“Cî^ýßøü§Ø}ûkÄnLÛæFRY WÌ G<ñüK¬n?±ÔIì\{Ýëo.aHN4ýÅ)eñµgÞÿQêÑZ~©lsýöW¿ð@±Ú‹ßóCS/^[Ëë_úƒwÔœ¼ØfÈ ù!\× ±æö›_+¹Í÷C ï$òQØfȹ§ß˳ú8ÛWÞÃ`e=Ûó)û7ßàÕÏÿ&wßü*³Ãßtÿek-`§z¸ÂÊ™ó¼çûþ—^ü.V·/¢E\ÏÞí·yûË¿Ï×>ó1Ÿâûö„>3‚Êï_?÷ž}߱ŻÕ`È—ûŸÈêN½ƒÕ .}Çw˜/ŸZ«¦á+¿ó+ß4Óèü³/±}ù9‚+q´Zqóµ—Ù¿ùö·å!Ãz5eo{YBJå¬àbñÑKf†ó. ‹¶Âù˨*‹óÙ:Æüd‡$Y½¬L±FÖh“£*777mé:Çúú&ëëë(±´çÚµœ\yòãiÏ[7öˆÃúÀ³ìíÏùÒË׈I1Z¢”¥u®XòûfeÐ&[ìJî9[Ú(¢(B†åâ…5nÝ9bÖåBº±ÞðÄ…&SÇÍ)ç6+ž»’Õ¾­sl®hçž[»Gô.¢‚ÁÇD®™2Õ0ùbËðò$³ˆ=Ͱ“€t5 è>!}ÂD°1`RD§˜}²$ë¥9G)%%|Èß*• :H]Q»âÙ’N©'3|êOP.ór=¤²bO‘¢Y&))×ü<IxÉ¿3QÇr¤Kþ«-ÒY­HÆ tn.±Ò3ñ¡œ:TÞâf,©eþ2 y+“nŠ„ÐBKL[ƒ[£UbŒì÷¹µ{+g!‡÷I8»r†èwîÜ!v£áˆõµuîÞÝ¡å|ñª2¬m¬3OðÁ3 9:<Ä»¼ÔÆ0 éû€ó¦±tÏD$Œ5X«è:_£Æèå@–RÂûTòã k„ )ɱ3Ã}´•ã]Åñõ{‹ÓB˜Îé10¿€û—™éÝO˜ïRùû0¦Ó75Ñ>&œr²/ÓãR:åMuoƒxãë‘%½‹ÇüíÝ)ëwJŸÈM-ÿÓʼn¤Q"(¥s¤g%šº®©šŠ6Í ó>«ûÌÅ G9ø0µ)®™º¼M5!ÂÁî~Æ×Q´³ßu(m98šÑûÄùsg®4Œ[Ö׆(­9·u­ý¼ck}„R–ðæsÏþɵÌ@1Å91¸²½N~Œ ¡ÁN°{kBeÍÐ`ââù<ÙìLçœ ¸rv“ñ¾ãÆÝÖZJˆISËåó6F5;‡s¦­Ã—¼Š…à#!iº¾§÷žÎåÔ¹ÞÏq1sñ•DüF¶Òö!çQKäanIó}ö„RÞ££Ç¤€öÙØPs¡Ï¼¦ÊºU!¶ÎM9d‘˜øyYˆÇ²‰KÎ\*C$dJ›HÑ Æ¥X‹…ýJ¶è$¤²@Ïj‚ÏÌŠ ù6AbÉÏ‹¼ Å&[t6Õ[ä$KÄ‘ó‘Ѫd°©lp¥òýQù{*ûNe/-Íݽ–=Ý ç:RXA¢#E¿Ä¸çóžv6Ç—ô¸”"mÛ1hz*k˜“&ƒá¾ïiÛ–ªªpÎã},®¹R…àp¾-ñ¢¾o—öÙ!d#Ã}ÎnÐ’í5 óÅXU FXz)½ ÃJa9,HéT)–S:²Ì86ÊË8äƒȱäBh$Jö|Yº.i·éôßLïš`/÷UÃã»soÅ—uŸGÓ{‹îÂ9ö¤žÀ‰$½cñûšF:át*ÉPzŒB﫸|Ôéôÿî·BzÔ³ó@¨ðaDªwҋܯ±xÐÏ›E†âØ LHY÷ ÁŠÂhƒ/A+Z v¨0a…nâ×S¢KˆBØßÝg}sƒ­ív÷™L¦(]a´¡®klUçÆ³ý1`Ñ" UEw4ãú¤§ëCÁ’ —ŸXåæ­}öÆh¥9³5@ÃÑdÎæÆ£4Ï=}ïo¼uˆËg!Œö(­òä­TŽ~TYÑ­”Æa›5šnÚ“b³i 4g7îÜ œYòä…5F+Wo`qñÌZEv÷6i6WÛgÚ>r4ž“!¦3ô u¢s«ô>O¡! ­ëòué²XËyD >Í‘˜ky×Gº™GÚóˆt Õ$ä¦"Þa\V‚Ö†F,FWh=ÂTk(åQîqÉ·Kè*H$¦²DO¾,ÔËQCÊb4åPÕDD¥„-¥#¿!ˆÄb;ˆ E#—· )â|n$)·˜X¦¸¬z^@fÇïý¨LÑTD1y癢5»ü IDAT>¬òÉu ü'ARŽ~=š8¢O$_åF<ïÙßßcee•Íõ\ð½_žLÐÄ…¿[YBx籕Í'Äeª[~C€}Λð çÝ"™ït¸JÀÒ™|à},y‹éöž Çû§Ó¾Grœ’ö€¼œL`KËx¹cnNÄY—×ëä7Nî —Oì)“·ôˆêò€L†¥±\ztUú3Açé¾_•î)ò馅éVÒc7†Çh÷DÒß¡Þç±ônž­wìoù}“E1jÆV]¥‡Åâ:Òvó"Wëqâ4g½ÚÚ2 ðÎú€*æqÃÁ€¦nðí.~ÙܬÙÜÚâîí]voa«:›rÅ,À³U…­-M3›M²LM#†›W™Lzj]qöÜ—žÜâö­=îÜ>€Y?{†­Í†·¯’$0¬kÎn­ç†¹[~0.)Ñe Z‘ÎS)M÷¢#t=WžXår¡”bo¿ÅŠpáìˆFnÝ ‚pùì*ÎfC5‘Äž±M§(É47£…rLa‘TœèÂ.œO8éC úÄÜ;ú¾#’“׆d/*¡ë;R ©uô³H˜zÄ{ÄõH2tåz$ÍP>¡° ÚÑzJŒjÑqŠv3ŒôHÁòt«ËröÄuSÈâÔ±˜*C)z¡°°–Ü5bI1‹Db™niù<Ä”²±b åkˆù:!“¥Eáœç¯( ˆ%%“£nQez§,®‘ãû) ?11$"óÖãÜm„à®ï 1ÑvªAwc 1&ú®[•Oë´É )¦€B¢/'°üìåk*«©µàeé›Ce”’eD轕$-R§çÈeâÝò>=ªÄçQ/Y:3sOL'¾Z~Ÿfíb¿“íqŒä¾b¯ôˆ<Œw„ÌÒ»ø}{ˆß&¤ÿÏ &ïQÅì…Î QE‰_ ÅÀ®ä÷Ö Sk¬ÑÌöç¨di5“ñݼe8CäèhLekƒšÃÝ=úvΠ1\~êkkkܹ}—‹Îpîâb€ëoßf<™} ÷Œ™¡ŒÉØn]åÇ^…©ÔÕ€Z 9Ús´?¦QÂhmƒçž:ÇÁ~ËîÝ g×+ž¸t†á°ÂÃÎAË[o¢+ª-ʪFe+mÐZòbX2íM$«­gŸ3­ŽZȹ͆óg¦Ó =O]XaksÀݽ9‡“9gÏ X[±Ä0¤®«CËÑ´£÷YtˆÎ«e‰,3¹‘À‡,€™;èŠ]1ô8ïq±Xs5wç=]×#.àæŽÙ´'Ì=¡ Ä©'´žÔ ´™¢ÐYXUH¢ô§Ø4Cõ= ••×Ð ,U²;ª,s+c¡rÆSlš´(*’J6r6CÌ é€Na¹ïRd…ü¤bÀeÇc,ËòTÚE‹Å”ê ‘|n’"©j©2$[D²M| § ¬$œSônñþ¶Ëå~Œù¼Íï kpÎáz·¤Bf8I-§s­u¶÷®ÚÒ ÆO~„J²q]’c«ñEåÏ+9u:9‰¡ß[”lá-²yžµõ®^?Äښ矻ÀáaÏÞ^ÏSOm¡âÖ)ëkuöi:šRÆŸ­Õ4MEm¦²h•ô°S*Éb¢ ›k5Z 3CË™Íû3ÚÖ³6ªXߨñ>`L†ŒÉÁ!ãñœyÛaŒ¥jTf …´¤ëf‹ƒ’:°Ñ"AcM¡ðâz$¶„àÐÉcè1’—ㆈ–”H9,à‘%ܲˆê,*óÆP*°Ú©¡ú8ë¸4³Ä"1(ëXŒÑ%¢3ŸRbÈ+çH±ÆˆKN¼H9=,ŠU<Î^NôéA“ìËì"ƒâa¸ÿCQë$Y¹NBLéþ ýŽÀ¸œS“È·îDñM©ŠÓŸåï=FüÿaS8õZmÓbúXP¿D­4Í FBŸÈ EpFkjÉ Æ$Š@ÎCpIrˆ‹RœÙÞB´fr4åɧ.ãœg|4cóÌ&1dŠí`4¤®*nßÜçæµ»lŸÛæ©g/óö[wØÙ9DöZ¡•Á˜œôT$eè}âÂÅmž¸´Í­ÛšAÃÊʈÞEÖÖW™Ž{ÖVhmxåµ=ÄjÄäÏŒ1‚©Ê@¥F+¬UTVcÙ´lÙg‰AmØÞâ¼'O])|ˆ4•¦s£q‹ÕÂÖ™³®ÎnŽòÂ_ûS¦óv™[«ŠVP™>+’s Üâ£àb^ò:Ÿp1Òû€'âÇ-,Q\ÆÚó¢¸ÏŸ#tž¾sô³€ŸwômO;D—Ú„q ñ 17 éð}K×·(ЪG'A«„I+=¶¼oTŠ×;_,‰IrùbŽÄÉĬt]X,lŠ®£ð¦2;ŽxÜ R3¥"LöZ,•O”uN†ËDœÉ‹ú•7p"¥+ÝS¬eIø?É9†›N©lUÞã4å‹ ïþò<Ô£æA¡6»—o¢à¦‡#Tï ,÷¸Õ}'–ôîšGú67ž¦ ¦{©pi‘€$!³/lb6›Úˆ$] §|âÐZS#EÅVJ`”ŠFyÇHéb­HwnãQÔÆƇ\¼ò[[Œ©5;w¹yã:Ͻð IZÄFk–õ!×%ë 4ëYÜåC ³€®kŒŽöY]±<ñÄ*wîL˜Ïº¶üÑ—¾†©-/¾p‰ñØãuÇ^¸„Fñ7öéfà²×Q°:búˆ(Öv³ÊPi5 m-S§˜ù)ÏŽ0Ö²sÔ±ÒX¼hö;RT¬­4ø 0ªáâùUögìðÿ²÷f1–eÙyÞ·ö>çÜ{#"3†œ§Ê¬ª¬±«ºXl›­f‹d[¤LÈ–Dˆ0AK°MA–läCÒ‹ß øÁï6`Ã0 A%Y¢¨¦šl²Ù3»É.VUg 9O‘ã½çœ=-?ìso܈Œœª³ªZˆŠˆŠÈ7Oܳþ½Öÿ¯ÿ?¸8àà9§9VÒäÓ¦¥ê²§RÎKíäz2ñañѵ@4D¼vI1áC$©àbKŒ±ã4 QÛl =É×’‚â¶Íȱ½R›ðÛ‘Â÷1õýàsDh]ÓJ‹Æ,-±,K¢ê²Ì-ÙU&YWÒuSÅ[dì\Õ½Ï viÚ¨Rw'e‰v¾D]¹6“=.µ«óÅ’I‘ìT9:.ñLÆ0ùaw“±zÏ =í?Ï׎“ÙszפD‰“QÍ4Üï„«{güc^øAós¹÷Ú0ᦖèd¿B>Uð÷Òšö‘’N??y08è4ª{Hö~û˜Ïžú·?´›0¼òàz}Ï·è®õÿŽƒC>ðØBǧ1`Kƒµ[f_G’Ó8NÆ&~Â@,=“ç–0ôºœ^c ÛuCÑmçœß¢ª(ñ!1˜1{æ µODòÉûÊ•[Tƒ>gŸyŠÕ;[,ßZ ƒ>Ï¿pŽ˜ —.ÞbØzŒäñ“eÎV(L~ü²B œ8y„Å…y6G¥Åƒll·¼óÞæçxù¥“¬®5\»º†¥déà ‹ÔM¢v)“Õ…æ­EÓuUŒ‰ˆdòÙX¡´†¢È€yxq†Åù~Îy³ù:¥àYZè39n.obðÌ™ƒ„˜¸µ²Él¿dá`º Ô£5`-ŒÉF|VÆ—'^ÿyŒcµÀ¥n?ŒlOœbÌ1œ!%\PRŸ|—r&Êœ‘†Z¼Ë)`®ñø6áœàZh‡Y÷/'ŒÚÍm‚¯¡fÀI”PäÑH©>;̰Ú9N¥˜Á ó J:Á,;䶆nˆ¥“ iÕLèü½±“ŽÐžœñ»Žaü5v+t &ÒÐcùÔWeWR…Ýq\:5µ‘É~ƒt`wOqŠóÝáî=W?ln> ,bwÖÝ2WÙ%YšŒÏvѲ/±¼¯ôRä0ÛÏjãa®sãë~¯âG?LSðdŠü“,è ÀÆVa[Qæ}¼ ¤6Ÿˆ&ò8íì 4§Ë©Fê$تd%Eæböt²’yŒB FÀ– J#)pM‹4#Lu€èJÒ®²th&ïŽ-¯³X”?¶@nc…¾Q½~ÅácX^ÞdToç*?ÿ$ É ±À;%&- n޼ͨ±thë·nq{eÈââ/>{ˆ·W¸rm“@$pþè"çÎÌó‡|‹åµ!ÖXÊŽ§( KY9¹®È§¯ ŠÐؘcKc}XØj8²Ð§mu“xæô<µréú+Ïœž#ˆåöÚ‹ èõ j—®ŠÊ²±5ì@.À)§÷e‰1HÈËrbr'•È€bÊäeµ$–¤Ò¾JHÝÂVªòH*äŸà%'᥈ ÙÚ:i"8×å)´y¯%DB¼W\ ¡n >áFC|=¢nšqÔ|CŒuàŠ 1ä} ÍyÞV]B¤Ìäó|ÂhÌ :M»†%ItÌ‘O•*EºÓ±L©q¤³³ó…}vÒÎèF÷JåÁ÷ÿá`q¿†fÜi=ŒøÖÇ#Á Oâ±~d8ˆ^¡Ea'Aíɧ¬S/–îƒI§ÌvW! ”ƒMˆô]ûÑ!¶Äξí lÚÎ; "9<£E,¥éQôóX*nƒ f08pzÔP×1%½ÙCœzþeÚvĵ‹¨˜²Ïù—žÅV=Þ~ç M[fR»èŒÒ AŠ*[q±–S§Žrpn–?ùàÞ%T-GÍóôéÃÜZÞäÚ­mbT—æ8p ÏÚzͨ‰”…Á–^¯ g-•))`mWJίc¡ˆ’(gŽàøÒ€µ­ÀÑÅEa¹vg‹³Çg™é|pc ×FNcnPpíæ)ÆIÔ¹”9BÒCYd¾¦(rހɦ·myN¥“NžœwʲçšÔ-· )‘•? bÊòÒ ±Û7¸šˆ1\Vöø7‘Còh²y …%¦DôŠk\hhFk¸fßnÑ·ñuCl=±ö$ïЦA}€¶Û%HU!t•?+œ,]¶têTHÝ>…v‰Z±“…Fst9:M%•]aîºGÓ£Ó…lOQÒ{þ»§H3¥bŸJ¶g;j/Ÿ¹+3hÏOy°wÒŽEÄ~[Ʋý»ŸŸÐ´jjo!ÓãŸûвçIïjL&ïujÁOÜmÈ£ÓVéPÔÿ¬sx€Ši¶R[dÄñiAö¹®ùf°"Ì"„.4Ç–¦,¨Û–ÅùæfúÔÛ#ÚQÃÒ©ŸaîÄÈ¥¯ÿC„!Vl76$™¼À†ÁHIÕ;NÑ_¢jîPJN 3]õë f9qö4ýÙƒ\½­Ôm…Œ>`aiž³çŸaõö:W¯¯äqŠ-ˆ¶@MA´Yí$E^®’¢E…éõ0…!DŘ‚£‡8wú0·îlsùÚ8wú0K ‚ä‘Û¥ëë¬l4PÝ(å‘“”ôÄ2WV ŒÐ£@“EÄ‚’$0†ƒûœ<9Ç–‹Ë[œ:6ÇÙs\¼²ÍÈŽáµçùàÚË+ ç*Ž,TT¥pçî6­Ï™ y›ØÒ³Y$PØ|×–ÝÆxNÃÊA"FSî8$›+P(jd2”]Mœ”˜×áBÌj´ ¶ËÈ |"¨ÒF!& ©D0¤”÷»W4mS6qõ]ÚÑ*Ñ iüß´øQ›÷†#´mIƒÖ‘š–²"+!¹lþ—’³:1Ú…Ówo¡Ûyˆ©Þ‰ÝŒŒ•Mº{¡êžÓžS¦êýáA÷À‡ÎÈw[ÙíV =nµ‘'X˜t‘}¿‘Õ};}6XŸhaÿ¡ÁBpÍôÏ@á^¢´:=V•NŠ!»¦˜ùV(DèK¦Ç/ðbÐ#$h[‡-,³s³ôû¶*¨Šü·çòÿý–gùâ?âöÕ/5Gà=’ò)ÌиUG±3')âˆ",S(¬effŽÁ`†è=¾˜Áqœ|§Ïαzë7¯\ël”{œ=ÿÇNãâåe®^¿‹/:À°ÉÔ䄬ÜMÊ^SÇbâê­Mfû}Î?}Mðþk—xî™ÃÄï_Y#¨"ÆfI™‹¿šœUa*[0(,,•µÝf3©ÌmuÌ úÌÓ‹¸˜¸|{›£‡<}fžå†‹7¶ˆQ9x âs¯#(|ëåll']@‘IY9¤ã8H¥4kÀ”t<‰¡´’¹ c;Gݼï!&ûT™qw1Ñôî,G—Ú’)å 防ùRÒHˆ1/ïi ZÔ ô€’$‹ÙB" i›»4a‹¶Ù"Ö«„f çj\[|ƒoêœ=fKèÆ‘š†4ÊFò-)úì.š2Pɤ³HùéxA.ï!ŒAB§xˆ—¦*NïƒMC‚>¬‹xÄb%;†oìkÝ£>zÐôÿ1ä9ººÝ yåC¦ÐU÷›­<‰ã¿A²„ÌœÃ)üظ’çðX k³¬µ(yêégéyÛ«‰bt‘æî;Ì/âÅ×>EŒðî…K¬oŒÌÌQ }¢QÐÒ’LA2eìK’‚Ðùþ<÷ô Μ8ÄW¾y#%/>s‚^Yòö»·©›È©£Ñd¹±²šÎw¿è|†lÖ¼«ÑnÌ£TÆÐ3† (,”ÆP*ÌÍÌrôðKó38¹½ZsýΈÖ'zý‚Wž?L¿oyûƒu¶›œÞë eÏ¢ÝTêtübÂÎà£ËÜ6€µJQd½0PXÉ!0¶ 4«•uÇEuÖßÒÍû“QRW$"y$¥iç¤5K-“2;i1È Iú Jë\»sk„fƒÐlàÂçj|[ãÚaä©s¼g5¨ÛFëšÔ:Ò¨&¹;4bðhˆRèP³ï–ñ=ÅmgJ¿Kr*¦ÊÈGX¸ô±ëé.#ä‘6—ŸxG!ùø‚»úUÔŸr`˜úýŠÞ{…dWïPÉT Úµ£Ea1ý))mãòwa0èål\¯IÔMÿñïÿo,9Åh´Æ?ÿÇÿ3òæ…ìq_Xª²¤ßïQ–UN™òß(¾}9‚ÖïcÛ÷)lݰ¥¡4e¶6K´‡yêÇþ*'Ž-aïþ:Ú䯕›89~ö §ÎžAÅpûöW¯ßÆ«tE•ã@ËÜa¤Â(8~t‰óÏœäöÊUU¢Þ»¶ÊÚFˉ¥ƒ¼ñÊ9nÝÚâ;o^ï’L笚ƒxÄæŒk) ZØÞF»>)߯²Ðïs _¡Þà|B“¡×/ùñWNäd®·WY_wDA ó}>ÿ§ AøþÛwصHaº]Ž,'Æäp»¨¯.{…š¬ + B(KCa¤Á“sW1ähË‘oü–l¤K="¯Öõø™P-HZu¶=LÑËÞHR‘’͆~n„o·ñaç†D·5)4x×C¤­ëœiÜ6¤fDªk’¯I£!É»üyãHÞ]Cj±ÛGI1’Bö^Êʧ¸ºÛ›g×ðG÷zûìá$¦GE÷å‚õë¹NÀC5‰æø€¿û¡‹Ù¨‚úñü˜E¡ôï (Ü öe¨ºÙ±´NÉÁñ¶×˧Êñ.NZéƒó¨æ;÷ÖÉH‡ø;÷åÚ-ÃüÎ?ãÒ;ÿO6fÓ®ÑEU¯¢?˜¡*-bÎô5ÜæÂðëhʶEarb7çôfù±ÿà—yãÏý_úÿ‹[¾ÍË/½Àù\{ÿ*ÆÎ}‚ÇsõÖ*—n¬bŠŠã‡—X˜?È W±=ô¼så6ÛµGèjÛ)‰È‰@b²uˆX“?ß™åL¤™¢†ù~E% o )¨LÁù³Gxúôa¾÷ÖM–Wj yï¡êgë‘¦Žø6b5[µ@ŠÎ±ìT&Åx,”hR¢%âPb‘cL5˜2ƒ©„Âk³ßQlÖÝNv”|Ïaêm¿¯=‘ð¾—þ ±Ù½Où§ v¿ éÀap’ûÆjàãŽßŒìžáÎè3 ØÞ¢Ì-nÝäÚõþîÿð_óÿä·ØÞXÏE3¦¼=(ÌVT3Eg–'HR4­QJMÿÀ«Õy6֯ю®Óºˆ 1Gög88¿ÀÜì€÷/ü€k/ñÅ_üEŸ8ÂÛß{‹“'póÚ –oßæÐÑÃ¥aeeçê¬Ã×€¤¼‹<6ç+¬bŒÒ¸–¦m¨ œ=y”ùÙY~ðÁ%|ôœ;yˆ"·Ö–Y<Øãì±EÄÚäP|žÛ“ˆ2htA:I!e¿¢”BgZI’H&»ÉF›(úÒ7¼uk•·ï¬²-‘ÆF‚MÌ/ô8sâ W–×¹tû.°Æs`V8´P¡ù†Vo !¢!æ\í (¤lWQ$¡— ý¨ÌÌx¥"E:«‹B“%ª®¸&Ðú„óŠ >‚ ©³/´)QÅùH">*>*.EÚèð)RÂLjה‰o1$[€- R$«Î‚X’Í{©“,‹)²Ü)üåÎçRežIª )J(2àH‘÷d°e·+c‘®sÌöö–вJm×a±3 yŒÚ62»òØÙ9š‚ y’ÅùA…ú‘‹ó‡úKÿpòÃ<Ç{Bä#ýžïŸN€ØÝûæÜÓ‰9 ÞÇ)Cƒév—›?8‡ˆ%5 &Ä‰âÆˆáÚµ |êSŸás_ø"¿õ¯ÿç<®¸¡£®=)ÊÙŠÁÁÕL#ÿ"² IDAT…±àýÑo28ð:só/“š+¤°I ¹@5£–Q3„ÁÌ mÝò½o~‹Ï}þ³üê¯ý*¿÷•o±q篼öUi¹øî{´Íˆ™Ù kP"ššDM“²¿5P¡4ÊÙK sÌô N^ÀhäÎê]ž9vˆã‡˜)9}dž˜F8?¢(5[sTŠ‘ˆC’@òŒ9CB’<)yH‘tn¯mð¬lo²V7DQ¼D†)gJÎ]âÊÆ:¬¬‘j`xáü^yñ‹‹3ÌÍô:ò˜"ž £ØÔg;nM¨Oh›À'$ 6¥Z3*ô}¤rÓ$̨AÛ@j=ZgÀÔ&bˆ>|$ÄìJ›b"¤˜¹*Ÿ; Áçå;΢¤Mü¢Ï-œ5†ÂVˆ©P[b¤$Q` ƒÀjÞ&·Å$Ä=¿ÏE_ŠS”x …îû³Ì¹[ª´y·EÆ|Tn—c²7Yv¯ìùòÀcêkÄ®åÓ=UloQ›ÀÄÇ\u>Ô“÷9ü—Däcº†ÿ†5ûÄ®ÎzÊÄL$ká§¹Š©»&¨†Ù™Ù¬•÷ÙèY(„YcÆÎ€|õoò·ÿ»ÿ†º=À;o}+Ï©µsøŒ™ô®·Ífƒk²‘]9E±FpC.~/Ïý-DïæÓɾúÎ;†£: Ï·¿ñ-„ÿÕßþ/Ûãòû¸ðÎ; G[˜›ãÇò'8|d‰»Ë·ˆ¾ÍûТˆæ˜O‰›"•(ChG<3eÁêíêa˳'áêš‹W®Ñ4#œ¥$Òº†~!6PiÄÚˆ-Ö†ü±‰1619R³„•„‘„1y³Ø˜„HB$°0gyöø"«£-þäÖ2ÃØ’f„7^9ÃÂü€ï¾w…÷nÜfî@£GgYÙÞ"¨Ã–JUAUæéFZjih $ÉVš")944J6JL–†ARªà±Ã´iR{´iÑa m¡ñhã¯à³ü”àј |V%çHaDð>ËX½#´‰$[’k…• ‘ #}”²;íg•Ö8!p¼E1¹c˜GæS¤(;@):°°y|5æ‡:‹{:›nÉö¬;§~#“Ô°]ÉmãûDvÆO´D··›Ø[MdÿCê'òUñ#(´O(>²ŽâO `ìßALÁëtÕ~ëý{ɶÁ GYôÑXVê†&)I”ÒÀÂbê5ã×~í/ñ­o—µ•;ÙPm²ušó2ñà W'¼[Áµ'Î}Ìq¼¿„-¶Ñص¤|õäªó¼ùÇßåæÍ ~î/|Ű|ë:gΜáøéS ··¸rñ"ÃÑ0/ì™L£""cƒ9‡Q‡DÏh¸ÍöÖÆ$Î<ФÀêògúœ9²DhšµMN/Îó̱%ÍÐà±ÁQjÀ¦ì7dˆ]C@$äd6<’B·Úåóq ùÿwF²1qsu ž}Ã瞊Ú~óÞâÂò-––f9ú0ïܺÅÚh“C‹3ÌÎ4ÉãU±”%ØJQ›ð6ÐH‹³-NŽõ-1µ¨÷â}övòó(¬ÐC‰hуE$Ž]q'„La:9°™ê.ò×DZ9ý/~» ]Ö ]HPî&öùÉ~÷ y±DAº*ìã º§šÈþµR>n Çéäc¬¾ø~l@ñbéãý½ 0ûnz½k,Î;ʢĵ-Å©P+ “Œáê•˼þS_äè±%ÞÿúïÑëP&²7Ó$æT±ä‰T×àÚë4^x楟fÔa4ücªÃVE7¢ˆ]ãØ¥V¸rñ]Þü£ðWÿ“_æÈÑgYY½E3ÚbùÎ ¨Š²s#í¸&$DcI:Ë u¤1¢\<Èá#‹T…a4ܦXX<Àöæk˫̖§¡Y_# ·é¥@‘"åxŒ¥ž"yŠ(Í£-£); ªÃjvA5 ÉE|›ÁÊ’8{h‘ř߹ðM=âÕ3'xõÜ)¾wé 7ÖÖyúÔaè37[±t°‡ó-öé6¥Ç£v“§+&Mø"Q›À(µ´âQ“ÁKC—1[4åà œD§ôPzó¿/8Ä·àh[´iH£ ±vP·¨shëÑPŸÕl91É‘bK 1:y›Ú9‡‡M Q(Ô`´ÀÄ¡@)@ŠIðÕ¤ð;…Â` ƒ±‚éFJfBV›8:00v’Õ1‘'OÖ2 S]Ä„lvÇÞï»_…šß÷l9ËñIò£u~y Ýsx|Ÿä5ýûtrE›ìŽîz3ª²U| ”¶Ä9Ÿ%…Ï›ò2l†¬ÜòŸý_á÷¾þMê»w˜+„FéwÞÐ}o~ M)Ü u½IY-pþ¥7¸~ãÛ·¿ww1}C®D ¸&ª1fáúÚ¾õõïò7ýoÐÖùWÿü7˜_šcîÀý™Žž<ÁÓÏ=ÇÜ쀶|BT²Q^ŠX )§«0ª4uÃp{Äêú2uhY\X[pûÖM677hê-ªªàÀÜ wnß&4#Lj1¡ÆÄ@¡ “4{T%0)›ÔIŠ˜”äónALÝÿÏ‘£J virÄÄÌ âèüÏŸ:ÊÙ# üÁÛØnj^æ4×VWùîWx÷öŠev¾byû.15ˆ&’rìG% F1…P‰¢HÄ"0ÏoX‡˜œt—RKÒ¼k š%ÏC…0裌‰ã=¸œÏÔ¶Í[ÒmCÕhð¹óp-"<©uhÈrWÚN®êñÞ#Á¡>bSB’`S‘e³¬æ+1&G¼b0¶Ìc(Ó›L‹IWQvD,2^.šÇK“â.yô†Ù¶5Í/Lû Þ3ËÌ7¦9 ³çïìòršf(ä“«/šàþ˜TQð£IlXÁÇøK¶"üƒ{I÷yÁê>3¥©?ãS[LI1‚÷žÆúÝr(es{“W>õGOåK_ý=F\ÌÅw`”ƒ(ÉYùçvAïåÑ­±¶>âüóÏsìä³ÜX?ÂÖò7hG[ ·[’IT39.5t)kÞ'ÖîÞá_þÓ¯ð_üú_ãÄS/°¹v—…ùêQËüÒ ¬®mzýì ¼‰h"éà'Ñ›Éפ98w€ÅCKܺ»Lð‘ÁLŸãÇO°°°Èë×i½c03cH>ç&hpà[4µ¤ØSC Ù¸Nƒ#EGð;ãž1¶Žß¡)°ÑÔ¬m®Ó+ +›ë|õí·i\ÃKOäòíÛüàÆ5bj©Êıù9¶Û!ï®°æFŒpDZ)<EÅ£x’ h‘(l¢W*E•ð•gd=µñÄ*¬’ %™ˆJ$ªËÞIš;›"•z&Q¦@•6´˜è1.s± h뉵#6-iä²SÝæ7ïѶ…¶!6uî(|NÊ ¾³%ùú˜¨T"Y09ÕÛŽoèM€ÀŒIn1`,ÆæöÑt¡MÙ6E¦r…:ï*#»xºiõÑn ØK&ÈÃS#{…M;÷Ý´¼ö#ŸOì úØ`ñ=‡h õ#õç#þ%w„<þ/oÏþM–Âæ“VL©‹]ÌȱËÿ5…a0èS•¦FuË©3Ïó“oüÿöË¿O]oâa”`””¶û1}£ÌŠÐCH©FÌ)¡½ÃêÝŠ_üùó¨9Á•›‘Ô~Ÿ³*j´Ýàœ‡B1½Î3ÉBݬó¥ù¾øó?ÃѧÙÚZÇšÈ7¿ö-.]ºÈh8Äé¶£-E€-ò¶p¶ÁŽhÌ„z ®³¬ÎýNUÌÍô°ƒŠ¥CK¨(«›9´È™3§™?x€ùù9Œ5´¡EÕe2::LòØTgžÂh΂F)5PHî ‘"EŒúŽ@Oê mõV×Ö)UøÌsϰ½½Í{W/cƒãÈÁ¯œ>‰ÑÈ…Ë—iÛšÅ^“‹ó úCï¸;ܤ5šF&eÞCc i&± =K"¨£ÕšF‚:‚D"ÚÅú< >û&ň ”(•B¥‰JEtT¾AÚÚ:h[R[£.gKĦ!Ö5©nHíGP×Ķ&ÕÛ$×|KtŽè<Ñ…lY5TB íöPˆ)ŸþÇ9j2pHéB¨rW,;c&²¼U¦F¯"SüÄÔXišÄ–]¤vWÙyÀ‘•}3¦³zd¿3°ïëXÈ'Xé>"rûé&>¡Õ½Ä='’ÝFÅ;þbro@ÆxQ3å¤(MJèüp Ûrçð1‘@opˆW_y™ï¿ãX½ýfw#æ»GiÚ$4]ÎÄ,PɈJ$ ll¯suõÿñÏŸâöúaîÞ½M W:"1ÛS»ÆÓ6çˆTB0Cþð;ßáç¾øs<óÜ+üŸÿÇ?âÈ‘Y–cÌô™™acs“Ñh ±Â`¶Of@Õ¯°…¡ËPŽ"¾²½¹‰úÀÐ;n¯.£FxîÙóD,×–—¹~ë6ƒþ€³O¥už¦qr4kA¢b\Ä´qÄ”OÙ.à}Ä·žè=Á‚÷xr1vžZ¢k9±8Ï‘Ù>x€󋬬­óö—ØI.R üåŸú ^ú,.^æÎÝ»8¯Ô­gÔ:ê6K~Ë”(#H¤„I‰2&*M”$МLWGGC Šï|©RÞý ¢Éç±T S;¥Fz$ªä±Ñ#®A|Ml[’k¡©‰uŽìÁÔ M6ÛÄzHj¶H£-R]Ú–Ôú 2! !G š¨˜dsg‘”èœa5o«`0 ãqQV0e¯á±}{ç;%£ÈÔ¡^v€azü3 ØYB•]Ér÷.­íeíË îwOÞ,¦¸Q˜|2·|BGâGå+~ÈÔpúžQf«’Ù¢Ìæw!@H´>²íC_“¢£Š!/jÀƳ)4F¡J_` yIЩg>ý0®û8shBq 9É’¯EÏ(•I”ÑQ¦éÔQêÛì³äÑg2;¹LxÇf˜^]ChjÔµ„ÖáÛ†Øxð>_/  e” )u\Oìl²©Ÿ!Kp'Ç¥ì/Óv¶«ÍNžŠŽOíf²\7Q(énùø=JØýޤ»bÝv—zé”zûqƒÓz’}5'{;‹)®BچȓøÙÁ~ÅÉý®Ã½ñÐ¥ƒÜïêÉ}Ï2»^ AÆ®¢ª4ðsþǸøÁ5nܸœ·®ÁÓÍjUÇÑóã6]‰*´šhc¶fäOòãŸ>Ä­Õ#¸í+Ð\'JÞYÞåI(“ Öšá¿ÿÕ¯ó+¿ò+üäç>ÏoÿîosñÚ;¬¯oRU½ìóä[bÌþPÞ{FuËööˆÑh„÷ŠU¯éT4n8bce•à•SGO³8»@½µÅÞ{—ë·o£I˜éÏðéç_àбã¬ûH«‚©f°…¡´–ÒZlÙÅ¥ƒH–½JÈ€a£RD¥R¡B°ª˜˜¹£=V3Ql42Ó+øÜkŸæµžãw/ðßþ&íh„DÏüÜ€áyž;}Šc ó¼úìÓÌö+ÖÖVñÎeB>F¢k©c+´4¡%Å\ÔKXHôÝŽGÂD¥Œ†>Ð7`P¯<‰˜¹–ÎÿJLDlÌR[IYZk+BYdO¬ž…žäq”é5xHè}·Ü×eiûÎ"Üy’«¡•èræD¹“Õ…‚`’ ãN˜1Pìä$‹ê=ÅtRü»â-2Å*Ë´y>»GK»ŠüÎøéÞ.â!7;ÛÝ»Èì}T‰=<@ñ„Nî?õýîWü;{FQûTù]/ù½m}¤_Ûø0´º²ÎŸý³³%o¾ùfö& y4„#4ÁÈîÀöñÈ+j$6ÂÑOsäHÅ¥ë3TíÛ” „¨©ë%£éØkXß¼Ã÷¾w¿þŸþ §N=Ï—ç·9ûì^ÿÌS”%7nÜÂ{Ÿ35å8Îèñ®eÔiëb¡ô)˪†íuîܾÉõ׸|õ ++ëhŽ.-ñìSgé÷z\Y½Ã­ Z“¹#PXƒ-„CÙE»f;ïL^rÇ ©+Æ=Sät¹nî.8IÌô*Joþà-Þ¿üª-¨çÌ©ÃüÂO’çÂÅ |pýÞµ¼øô9†õ6ë›w»Â1&u›„O‘::FÞ3Š-±ë(Šn‡#gIG`g Õ*I’;¯—AÙì#|Ó~¢Y} ÀÇé,>"øG’Ë‡Ž˜ö=Þû²ÿ”GZÑ„¤Ž3ç>͹³'ø£ïÿ€¦Þ˜|=ÅD ÝÍgrÚ¸°ï]%s‘(Çxíål¹y6¶ÖHÍU Ró )ÊŽpò>öÛ¹sç ·W{ü_ÿ+<ýÌøÒoþk._{µæ.^më Îgcºˆ!åmmic nFͺ¢èÍŠ^#‚m!¾åÄñ|êÅ8yä(·nÝâ[o½]XCÄ©ÒØ’h“Ûˆ  ŠÄHÉã$$)Д ]1SÄeë ”¶ÂJA ÆiÁo{î^_e´6Ä´ N8½tœŸþÌç¸úÁU~ïË_e{mvsHO-'áú¥Ël­m!.`ÏüCˆÝÎFBbžáG¯4md«‰Ôš÷^J$ïh¶2 KI%=c( K"Ò¤DÆ`! ¥³G²]lG¡[r©,E¯ 7[ÒŸ)”†ŠD)‰"L×MHèR £Ë ák4f`HÞ\ >{€§D—01 ˆ Aó¸3ú¼ñÝql92—ŽÙy=ç3Ò1=Én–ÝÓnïIR9¦%KúµO‡!²‡´Núx*'¹w1ïc‡þ ¹ÂN8òãÓúçè¿ü„€ã“üó!:ˆG‰}^Br?0É&€¶ZäsŸ}•÷Þ»Àòí›ûtÚÞó Üt'¡iU!#6Gž?ÿOŸQÞ»¶ÀpëRÜÊ|QŠÎqVEö…RU—/¾…é¿È¯þµÏ°¼bùÝ/ý&n8DS¤œ1ƒìî£Ïëj)BÂùˆsJë#u©]ÃpÔ’‚£(•^Àñ£'xêÔI6–—ùþ7¿ÎÅ÷ßÅÕ[˜1ÄV˜²‚Á ¾ìSW}jS4ϵI9É­PK™À¨!)(P$v«">+ž$%ŒµEÞn7㫚rᛩú¼òÒËlmlò?ø&ÒWÎ?õ4?÷…Ïsá \zÿLôÙ—j<ÖQ‡¤I™‡Èc%!Û…øè;Ûò[ŒF bÞHïNÞ‚ŸÌÀ ’£Y ƒ-”D¤N mð¤”ò¦·ír´McÊïs·aŒ …¥èTs=fýžÐ·Ð#R(S¦ìûDòà4ÖZ4„¼|ç|¶é$ÌÁ4š¼±Id¹lJˆf›ÝSêǰw¬4!„u§„ÉT-èî"¿Õ‡<=@»Ï'÷v.÷<ž>ÙQÎ y¤gtßéÑC<³äºšúÔÿIvO ØK<ü¼ÑÝ/1?ýÓŸcuå.¼ÿ.ã Šýn€qÖð4qm‹6c¢˜{Ž×_¬XÝ´Ü^^£m¯:9<™.®gü³uÒn'|ñû¿ûû|ö§~–_þ¥Ÿcc8àîê%/%Ô­í-l¼WavÀ%«rb–qjVh¹è©CË0ÔDñ8­Y^[æÖŒF#\h©7·ØÚ\'ú!/Ÿ{š—O¢Ù±åj\ipUASTÔbñ"SЬ`1E·åmósOt8$)\ …GR6çz“³7Jk8rä0³ƒ‚,-,ðêK/qîìYÞúã·xûO~@h3EŸ³§žâäÑchq›-Òf.DÚˆ¸ˆñ) ˜à±­CkG[;ê¶¥5xß 1–¼•ž´ë@²“$°ÉPa¨¬Å¢õ´¾¡õï}VÁ®t»Îl5óc&{.™^ŸÞ\þ\IP2}«”&’=as‘'yT3àiÌ^XÁ%bèí‚CAt–$w^јmXˆa,ácoðФút scëKQv+•ó¯ÂÞ„ø£ñƒªÿýïãݸ SÒZݽ±÷n}„j´s‡+¹.ê‘Z˜{{ýÆvšÍ÷Ð’&S@ó1¶Wpìò¸xñx¨½÷±BŒ—?õª†7¿ÿIÿÐ?S»Šb²º1ÏsÏãÈ¢åÒ‚P_$Ä!JŽßÈe ÝM“€Â–œ~j ï^äÅ—>Í/üÂçùW_zŸ™þƒÁAnÞZ¦­ÁE’IHOÐ\ÈöÜI3‘1E’‰ÙÙ–@ЖÈÞ¬ep°…¡, K‹‹œ?û ÇáÆëüàÒe6¶G¸”rÆ‚g -–V—r¶BR jcË®øƒj$©£’ECІm@}>Å…%FØXÛ êUœ>}š^UqçöþäßâêÕëÝÌ=øÞxãu~ìÓ¯róêmÖVÖÑØ¶"݈K0ăxƒxÅx°AŸHmÂמzØÒ4#œ6ˆIÆbÅt#¨Sµ¨äA”)©lAa•DÀGÝäÈâdga§ jV 9¹Î”ت è÷©fû %ƒ~AU)•‰”V)Œb$"b² zNTÔ"¤Üé 1T¨H* æC‰jîrwÄΙˆûdïÞPW‚v ™t÷kz×í¨û }•ÇöÌÙÇ5Au×ý¯òaæò$Ä?¹}/cúÐÎáQª­<N}<—ä Ç#w?LÊÕƒ( ÓÅŒ‚rúÌ3=z”oë«Ýf²<Æ«dç¿> ¦<Åë/ M˜çÚÉ]Ùë8¾uÒQèäðväÈÊRùÁ…›üì~‚Ÿÿù/ð[¿ý6W.›ÑpDJy.]"4‰˜¶(”à1$bÈP¾Í‹‚)4f‚Û»†ª„gŸ>Çg^{ƒ§Ïžckm™o}í·¹páOmÞEFд@$‰%X¥- ®,pœ±Ô)â¢c~Dr.µ©,…ä¼è Äî#ÑE´ @"FeåÎ]®_½Îõ+7X¹½J]7]§räèþÜç?Kˆ‰ßý·_áÆõëÄØ‘´z/›3#‚é–Mw:6Fõ _F[ µ¥¥(º¨Ó)E¡ VJJ)snyi›h|C=áG Ýrf7rÓn—†ñXR;õ\Qåîb0K¶G¿2Te¶@/ŒR˜Dib=b"t¤|¦¾¶ÊÒ`(A*R*±Z!Z¡Á€†ÉJÈ;L +tzƒ{ªÞOKÇe×ñU¯± S„{FO»‹î3Œjó±×Ç'JËc}¯>jwó šñ}Àx$€x¸a±<Öïpת“ÌÊüÁüðâ‹|íkÚ’ÒãÝc‚=ËóÏV,Þù À5—A·wnM™Ô¸îãnƒ;)[[[çY½» æo¼~Š…¥çù'ÿï?&†­å¦®%Á%T è™uÎΖܸ~›£Ç_à§êsóÏóï~ëÝN&·"±) ¶49gZÇjH%Å»DpÊÖæ&ï]¼Èû—®°¶9¢ ž"Ë`nŽçŸ{³§Î°ró*ûwÐ6ƒFÛ¼¥[¸²ÄUg ¾04Fh B! DÉ jF“ˆšc>Sê¶ÝS"¹—âRDT8tì¯ÿÄkXkùÃo|—Þ»HŠÙeI:|ˆgÏ?ÍùóÏòì³çX:´DÓ4 ·‡cñ;»Å²=·åŽ{÷ûÊ^I¾NÔÆºáR‹ˆŸ’ÕŽA%wa™P·X,=[RU%ÖBr´®Åµ-1Ä©ÓH×M$í>L;ùà*9©®ìaËEYQ–Â@!‘BZ„ÄåNSÀHBŒf°(,Ɩآ¦ìcÌ,Æö»®Œä0(³+%n ;ÆäÂí™& Üÿ˜¦¸åQb÷¢îòÜÇ#‚ƒ|òpß¹Æý– ïWd:«zÔd¼O¨»xPWq€øÐOTûÉ©v!=v–sç’ï}ç{x¿òÈ#Ö½#+ƒàc'ÎpxAYZ.ßè±¹vaûD‹Ì\àÔ™3¸¦åÊ•·øòï^àÏþ,oüØÞ{ÄåKßA)°û‰M”î”X0…Lò馉àrkCdÔxÃÂÒa^xþUž;ÿ2"7®^¡¾»Æhsvk¿µMÚÚÌ61KBCaÞhö¯2ÐH“P£9m¯°ha1Vr¶ÿugÖÇqeáïfVu£±pßLk#E-a;äÛó0óÏæOÍËDL„'Æ![cÙ²eY%Rp@bïZ2óÎCfuUcá&@òð¥»ÑÍêZºîÍ{Ï=ç4ZR(öuR`µ†gܼy›­Í-Œ1„‡üê׿äê»WñÞóèÑc¾»u—©©)Þ~ç Ê¢f}}3zqE}ôTµ Û,2æè8™§¯Ø-)F#ʺDMEff”~/ã ¯±j̰ä6£—E,Æ«£¬Jê²KÎ[‰XGÓ‚’&iø0$!`›c²¶×ÃX‹¡ÆP 8T“É‘*JHþB‚µks$Ëɲ6`íczQ"ÞÄi¬¤Î«-‘NõpÐ$Ñs’¡èL`¼(òÉdu×59ÝôÈÚ%G ô=qŠ_¿|Gäµø°¯û‘¤¾÷¶¡ŽhŠé{´œšÕ¡Q|b†¿æÉòߨªÇû&"äe.“(H¿›_¸Â¥‹GÞrki ñï£uö)·±u0ÎÐïo°½}‚_ýÓO8wþ:ÿù_$+x²É_HýÒ „Z >ñÄtÚ¾é6(Áf§çùÙ{?çÃ~ÁÂâ)–Ýçÿü1·nƒ÷žþ`@nÁ ÊÝmÜ½ƒŽÊhëéA§àEqDÅÙÚ{ 0¯B4Ü÷|Þ¥D’Iðìnï°¾öŒºØ †Å“ üë¿ý ý©>ÿóßóå7Xy´ÂÆú&£Ñˆ7ßz“²¨xôðqlã4I!µx’jELmNˆç+t^wÿ .ᣂÝbD©#ŒuXi%]b¢I±/ÿÉèCž[0çjª²ÄÕí˜t˜Œ˜š´ÄB6Y˜&ϱy¬R„ ¡@´LÕŒ|$ÿÄσ±Öæ;Efûˆô°b±V{<Žé‘Is"Ù3Æ-“Œ‰=Èõ+Þ’2¹¢9PºBá ™¤Ã–šGÅ4>î CŽîÃ/e+û}™¼nâ;º/NrüW$³àÕ 2Äç¿dwãS\µvhï…*Q Æä \ºpcs3•g³µ{­dÈþ:W³±¹‰ÌÏÏ3œžåæ·_Ò\ã7ÿ<ËÓÑûüõ³ÿ ·nß÷ï›”Q¶cMÛ{ŽB‘U}ê,‹ó§¸{ç.Ÿ|òî-/3*jazfÀìÌ4½~¼Ÿ1°]Öê’Pí"u#(kÆÂ†jp*8 O…¯“4yLÁÔ€±Šš@ð5µO¢ƒ(*Q|°®*f§û|ôëØÝñÛßþ.¶’â 33Óüì£á‹Ï¿d{{'M 5BHÉAÛäÚ|ó¼_tbì] Ú©…ÐØ´j÷ó5ûj$êebɳœ<OY(‹è±a›I…Òvt\¡ÄqÔv[`‘¬u³l–<à  B4úQx’‘R«E©$CL?&òä|ñ–†¹l:~ûØËÊ~ nрد=.y VÔÇÚ‚ú>VIyÅvÙ1UVÌ«Urĉb «`í|ð>£ÍÏ îY'C¶Ê9¬–P2ݲÇÂÉ“ÌÏJ\ÝÉ€{Ë·öÜ "b˜azzš¢,ØÜÜšŠÍmÏ•ËùåÏÏpcéËK¿Gl‡ kº›j _¤é-‡N¯×4@¥°½½Í;KÜð ÂùÓ¸öæuÞzã*ýþ,ƒþ Î_¦,kv«’^–“â |±M(wQ_"eq5‚æÍs\–ámŽ¡¶–"ñ%Bˆ¹™äWOíÞÇñ\P®¼y…ápÈŸÿø)ëë(J>•séÊE~õ›_b¬áÓOþÄ“Ç+q¼6ÇF•µü#î¡íã4o«Ž -€ÛM.cWBõ®£( ʲÀQ§þ~è̉&¶}gŠI°dbéåÑrTƒ£ªKêº"8Ÿ0i lÚŠó5‹ÚmLM± Æ8ŒÔ-!xBÌB$Ý…ãAMÄÖÄ¢QÇ—ùë…îŽKÜÄT‘LV戒ÄsìnE÷R‰I~Äx~ìÅ,¿bÂ8ö ^“ñ²-&iÁL25û£í¨–n=äø:nž<}T8¦‡µJ– +k†Í{ˆ¸IûÔ‰ŠÆròÔ)Œž=}FQŒ¢Ë˜LŸ¸È¹S†·Þ¼ÈïþpW/'s™.ô(ûúµÒi»·‰ˆ1Pìƒ255Å×ßçêÕwÙX_çÛo¿eii‰[K·™Ÿ_äòå7¸}{‰Qµ–,둉AëŠ:¹±QPŽÀ¹Øß7BÈ ¾g Æâj›$Aìø¨°IÊÚ€‘íꚢ*™™›eñäSƒ>/çÝ÷®rþÂYîÞ»ÏgŸ}ÎúÆ:b…ápŠ~¿ÏÎîÎû¨ ;N !a1)„Î㸺h¦ŒÚGm0æu“@<ø:P¢¯FåJ¼8 !NÑbãÊ"U –HÌšöŸ:ê:º÷yçǘHÓ·²Ð.¤“a­ÁXÅÚ:%‹¼†K>Ú²ú’  M^ Š>‹‰Ï#ÉÆ{"qH;%6!°×ñ{8’ਓ|º1ùïEzÇKe¡üZ@È1ymsD×!&ˆ×8¶£º@"-YÈØùà´¼ƒ«×^³Rnz·Š5–:Ì3Lsb& xÖ·2V×VÝŒDª» JU–LMM±°°ÀÜÜ333ìì<㟮rýú5æO([; ܺñ9Æ–·w'D ÷6¤¥p!Ï-ï½û>çÎã÷Ÿ|ÌwK·ØÜÚÄ˵·¯òÓŸ¼ÁÒÒmîÜ»OUVÔ>öjÄò¼O&Š/ \YF‰2ú>h%7ÔKì¦'œœQª´Ò7iå­VPK v† °½³ÃÊ£Ç+ô§úîÞ¹Ë_?ýî/ãB1%05èñÏ¿ùˆK—Γ÷3¶¶¶q  jb}'…ÞF^›ÏtÆQÛ¤RKN“‡CS¤$딺»EUà©Q m :1R:ž²RÁb°Æe&â¡¢**œ«ÇIACg c€¥e,ˆ±˜\È2µ†”´Ô‹L{š)ªë† QC‰¹oŠI&|RÆ÷Ž´<”IËë—`K\w§÷M{¾âjQ8vk‡#ßìk!Ç µÿ“ò@w[A¼Æqé%ˆ&EØ|€É/#á>Uñô¥(þÝÕøAI3‡±ÓÌ€~®ln)+«›øz•XJã!„äu쩪ŠÍ­-Ö××ÙÙXb·<Ç×9yêßÞÞd{ëc‚ÓĦ“kÈx˜0ÍÖ6ÿmnvŽ™Ù¬X.]¸Ä{ï½ÇÌô,_~õÿú«TÒþ9ïãkUL–ÑË3,Mþ”’Ù(«”TÆü«èé¦8J’z®65É’dÑM­öŽ'«+<¸·ÌÝ;K<]{B]×±UEÍ©þ Ï¥+—¸zíææX[}ÊÓõ5œ*­öÕ8)R»«î5­ôÇ8Åxê¨Ásð»M"c»W|­”»5EYR¿¯™’J×E;U@ÐVêÍŠ‹É#~R»*¶ |h'±þ‹OzL®M±ò 5“yLæ±ÆalÀ¨'ZÚ%²FçúGïs›„AU:çJ;‰¨3¡´7€ïWžˆ{†>'ÆÈ~zÄã¶òšÁë¶£þñ7ö”,^òýäIýê@ÖQ¡÷ éÌ’÷/âªÇ¸úéK]ƒÛ¡íŒ¹˜6;Åì4œ˜1”•rïÁuOPuÄ•ïå=ææç 8ûȽ¼ÇÜÜ<Æn~ó ‹§ßçí+ANóÍ/€]ÝïP¶E™”„hÎA v›[[<]_cq~‘³gÏ1*Gñˆ¾ß™5ˆzB¨ÑºB\”µ¦(cëɻăäÉ]üœ‚k‚ucìĈ’ƒ5Œ¥fõ>ŽËg¦ùÉ•+¼ÿÁufg¦ùìOŸññdzüàA. qÿbp&ñQ4='¬ÒkWiõÞà„1‡!àÚ©>b•¡¾­6BõÈQ”U]ã‚‹ß§:>¶qU!š€èx­Lj5fYt† Zã\Uaƒ'Ÿ’ZªÔ§ªÇ£¡yÞòMÀ(b<ÆÆDaMãý5dŸªQœ…UM M­@´ÃÊÞæÛËDe€?Pké€Å˜î­0žç)!¯t Ô–ã²ÿß³‹¼úû“ âήõ>‹Ad†|ê"U± ~ãåÄž*¢û7UöÓƒŒÅyÁfpwÙQQ­üм—3qÎQUA½^Á`ŠªrŒÊ§Ü_ñÖÛW8{ºÇí»ÖŸ}õf¢îIFÚö›·D(«’‡°üð>³3s\ºx‘éáÜf8ç8sæo^y“Q1bs}c<)åCJ•j1Ø„-Di É’T\ ¾Nj¤:ž2mŒDàQ¼Æ¶œ¨ÄvY+l3³¼ýÎÛ¼ûÁuzý>·¿»Åçù ——©Ê"*žÒ¶–ÆÊ¹ITЧ`Æývm“BóØ‘g»j‹]L®êWWmªZ©Ë@9rUE$ÅUb¢ÐÄÇÐNû©$ŠÚÚd^%ÑgݹˆÏ„àÓçCÛ ó>¶ÔÒsõi Ö7øC:Û&Œ“…1!ú{¤J'j6²#QnDšßvøTIè^r¾†Ø×q8À³zŸ­Ä¾1Œ# ?€ õ‘|Åkmèy$†@c¦=ïï¯ ä‡È2±Öo~ÓYo–íÛ7¹ñÍ =yÌÊÚ»»Û\»z ÊÃG:=±IÞAH õÌZLUïÁy´®cEáj¤Š}ñ˜(¢Ï²!`b¨‰¸…Ÿ+AYX\àÚõëL ‡|ù·/¸qã+ÖÖV¨ë M<Œàj²L䃜ÊUxïc²ERòò>‚·mrAŠ”T’U¬H“4BÒÔJ9%¢ˆo©ÃÇð^ U *娢¨êèl×§w1†&ø6ÁPc ‘(b%ghÀí&)ø–¡îCÚ¿ÎcˆÇ|ƒ¹ ªëÛDa£iô6MÖEÜÁ¤1Ü„Sìíkî F÷·‘äE‚Ž» Þ¶ªŽ0IðÃÄÍ#ËEß;ó¼ì«ü¨É";l¡ûÜê÷Ü+™Ü»f“‹÷ÞWÈë NL¶lRk"£F£JجQ®\°|wû[O!¦<°íU×5+«+mlìO÷#þþåçœ?û N/z~úÖ/øî›X{ˆ€TÓÀ>mîóSý)Μ9Çêê=z„1†™éiN.žäí·®òðÑCn|ûõDk P¼÷H‚˜è—`-SÆD!ÁàP"5Ô˜1µK°š‚7QÁÔK”ðè[C¦A(ª‚[7o°»µM]×ÑÈ)ä3ÓÓÌ/.púìfgg >õ2ž®?ãæíÛ”UE¤w·ç;:ôIâ9F9òÆóÙ$]¦vRÇÄŠC‰ã^˜@v'QÞq«'(!@]yŠmGÖ+¢ñP/§—¼3–¼6q ¨KT"®p8çp®"xí`kl¡#,¦ªSG­Ñ¸yŒ b ¸øÜ{mÉ–ÆFƾ€ ¤î½êǺ§ÅÙÕC…döÝiÚ9µiñ zðv^5¶é1H"æC;ö öÇôE‡lÖ"òïòƒ·ÍdO®0‘UšÍclW¯ xÄdˆ±‰ddsÈÒHÐÑ‘rÛËzÈ Ø6?͉Y˜š#O•• LØî*–¡@¯—377Ç`8$³ƒÁ€“'É{=Š¢D5jëlmo37–~®ÌŸ˜béÞέí3ay~ßUöTBQUŒŠ§OŸa~nÅù“\¸p‘……Eîß¿ÇW7¾b{g»sÏïõ” =¤1†,Ë1)àù´‚> ÑoZ¼™Ùbµ: qÓzçkª¢HºDBk¹|å§\ÿðCNÌͳ¹±É½;ß±tûOŸ®qúä)yÎúÓU‚8°I¤i?¥µ÷ç]TÄ ˆ÷âsmå-V.VlŠZ–¶ ÑØ&kÁî„gH+E« Øv¥§*¥«¨Ó*_;`¸-§BÓ˜jHÕژ౺ñÁãÓ[>VnãíMðC¯¢Øw'º ªÉŠø$úב$i˜Î]—:Iƒ{ØÑ‡†{•Iû uØ^¤©Èá>rDáâ™=²Ô‘—&òœªãx1ŠìÇÉ–“«š†+¢_£¡ž0÷ž “º´)0ݧe£¢­°›Ž¨Ë’õÍ)æN@fàü©Œ x¶ºgy:2Ç®öŒF»dY>nìììPÕ±G…Ö¹{÷ξAfΟgé»;`k:³&{ŽõëHmïNM+¸‡²¹±Á`zõz¹¢( êºÆ‡Àé“§8qâëëlïlâœß×fPUÔÇ60Ðïõ ¾vŒv ê„[ˆ´;%>£Æ bP›Å¶“I€€UC.^Ò3²ÖrùÒ%.^ºÄݛ߲²ºÊÖînšûwEIu¹ÄÚŒPE W¬ yŽd6ò#¡ÆØèšj+Šä dLlµÓ°M”©hVàYdPG ÆÄ»Ðb…ƒ%bÒô#¨ O‘EµÚ<·ÑÛ±´lcã¹ AÀmUŒ˜D:T|ð$?IÇ&†¤­ÆKi‘˜Tª(bŒ"â&Íy3ÆŒ|Ô$Ð=a]×ïí¥v¼ÔÍÞ¥ûH‹‘I5qØ6^EIïÇZ«V™+ò|ØdÂ+Éžþ ‡l¿Imì”IEND®B`‚jtreg7-7.5.1+1+ds1/univocity-parsers/pom.xml000066400000000000000000000152601475274123300206040ustar00rootroot00000000000000 4.0.0 com.univocity univocity-parsers 2.9.1 univocity-parsers jar univocity's open source parsers for processing different text formats using a consistent API http://github.com/univocity/univocity-parsers GitHub Issues https://github.com/univocity/univocity-parsers/issues Univocity Software Pty Ltd www.univocity.com Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo A business-friendly OSS license https://github.com/univocity/univocity-parsers scm:git:git://github.com/univocity/univocity-parsers.git scm:git:git@github.com:univocity/univocity-parsers.git jbax Jeronimo Backes jbax@univocity.com +9:30 parsers univocity parser development team parsers@univocity.com ossrh https://oss.sonatype.org/content/repositories/snapshots ossrh https://oss.sonatype.org/service/local/staging/deploy/maven2/ org.apache.maven.plugins maven-compiler-plugin 3.1 1.6 1.6 org.apache.maven.plugins maven-enforcer-plugin 1.3.1 enforce-versions install enforce 1.6 org.apache.felix maven-bundle-plugin 2.5.4 com.googlecode.openbeans;resolution:=optional,* bundle-manifest process-classes manifest org.apache.maven.plugins maven-jar-plugin 2.5 true true ${project.build.outputDirectory}/META-INF/MANIFEST.MF test-jar org.apache.maven.plugins maven-surefire-plugin 2.17 -Dfile.encoding=UTF-8 maven-assembly-plugin 2.4 project org.sonatype.plugins nexus-staging-maven-plugin 1.6.2 true ossrh https://oss.sonatype.org/ false org.apache.maven.plugins maven-javadoc-plugin 2.9.1 attach-javadocs package jar ${JDK8_HOME}/bin/javadoc true org.apache.maven.plugins maven-source-plugin 2.2.1 attach-sources package jar UTF-8 UTF-8 org.testng testng 6.8.21 test com.univocity univocity-output-tester 2.1 test org.hsqldb hsqldb 2.3.2 test release org.apache.maven.plugins maven-gpg-plugin 1.1 sign-artifacts verify sign jtreg7-7.5.1+1+ds1/univocity-parsers/src/000077500000000000000000000000001475274123300200525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/000077500000000000000000000000001475274123300207765ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/000077500000000000000000000000001475274123300217175ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/000077500000000000000000000000001475274123300224755ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/000077500000000000000000000000001475274123300245265ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/000077500000000000000000000000001475274123300262055ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/000077500000000000000000000000001475274123300305425ustar00rootroot00000000000000BooleanString.java000066400000000000000000000041271475274123300341000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates that parsed values such as "y", "No" or "null" should be interpreted as boolean values. * If a parsed value exists in {@link BooleanString#trueStrings()}, then the field will receive true. * If a parsed value exists in {@link BooleanString#falseStrings()} then the field will receive false. *

A {@link BooleanConversion} will be assigned to this field *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface BooleanString { /** * A set of Strings that represent the boolean value {@code true} (e.g. "y", "yes", "1") * * @return Strings that represent {@code true} */ String[] trueStrings(); /** * A set of Strings that represent the boolean value {@code false} (e.g. "n", "no", "0") * * @return Strings that represent {@code false} */ String[] falseStrings(); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Convert.java000066400000000000000000000041221475274123300330240ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Assigns a custom implementation of {@link Conversion} to be executed ({@link Conversion#execute(Object)}) * when writing to the field and reverted ({@link Conversion#revert(Object)}) when reading from the field. * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Convert { /** * A user provided implementation of {@link Conversion} which will be instantiated using the arguments provided by {@link Convert#args()} * @return custom class used to convert values */ @SuppressWarnings("rawtypes") Class conversionClass(); /** * The arguments to use when invoking the constructor of the class given by {@link Convert#conversionClass()}. * @return list of arguments create a new instance of the custom conversion class. */ String[] args() default {}; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Copy.java000066400000000000000000000056751475274123300323340ustar00rootroot00000000000000/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import java.lang.annotation.*; /** * Allows copying values of meta-annotation properties into the properties of an annotation that composes it. For example, * consider the {@code @MyReplacement} meta-annotation defined below as: * *

 * 
 *
 * {@literal @}Replace(expression = "`", replacement = "")
 * {@literal @}Parsed
 * public {@literal @}interface MyReplacement {
 *
 *     {@literal @}Copy(to = Parsed.class)
 *     String field() default "";
 *
 *     {@literal @}Copy(to = Parsed.class, property = "index")
 *     int myIndex() default -1;
 * }
 * 
 * 
* * Values set on attributes {@code field} or {@code myIndex} in {@code @MyReplacement} will be assigned to the * attributes {@code field} and {@code index} of the {@code @Parsed} annotation. This allows you to apply the * {@code @MyReplacement} annotation to any given field of your class while configuring the field name and index * to be set for the {@code @Parsed} annotation. This eliminates the need for adding explicit, additional annotations and * their specific property values to each and every field. * * The following class can now make use of the {@code @MyReplacement} annotation to apply the the annotations * {@code @Replace} and {@code @Parsed}, configuring the properties of the "inherited" {@code @Parsed}: * *
 * 
 * public class MyBean {
 *
 *     {@literal @}MyReplacement
 *     public String id;
 *
 *     {@literal @}MyReplacementUpperCase(field = "client_name")
 *     public String name;
 *
 *     {@literal @}MyReplacementUpperCase(myIndex = 4)
 *     public String address;
 * }
 * 
 * 
*/ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target(ElementType.METHOD) public @interface Copy { /** * Target annotation class that is part of a meta-annotation. * * @return the class whose properties will be set from a given attribute of a meta-annotation */ Class to(); /** * Target property of the given annotation class that is part of a meta-annotation. * * @return the name of the property in the given annotation class that should receive the value of the * meta-annotation property. */ String property() default ""; } EnumOptions.java000066400000000000000000000101251475274123300336050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * The {@code EnumSelector} annotation is meant to be used in conjunction with enumeration attributes. * *

Values parsed from the input will be matched against one or more properties of the enumeration type. * By default, values read from the input will be matched against:

*
    *
  • {@link Enum#name()} - the name of the elements in the enumeration type
  • *
  • {@link Enum#ordinal()} - the ordinal of the elements in the enumeration type
  • *
  • {@link Enum#toString()} - the {@code String} representation of the elements in the enumeration type
  • *
* * You can also define a {@link #customElement()} of your enumeration type (an attribute or method), as long as it * uniquely identifies each value of your enumeration type. * *

Use the {@link #selectors()} option to choose which properties to match the parsed input against, and in what order. You will only need to * explicitly add a {@link EnumSelector#CUSTOM_FIELD} or {@link EnumSelector#CUSTOM_METHOD} to the list of {@link #selectors()} if your {@link #customElement()} name * could point to both an attribute and a method in your enumeration.

* *

This will assign an {@link EnumConversion} to this field.

* *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface EnumOptions { /** *

A list of properties of the enumeration type that will be matched against the parsed input to identify which enum element should be assigned to the annotated field. * By default, values read from the input will be matched against:

*
    *
  • {@link Enum#name()} - the name of the elements in the enumeration type
  • *
  • {@link Enum#ordinal()} - the ordinal of the elements in the enumeration type
  • *
  • {@link Enum#toString()} - the {@code String} representation of the elements in the enumeration type
  • *
* @return the sequence of properties of the enumeration type to match against the parsed input. */ EnumSelector[] selectors() default {EnumSelector.NAME, EnumSelector.ORDINAL, EnumSelector.STRING}; /** * * Defines the name of a custom element (attribute or method) of the annotated enumeration. This will be used to match the parsed input and identify an individual value of the enumeration. * The attribute value, or object returned from the method, should uniquely identify a value of the enumeration; * *

You will only need to explicitly add a {@link EnumSelector#CUSTOM_FIELD} or {@link EnumSelector#CUSTOM_METHOD} to the list of {@link #selectors()} * if your {@link #customElement()} name could point to both an attribute and a method in your enumeration.

* * @return the name of a custom element (attribute or method) of the enumeration which will match the parsed input and identify an enumeration's value. */ String customElement() default ""; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/FixedWidth.java000066400000000000000000000053051475274123300334470ustar00rootroot00000000000000/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.fixed.*; import java.lang.annotation.*; /** * The {@code @FixedWidth} annotation, along with the {@link Parsed} annotation, allows users to configure the length, * alignment and padding of fields parsed/written using the {@link FixedWidthParser} and {@link FixedWidthWriter} * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @author Univocity Software Pty Ltd - dev@univocity.com * @see FixedWidthFields * @see FixedWidthParser * @see FixedWidthWriter * @see FixedWidthParserSettings * @see FixedWidthWriterSettings * @see BeanProcessor * @see BeanWriterProcessor */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface FixedWidth { /** * Sets the length of the fixed-width field * * @return length of the fixed-width field */ int value() default -1; /** * Sets the alignment of the fixed-width field * * @return alignment of the fixed-width field */ FieldAlignment alignment() default FieldAlignment.LEFT; /** * Sets the padding character of the fixed-width field * * @return padding of the fixed-width field */ char padding() default ' '; /** * Configures whether to retain the padding character when parsing values for this field * * (defaults to {@code false}) * * @return flag indicating the padding character should be kept in the parsed value */ boolean keepPadding() default false; /** * Defines the starting position of the fixed-width field * * @return Defines the starting position of the fixed-width field */ int from() default -1; /** * Defines the end position of the fixed-width field * * @return Defines the end position of the fixed-width field */ int to() default -1; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Format.java000066400000000000000000000065641475274123300326500ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.BeanProcessor; import com.univocity.parsers.common.processor.BeanWriterProcessor; import com.univocity.parsers.conversions.Conversion; import com.univocity.parsers.conversions.Conversions; import java.lang.annotation.*; /** * Indicates that a parsed value is formatted and must be parsed before being assigned. *

The {@link Conversion} type assigned to this field will depend on its type.

*

Multiple format masks can be tried for a single value.

*

When reading from this value (for writing to a given output), the first mask declared in {@link Format#formats()} will be used to produce its String representation.

*

The {@link #options()} is an optional configuration, with properties and values separated by =.. Each property will be used configure the underlying formatter. For example, * if the parsed value is a BigDecimal, and the format is '#0,00', the decimal separator must be set to ','. To specify this using the {@link #options()} annotation, use: * *

    *
  • formats="#0,00", options="decimalSeparator=,".
  • *
  • The "decimalSeparator" property will be used to identify which method in DecimalFormat to invoke. In this case, the method "setDecimalSeparator", with the value on the right hand side of the = operator
  • *
*

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor}

* * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Format { /** * Formats that define how a value can be formatted. When reading, the values parsed from the input will be parsed according to the specified format. If multiple formats * are defined, the first successful parsed value will be used. When writing, the first format defined in the sequence of formats will be used to produce the correct * String representation. * @return the sequence of formats to use. */ String[] formats(); /** * Defines a sequence of properties and their values, used to configure the underlying formatter. Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3", "locale=en"} * @return a sequence of properties available in the underlying formatter and their respective values */ String[] options() default {}; } HeaderTransformer.java000066400000000000000000000136351475274123300347510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import java.lang.reflect.*; /** * A transformer of headers used in {@link Nested} attributes. Used to reassign header names/indexes of * attributes of a {@link Nested} class which is useful when multiple {@link Nested} attributes of the same type are * used within a class. For example, consider the {@code Wheel} class defined as: * *

 * public class Wheel {
 *     @Parsed
 *     String brand;
 *
 *     @Parsed
 *     int miles;
 * }
 *  

* * And a {@code Car} which has four {@code Wheels}: * *

 * public static class Car {
 * 		@Nested
 * 		Wheel frontLeft;
 *
 * 		@Nested
 * 		Wheel frontRight;
 *
 * 		@Nested
 * 		Wheel rearLeft;
 *
 * 		@Nested
 * 		Wheel rearRight;
 * }
 *  

* * The {@code HeaderTransformer} allows us to "rename" the attributes of each different {@code Wheel} of the {@code Car} * so that input columns can be assigned to the appropriate places. * * Assuming an input with headers {@code frontLeftWheelBrand,frontLeftWheelMiles,frontRightWheelBrand,frontRightWheelMiles,rearLeftWheelBrand,rearLeftWheelMiles,rearRightWheelBrand,rearRightWheelMiles}, * a {@code HeaderTransformer} can be created like this to assign a prefix in front of the header names derived from {@code Wheel} (originally just "brand" and "miles"): * *

 * public static class PrefixTransformer extends HeaderTransformer {
 *
 * 		private String prefix;
 *
 * 		public PrefixTransformer(String... args) {
 * 			prefix = args[0];
 *        }
 *
 * 		@Override
 * 		public String transformName(Field field, String name) {
 * 			return prefix + Character.toUpperCase(name.charAt(0)) + name.substring(1);
 *        }
 * }
 * 

* * This allows us to to define the {@code Car} class as: * *

 * public static class Car {
 * 		@Nested(headerTransformer = PrefixTransformer.class, args = "frontLeftWheel")
 * 		Wheel frontLeft;
 *
 * 		@Nested(headerTransformer = PrefixTransformer.class, args = "frontRightWheel")
 * 		Wheel frontRight;
 *
 * 		@Nested(headerTransformer = PrefixTransformer.class, args = "rearLeftWheel")
 * 		Wheel rearLeft;
 *
 * 		@Nested(headerTransformer = PrefixTransformer.class, args = "rearRightWheel")
 * 		Wheel rearRight;
 * }
 * 

* * The above annotation will prefix the {@code frontLeft} fields ("brand" and "miles") with "frontLeftWheel", effectively * forming the header "frontLeftWheelBrand" and "frontLeftWheelMiles", which will match the input headers and assign the * correct values to the correct {@code Wheel} instance. * * IMPORTANT It is mandatory to define a constructor that takes {@code String[]} as a parameter. The actual * parameter values come from {@link Nested#args()} to allow custom configuration of the concrete {@code HeaderTransformer} instance. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public abstract class HeaderTransformer { public final String transformName(AnnotatedElement element, String name) { if (element instanceof Field) { return transformName((Field) element, name); } else { return transformName((Method) element, name); } } public final int transformIndex(AnnotatedElement element, int index) { if (element instanceof Field) { return transformIndex((Field) element, index); } else { return transformIndex((Method) element, index); } } /** * Transforms a header name * * @param field the field of a {@link Nested} class whose header will be transformed * @param name the current header name associated with the field of the {@link Nested} class * * @return the transformed header name to be used to read/write values from/to the given field. */ public String transformName(Field field, String name) { return name; } /** * Transforms a header index * * @param field the field of a {@link Nested} class whose header will be transformed * @param index the current column position associated with the field of the {@link Nested} class * * @return the transformed position to be used to read/write values from/to the given field. */ public int transformIndex(Field field, int index) { return index; } /** * Transforms a header name * * @param method the method of a {@link Nested} class whose header will be transformed * @param name the current header name associated with the method of the {@link Nested} class * * @return the transformed header name to be used to read/write values from/to the given method. */ public String transformName(Method method, String name) { return name; } /** * Transforms a header index * * @param method the method of a {@link Nested} class whose header will be transformed * @param index the current column position associated with the method of the {@link Nested} class * * @return the transformed position to be used to read/write values from/to the given method. */ public int transformIndex(Method method, int index) { return index; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Headers.java000066400000000000000000000057401475274123300327660ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import java.lang.annotation.*; /** * The {@code Headers} annotation allows java beans to configure how to handle field names in a given input/output * *

With this annotation, you can configure the sequence of headers to use when reading/writing:

* *
    *
  • when reading, the given {@link #sequence()} of header names will be used to refer to each column, irrespective of whether or not the input contains a header row. * If empty, and no headers have been defined in {@link CommonSettings#getHeaders()}, the parser will automatically use the first row in the input as the header row, * unless the fields in the bean have been annotated using {@link Parsed#index()} only. *
  • *
  • when writing, the given {@link #sequence()} of names will be used to refer to each column and will be used for writing the header row if {@link #write()} is enabled. * If empty, and no headers have been defined in {@link CommonSettings#getHeaders()}, the names given by attributes annotated with {@link Parsed#field()} will be used. *
  • *
* * *

* This annotation has no effect if {@link CommonSettings#isAutoConfigurationEnabled()} evaluates to {@code false}. *

* * @see BeanWriterProcessor * @see BeanProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) public @interface Headers { /** * Returns the sequence of header names in the input/output * * @return the sequence of header names in the input/output */ String[] sequence() default {}; /** * Indicates whether a row with headers should be written to the output. * @return a flag indicating whether to write the headers to the output when writing instances of a java bean. */ boolean write() default true; /** * Indicates whether the first row of on the input should be extracted as a header row. * @return a flag indicating whether to extract the headers from the first valid row when reading. If */ boolean extract() default false; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/LowerCase.java000066400000000000000000000027571475274123300333040ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates the String value of a field must be converted to lower case using {@link LowerCaseConversion}. * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface LowerCase { } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Nested.java000066400000000000000000000045621475274123300326360ustar00rootroot00000000000000/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import java.lang.annotation.*; /** * Marks a field as a nested object to be constructed with the values of the current row. It is expected that * the annotated attribute is of a type, or provides an explicit type via the {@link #type()} option, * that contains one or more {@link Parsed} annotations. The given type and its {@link Parsed} annotations will * determine which fields from each row should be used to populate the {@code Nested} instance. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Nested { /** * Defines the concrete type of nested object to be instantiated, if it has to be a subclass of the declared attribute type. * * @return the type of nested object to be instantiated. */ Class type() default Object.class; /** * Provides a {@link HeaderTransformer} for reassigning header names/positions of the nested class. * * @return a transformation to be applied over headers/positions of the nested class. * Used for reassigning specific input columns so the correct values end up in the correct nested attributes. */ Class headerTransformer() default HeaderTransformer.class; /** * An optional sequence of arguments for creating an instance of the given {@link #headerTransformer()}. * * @return the initialization arguments passed into the constructore of the {@link HeaderTransformer} */ String[] args() default {}; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/NullString.java000066400000000000000000000034601475274123300335110ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates that parsed values such as "", "?" or "null" should be interpreted as null. If a parsed value exists in {@link NullString#nulls()}, then the field must be set to null. *

A {@link NullStringConversion} will be assigned to this field *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface NullString { /** * A set of Strings that represent a null value instead of a valid String (e.g. "?", "empty", "null" ) * @return Strings that represent {@code null} */ String[] nulls(); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Parsed.java000066400000000000000000000114561475274123300326320ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates the field is parsed. If the annotated field type is not a String, it will be automatically converted using one * of the existing {@link Conversion} implementations in package {@link com.univocity.parsers.conversions}. * * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} *

Implementation note: All annotations in @Parsed fields are processed by {@link AnnotationHelper} * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * @see AnnotationHelper */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Parsed { /** * The possible field names of a record. If multiple names are provided, the parser/writer will * attempt to match the given names against the headers provided (i.e. headers found in the input when parsing with * {@link CommonParserSettings#isHeaderExtractionEnabled()}, or manually set using * {@link com.univocity.parsers.common.CommonSettings#setHeaders(String...)} for writing or parsing) * * @return the possible field names (optional if the index is provided) */ String[] field() default {}; /** * Field position in a parsed record * * @return the position of this field (optional if the field name is provided) */ int index() default -1; /** * The default value to assign to this field in the parsed value is null *

The String literal "null" will be interpreted as a regular null. *

Use "'null"' if you want the default value to be the string "null" * *

this value will have different effects depending on the field type: *

    *
  • on fields of type {@link java.util.Date} or {@link java.util.Calendar}: if the null value is "now", the result of new Date() or Calendar.getInstance() will be used. *
  • on numeric fields (primitives, wrappers and {@link java.math.BigDecimal} and {@link java.math.BigInteger}): if the null value contains a number, e.g. "50.01", it will be parsed and assigned to the field. *
  • on boolean and Boolean fields: if the null value contains a String, the result of Boolean.valueOf(defaultNullRead()) will assigned to the field. *
  • on char and Character fields: if the null value contains a String, the result of defaultNullRead().charAt(0) will assigned to the field. * An exception will be thrown if the length of this String is different than 1 *
* * @return the default String to return when the parsed value is null */ String defaultNullRead() default "null"; /** * The default value to read from this field if it is null. Used for writing to an output by {@link BeanWriterProcessor}. *

The String literal "null" will be interpreted as a regular {@code null}. *

Use "'null"' if you want the default value to be the string {@code "null"} * * @return default String to write when the input is null. */ String defaultNullWrite() default "null"; /** * Flag to indicate whether the parsed field should be converted automatically based on the field type. For example, * if the annotated field is a {@code BigDecimal}, then {@link BigDecimalConversion} will be used to convert Strings to BigDecimal when reading * and BigDecimal to String when writing. You may want to disable the default field conversion when using custom conversions through * {@link BeanWriterProcessor#convertFields(Conversion...)},{@link BeanWriterProcessor#convertIndexes(Conversion...)} or * {@link BeanWriterProcessor#convertAll(Conversion...)}. * * @return flag indicating whether the default conversion, based on the field type, is to be applied for this field. */ boolean applyDefaultConversion() default true; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Replace.java000066400000000000000000000034721475274123300327660ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates the String value of a field must have some of its contents replaced using {@link RegexConversion}. * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Replace { /** * The regular expression to be executed against the String value of the annotated field * @return the regular expression */ String expression(); /** * The replacement string to substitute any contents matched by the given {@link Replace#expression()} * @return the replacement string */ String replacement(); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Trim.java000066400000000000000000000027571475274123300323330ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates the String value of a field must be trimmed using {@link TrimConversion}. * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Trim { int length() default -1; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/UpperCase.java000066400000000000000000000027561475274123300333060ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Indicates the String value of a field must be converted to uppercase using {@link UpperCaseConversion}. * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface UpperCase { } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/Validate.java000066400000000000000000000054131475274123300331410ustar00rootroot00000000000000/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.annotations; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; /** * Performs basic validations against the String representation of the value found in the annotated field. * A validation failure will generate a {@link com.univocity.parsers.common.DataValidationException}. * * By default, nulls and blanks are not allowed. * *

Commonly used for java beans processed using {@link BeanProcessor} and/or {@link BeanWriterProcessor} * * @see Conversion * @see Conversions * @see BeanProcessor * @see BeanWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Validate { /** * Indicates whether this field can be {@code null} * @return {@code true} true if nulls are allowed, {@code false} otherwise */ boolean nullable() default false; /** * Indicates whether this field can be blank (i.e. contain 0 or more whitespaces, where * a whitespace is any character {@code <= ' '} * @return {@code true} true if blanks are allowed, {@code false} otherwise */ boolean allowBlanks() default false; /** * Ensures that the value of this field matches a given regular expression. * @return the regular expression that determines an expected format for the given value */ String matches() default ""; /** * Ensures that the value of this field is one of a given set of alternatives * * @return the sequence of allowed values */ String[] oneOf() default {}; /** * Ensures that the value of this field does is not an unwanted value. * * @return the sequence of disallowed values */ String[] noneOf() default {}; /** * User provided implementations of {@link Validator} which will be executed * in sequence after the validations specified in this annotation execute. * * @return custom classes to be used to validate any value associated with this field. */ Class[] validators() default {}; } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/000077500000000000000000000000001475274123300322045ustar00rootroot00000000000000AnnotationHelper.java000066400000000000000000001346621475274123300362560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.helpers; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.Format; import com.univocity.parsers.common.*; import com.univocity.parsers.common.beans.*; import com.univocity.parsers.common.input.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.math.*; import java.text.*; import java.util.*; /** * Helper class to process fields annotated with {@link Parsed} * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class AnnotationHelper { private static AnnotatedElement lastProcessedElement; private static Class lastProcessedAnnotationType; private static Annotation lastAnnotationFound; private AnnotationHelper() { } /** * Converts the special "null" strings that might be provided by {@link Parsed#defaultNullRead() and Parsed#defaultNullWrite()} * * @param defaultValue The string returned by {@link Parsed#defaultNullRead() and Parsed#defaultNullWrite()} * * @return the default value if it is not the String literal "null" or "'null'". *

If "null" was provided, then null will be returned. *

If "'null'" was provided, then "null" will be returned. */ private static String getNullValue(String defaultValue) { if ("null".equals(defaultValue)) { return null; } if ("'null'".equals(defaultValue)) { return "null"; } return defaultValue; } public static String getNullWriteValue(AnnotatedElement target, Parsed parsed) { if (parsed == null) { return null; } return getNullValue(AnnotationRegistry.getValue(target, parsed, "defaultNullWrite", parsed.defaultNullWrite())); } public static String getNullReadValue(AnnotatedElement target, Parsed parsed) { if (parsed == null) { return null; } return getNullValue(AnnotationRegistry.getValue(target, parsed, "defaultNullRead", parsed.defaultNullRead())); } /** * Identifies the proper conversion for a given type and an annotation from the package {@link com.univocity.parsers.annotations} * * @param classType the type to have conversions applied to * @param annotation the annotation from {@link com.univocity.parsers.annotations} that identifies a {@link Conversion} instance. * * @return The {@link Conversion} that should be applied to the type */ @SuppressWarnings("rawtypes") public static Conversion getConversion(Class classType, Annotation annotation) { return getConversion(classType, null, annotation, null, null); } public static EnumConversion createDefaultEnumConversion(Class fieldType, String nullRead, String nullWrite){ Enum nullReadValue = nullRead == null ? null : Enum.valueOf(fieldType, nullRead); return new EnumConversion(fieldType, nullReadValue, nullWrite, null, EnumSelector.NAME, EnumSelector.ORDINAL, EnumSelector.STRING); } @SuppressWarnings({"rawtypes", "unchecked"}) public static Conversion getConversion(Class fieldType, AnnotatedElement target, Annotation annotation, String nullRead, String nullWrite) { try { Class annType = annotation.annotationType(); if (annType == NullString.class) { NullString nullString = (NullString) annotation; String[] nulls = AnnotationRegistry.getValue(target, nullString, "nulls", nullString.nulls()); return Conversions.toNull(nulls); } else if (annType == Validate.class) { Validate validate = (Validate) annotation; boolean nullable = AnnotationRegistry.getValue(target, validate, "nullable", validate.nullable()); boolean allowBlanks = AnnotationRegistry.getValue(target, validate, "allowBlanks", validate.allowBlanks()); String[] oneOf = AnnotationRegistry.getValue(target, validate, "oneOf", validate.oneOf()); String[] noneOf = AnnotationRegistry.getValue(target, validate, "noneOf", validate.noneOf()); String matches = AnnotationRegistry.getValue(target, validate, "matches", validate.matches()); Class[] validators = AnnotationRegistry.getValue(target, validate, "validators", validate.validators()); return new ValidatedConversion(nullable, allowBlanks, oneOf, noneOf, matches, validators); } else if (annType == EnumOptions.class) { if (!fieldType.isEnum()) { if (target == null) { throw new IllegalStateException("Invalid " + EnumOptions.class.getName() + " instance for converting class " + fieldType.getName() + ". Not an enum type."); } else { throw new IllegalStateException("Invalid " + EnumOptions.class.getName() + " annotation on " + describeElement(target) + ". Attribute must be an enum type."); } } EnumOptions enumOptions = ((EnumOptions) annotation); String customElement = AnnotationRegistry.getValue(target, enumOptions, "customElement", enumOptions.customElement()); String element = customElement.trim(); if (element.isEmpty()) { element = null; } Enum nullReadValue = nullRead == null ? null : Enum.valueOf(fieldType, nullRead); EnumSelector[] selectors = AnnotationRegistry.getValue(target, enumOptions, "selectors", enumOptions.selectors()); return new EnumConversion(fieldType, nullReadValue, nullWrite, element, selectors); } else if (annType == Trim.class) { Trim trim = ((Trim) annotation); int length = AnnotationRegistry.getValue(target, trim, "length", trim.length()); if (length == -1) { return Conversions.trim(); } else { return Conversions.trim(length); } } else if (annType == LowerCase.class) { return Conversions.toLowerCase(); } else if (annType == UpperCase.class) { return Conversions.toUpperCase(); } else if (annType == Replace.class) { Replace replace = ((Replace) annotation); String expression = AnnotationRegistry.getValue(target, replace, "expression", replace.expression()); String replacement = AnnotationRegistry.getValue(target, replace, "replacement", replace.replacement()); return Conversions.replace(expression, replacement); } else if (annType == BooleanString.class) { if (fieldType != boolean.class && fieldType != Boolean.class) { if (target == null) { throw new DataProcessingException("Invalid usage of " + BooleanString.class.getName() + ". Got type " + fieldType.getName() + " instead of boolean."); } else { throw new DataProcessingException("Invalid annotation: " + describeElement(target) + " has type " + fieldType.getName() + " instead of boolean."); } } BooleanString boolString = ((BooleanString) annotation); String[] falseStrings = AnnotationRegistry.getValue(target, boolString, "falseStrings", boolString.falseStrings()); String[] trueStrings = AnnotationRegistry.getValue(target, boolString, "trueStrings", boolString.trueStrings()); Boolean valueForNull = nullRead == null ? null : BooleanConversion.getBoolean(nullRead, trueStrings, falseStrings); if (valueForNull == null && fieldType == boolean.class) { valueForNull = Boolean.FALSE; } return Conversions.toBoolean(valueForNull, nullWrite, trueStrings, falseStrings); } else if (annType == Format.class) { Format format = ((Format) annotation); String[] formats = AnnotationRegistry.getValue(target, format, "formats", format.formats()); String[] options = AnnotationRegistry.getValue(target, format, "options", format.options()); Locale locale = extractLocale(options); TimeZone timezone = extractTimeZone(options); Conversion conversion = null; if (fieldType == BigDecimal.class) { BigDecimal defaultForNull = nullRead == null ? null : new BigDecimal(nullRead); conversion = Conversions.formatToBigDecimal(defaultForNull, nullWrite, formats); } else if (Number.class.isAssignableFrom(fieldType) || (fieldType.isPrimitive()) && fieldType != boolean.class && fieldType != char.class) { conversion = Conversions.formatToNumber(formats); ((NumericConversion) conversion).setNumberType(fieldType); } else { Date dateIfNull = null; if (nullRead != null) { if ("now".equalsIgnoreCase(nullRead)) { dateIfNull = new Date(); } else { if (formats.length == 0) { throw new DataProcessingException("No format defined"); } SimpleDateFormat sdf = new SimpleDateFormat(formats[0], locale); sdf.setTimeZone(timezone); dateIfNull = sdf.parse(nullRead); } } if (Date.class == fieldType) { conversion = Conversions.toDate(timezone, locale, dateIfNull, nullWrite, formats); } else if (Calendar.class == fieldType) { Calendar calendarIfNull = null; if (dateIfNull != null) { calendarIfNull = Calendar.getInstance(); calendarIfNull.setTime(dateIfNull); calendarIfNull.setTimeZone(timezone); } conversion = Conversions.toCalendar(timezone, locale, calendarIfNull, nullWrite, formats); } } if (conversion != null) { if (options.length > 0) { if (conversion instanceof FormattedConversion) { Object[] formatters = ((FormattedConversion) conversion).getFormatterObjects(); for (Object formatter : formatters) { applyFormatSettings(formatter, options); } } else { throw new DataProcessingException("Options '" + Arrays.toString(options) + "' not supported by conversion of type '" + conversion.getClass() + "'. It must implement " + FormattedConversion.class); } } return conversion; } } else if (annType == Convert.class) { Convert convert = ((Convert) annotation); String[] args = AnnotationRegistry.getValue(target, convert, "args", convert.args()); Class conversionClass = AnnotationRegistry.getValue(target, convert, "conversionClass", convert.conversionClass()); return (Conversion) newInstance(Conversion.class, conversionClass, args); } if (fieldType == String.class && (nullRead != null || nullWrite != null)) { return new ToStringConversion(nullRead, nullWrite); } return null; } catch (DataProcessingException ex) { throw ex; } catch (Throwable ex) { if (target == null) { throw new DataProcessingException("Unexpected error identifying conversions to apply over type " + fieldType, ex); } else { throw new DataProcessingException("Unexpected error identifying conversions to apply over " + describeElement(target), ex); } } } private static String extractOption(String[] options, String key) { for (int i = 0; i < options.length; i++) { if (options[i] != null && options[i].trim().toLowerCase().startsWith(key)) { String out = options[i].split("=")[1].trim(); options[i] = null; return out; } } return null; } private static TimeZone extractTimeZone(String[] options) { String code = extractOption(options, "timezone="); if (code != null) { return TimeZone.getTimeZone(code); } return TimeZone.getDefault(); } private static Locale extractLocale(String[] options) { String locale = extractOption(options, "locale="); if (locale != null) { String languageCode; String countryCode; String variant; CharAppender appender = new DefaultCharAppender(100, "", 0); int j = 0; char ch; for (; j < locale.length() && Character.isLetterOrDigit((ch = locale.charAt(j))); j++, appender.append(ch)) ; languageCode = appender.getAndReset(); for (++j; j < locale.length() && Character.isLetterOrDigit((ch = locale.charAt(j))); j++, appender.append(ch)) ; countryCode = appender.getAndReset(); for (++j; j < locale.length() && Character.isLetterOrDigit((ch = locale.charAt(j))); j++, appender.append(ch)) ; variant = appender.getAndReset(); return new Locale(languageCode, countryCode, variant); } return Locale.getDefault(); } public static T newInstance(Class parent, Class type, String[] args) { if (!parent.isAssignableFrom(type)) { throw new DataProcessingException("Not a valid " + parent.getSimpleName() + " class: '" + type.getSimpleName() + "' (" + type.getName() + ')'); } try { Constructor constructor = type.getConstructor(String[].class); return (T) constructor.newInstance((Object) args); } catch (NoSuchMethodException e) { if (args.length == 0) { try { return type.newInstance(); } catch (Exception ex) { throw new DataProcessingException("Unexpected error instantiating custom " + parent.getSimpleName() + " class '" + type.getSimpleName() + "' (" + type.getName() + ')', e); } } throw new DataProcessingException("Could not find a public constructor with a String[] parameter in custom " + parent.getSimpleName() + " class '" + type.getSimpleName() + "' (" + type.getName() + ')', e); } catch (Exception e) { throw new DataProcessingException("Unexpected error instantiating custom " + parent.getSimpleName() + " class '" + type.getSimpleName() + "' (" + type.getName() + ')', e); } } /** * Identifies the proper conversion for a given type * * @param fieldType The type of field to have conversions applied to. * @param target the annotated attribute of method that has the annotation * @param parsed the {@link Parsed} annotation from {@link com.univocity.parsers.annotations}. * * @return The {@link Conversion} that should be applied to the field type */ @SuppressWarnings({"rawtypes", "unchecked"}) public static Conversion getDefaultConversion(Class fieldType, AnnotatedElement target, Parsed parsed) { String nullRead = getNullReadValue(target, parsed); Object valueIfStringIsNull = null; ObjectConversion conversion = null; if (fieldType == Boolean.class || fieldType == boolean.class) { conversion = Conversions.toBoolean(); valueIfStringIsNull = nullRead == null ? null : Boolean.valueOf(nullRead); } else if (fieldType == Character.class || fieldType == char.class) { conversion = Conversions.toChar(); if (nullRead != null && nullRead.length() > 1) { throw new DataProcessingException("Invalid default value for character '" + nullRead + "'. It should contain one character only."); } valueIfStringIsNull = nullRead == null ? null : nullRead.charAt(0); } else if (fieldType == Byte.class || fieldType == byte.class) { conversion = Conversions.toByte(); valueIfStringIsNull = nullRead == null ? null : Byte.valueOf(nullRead); } else if (fieldType == Short.class || fieldType == short.class) { conversion = Conversions.toShort(); valueIfStringIsNull = nullRead == null ? null : Short.valueOf(nullRead); } else if (fieldType == Integer.class || fieldType == int.class) { conversion = Conversions.toInteger(); valueIfStringIsNull = nullRead == null ? null : Integer.valueOf(nullRead); } else if (fieldType == Long.class || fieldType == long.class) { conversion = Conversions.toLong(); valueIfStringIsNull = nullRead == null ? null : Long.valueOf(nullRead); } else if (fieldType == Float.class || fieldType == float.class) { conversion = Conversions.toFloat(); valueIfStringIsNull = nullRead == null ? null : Float.valueOf(nullRead); } else if (fieldType == Double.class || fieldType == double.class) { conversion = Conversions.toDouble(); valueIfStringIsNull = nullRead == null ? null : Double.valueOf(nullRead); } else if (fieldType == BigInteger.class) { conversion = Conversions.toBigInteger(); valueIfStringIsNull = nullRead == null ? null : new BigInteger(nullRead); } else if (fieldType == BigDecimal.class) { conversion = Conversions.toBigDecimal(); valueIfStringIsNull = nullRead == null ? null : new BigDecimal(nullRead); } else if (Enum.class.isAssignableFrom(fieldType)) { conversion = Conversions.toEnum(fieldType); } if (conversion != null) { conversion.setValueIfStringIsNull(valueIfStringIsNull); conversion.setValueIfObjectIsNull(getNullWriteValue(target, parsed)); } return conversion; } /** * Returns the default {@link Conversion} that should be applied to the field based on its type. * * @param target The field or method whose values must be converted from a given parsed String. * * @return The default {@link Conversion} applied to the given field. */ @SuppressWarnings("rawtypes") public static Conversion getDefaultConversion(AnnotatedElement target) { Parsed parsed = findAnnotation(target, Parsed.class); return getDefaultConversion(getType(target), target, parsed); } /** * Applied the configuration of a formatter object ({@link SimpleDateFormat}, {@link NumberFormat} and others). * * @param formatter the formatter instance * @param propertiesAndValues a sequence of key-value pairs, where the key is a property of the formatter * object to be set to the following value via reflection */ public static void applyFormatSettings(Object formatter, String[] propertiesAndValues) { if (propertiesAndValues.length == 0) { return; } Map values = new HashMap(); for (String setting : propertiesAndValues) { if (setting == null) { continue; } String[] pair = setting.split("="); if (pair.length != 2) { throw new DataProcessingException("Illegal format setting '" + setting + "' among: " + Arrays.toString(propertiesAndValues)); } values.put(pair[0], pair[1]); } try { for (PropertyWrapper property : BeanHelper.getPropertyDescriptors(formatter.getClass())) { String name = property.getName(); String value = values.remove(name); if (value != null) { invokeSetter(formatter, property, value); } if ("decimalFormatSymbols".equals(property.getName())) { DecimalFormatSymbols modifiedDecimalSymbols = new DecimalFormatSymbols(); boolean modified = false; try { for (PropertyWrapper prop : BeanHelper.getPropertyDescriptors(modifiedDecimalSymbols.getClass())) { value = values.remove(prop.getName()); if (value != null) { invokeSetter(modifiedDecimalSymbols, prop, value); modified = true; } } if (modified) { Method writeMethod = property.getWriteMethod(); if (writeMethod != null) { writeMethod.invoke(formatter, modifiedDecimalSymbols); } else { throw new IllegalStateException("No write method defined for property " + property.getName()); } } } catch (Throwable ex) { throw new DataProcessingException("Error trying to configure decimal symbols of formatter '" + formatter.getClass() + '.', ex); } } } } catch (Exception e) { //ignore and proceed } if (!values.isEmpty()) { throw new DataProcessingException("Cannot find properties in formatter of type '" + formatter.getClass() + "': " + values); } } private static void invokeSetter(Object formatter, PropertyWrapper property, final String value) { Method writeMethod = property.getWriteMethod(); if (writeMethod == null) { DataProcessingException exception = new DataProcessingException("Cannot set property '" + property.getName() + "' of formatter '" + formatter.getClass() + "' to '{value}'. No setter defined"); exception.setValue(value); throw exception; } Class parameterType = writeMethod.getParameterTypes()[0]; Object parameterValue = null; if (parameterType == String.class) { parameterValue = value; } else if (parameterType == Integer.class || parameterType == int.class) { parameterValue = Integer.parseInt(value); } else if (parameterType == Character.class || parameterType == char.class) { parameterValue = value.charAt(0); } else if (parameterType == Currency.class) { parameterValue = Currency.getInstance(value); } else if (parameterType == Boolean.class || parameterType == boolean.class) { parameterValue = Boolean.valueOf(value); } else if (parameterType == TimeZone.class) { parameterValue = TimeZone.getTimeZone(value); } else if (parameterType == DateFormatSymbols.class) { parameterValue = DateFormatSymbols.getInstance(new Locale(value)); } if (parameterValue == null) { DataProcessingException exception = new DataProcessingException("Cannot set property '" + property.getName() + "' of formatter '" + formatter.getClass() + ". Cannot convert '{value}' to instance of " + parameterType); exception.setValue(value); throw exception; } try { writeMethod.invoke(formatter, parameterValue); } catch (Throwable e) { DataProcessingException exception = new DataProcessingException("Error setting property '" + property.getName() + "' of formatter '" + formatter.getClass() + ", with '{parameterValue}' (converted from '{value}')", e); exception.setValue("parameterValue", parameterValue); exception.setValue(value); throw exception; } } private static boolean allFieldsIndexOrNameBased(boolean searchName, Class beanClass, MethodFilter filter) { boolean hasAnnotation = false; for (TransformedHeader header : getFieldSequence(beanClass, true, null, filter)) { if (header == null || header.getTarget() == null) { continue; } AnnotatedElement element = header.getTarget(); if (element instanceof Method && filter.reject((Method) element)) { continue; } Parsed annotation = findAnnotation(element, Parsed.class); if (annotation != null) { hasAnnotation = true; int index = AnnotationRegistry.getValue(element, annotation, "index", annotation.index()); if ((index != -1 && searchName) || (index == -1 && !searchName)) { return false; } } } return hasAnnotation; } /** * Runs through all annotations of a given class to identify whether all annotated fields and methods * (with the {@link Parsed} annotation) are mapped to a column by index. * * @param beanClass a class whose {@link Parsed} annotations will be processed. * * @return {@code true} if every field and method annotated with {@link Parsed} in the given class maps to an index, otherwise {@code false}. */ public static boolean allFieldsIndexBasedForParsing(Class beanClass) { return allFieldsIndexOrNameBased(false, beanClass, MethodFilter.ONLY_SETTERS); } /** * Runs through all annotations of a given class to identify whether all annotated fields and methods * (with the {@link Parsed} annotation) are mapped to a column by name. * * @param beanClass a class whose {@link Parsed} annotations will be processed. * * @return {@code true} if every field and method annotated with {@link Parsed} in the given class maps to a header name, otherwise {@code false}. */ public static boolean allFieldsNameBasedForParsing(Class beanClass) { return allFieldsIndexOrNameBased(true, beanClass, MethodFilter.ONLY_SETTERS); } /** * Runs through all annotations of a given class to identify whether all annotated fields and methods * (with the {@link Parsed} annotation) are mapped to a column by index. * * @param beanClass a class whose {@link Parsed} annotations will be processed. * * @return {@code true} if every field and method annotated with {@link Parsed} in the given class maps to an index, otherwise {@code false}. */ public static boolean allFieldsIndexBasedForWriting(Class beanClass) { return allFieldsIndexOrNameBased(false, beanClass, MethodFilter.ONLY_GETTERS); } /** * Runs through all annotations of a given class to identify whether all annotated fields and methods * (with the {@link Parsed} annotation) are mapped to a column by name. * * @param beanClass a class whose {@link Parsed} annotations will be processed. * * @return {@code true} if every field and method annotated with {@link Parsed} in the given class maps to a header name, otherwise {@code false}. */ public static boolean allFieldsNameBasedForWriting(Class beanClass) { return allFieldsIndexOrNameBased(true, beanClass, MethodFilter.ONLY_GETTERS); } /** * Runs through all {@link Parsed} annotations of a given class to identify all indexes associated with its fields * * @param beanClass a class whose {@link Parsed} annotations will be processed. * @param filter filter to apply over annotated methods when the class is being used for reading data from beans (to write values to an output) * or when writing values into beans (while parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. * * @return an array of column indexes used by the given class */ public static Integer[] getSelectedIndexes(Class beanClass, MethodFilter filter) { List indexes = new ArrayList(); for (TransformedHeader header : getFieldSequence(beanClass, true, null, filter)) { if (header == null) { continue; } int index = header.getHeaderIndex(); if (index != -1) { if (filter == MethodFilter.ONLY_GETTERS && indexes.contains(index)) { //allows the same column to be mapped to multiple fields when parsing, but not when writing. throw new IllegalArgumentException("Duplicate field index '" + index + "' found in attribute '" + header.getTargetName() + "' of class " + beanClass.getName()); } indexes.add(index); } } return indexes.toArray(new Integer[indexes.size()]); } /** * Runs through all {@link Parsed} annotations of a given class to identify all header names associated with its fields * * @param beanClass a class whose {@link Parsed} annotations will be processed. * @param filter a filter to exclude annotated methods that won't be used for parsing or writing * * @return an array of column names used by the given class */ public static String[] deriveHeaderNamesFromFields(Class beanClass, MethodFilter filter) { List sequence = getFieldSequence(beanClass, true, null, filter); List out = new ArrayList(sequence.size()); for (TransformedHeader field : sequence) { if (field == null) { return ArgumentUtils.EMPTY_STRING_ARRAY; // some field has an index that goes beyond list of header names, can't derive. } out.add(field.getHeaderName()); } return out.toArray(new String[out.size()]); } /** * Searches for a given annotation in the hierarchy of a class * * @param beanClass the class whose hierarchy will be searched * @param annotation the annotation to locate * @param the type of the annotation to return * @return the annotation of the given class or its most immediate parent, or {@code null} if not found. */ public static T findAnnotationInClass(Class beanClass, Class annotation) { T out; Class parent = beanClass; do { out = parent.getAnnotation(annotation); if (out != null) { return out; } else { for (Class iface : parent.getInterfaces()) { out = findAnnotationInClass(iface, annotation); if (out != null) { return out; } } } parent = parent.getSuperclass(); } while (parent != null); return null; } /** * Searches for the {@link Headers} annotation in the hierarchy of a class * * @param beanClass the class whose hierarchy will be searched * * @return the {@link Headers} annotation of the given class or its most immediate parent, or {@code null} if not found. */ public static Headers findHeadersAnnotation(Class beanClass) { return findAnnotationInClass(beanClass, Headers.class); } public static Class getType(AnnotatedElement element) { if (element instanceof Field) { return ((Field) element).getType(); } Method method = (Method) element; Class[] params = method.getParameterTypes(); if (params.length == 1) { return params[0]; } else if (params.length > 1) { throw new IllegalArgumentException("Method " + describeElement(element) + " cannot have multiple parameters"); } Class returnType = method.getReturnType(); if (returnType != void.class) { return returnType; } throw new IllegalArgumentException("Method " + describeElement(element) + " must return a value if it has no input parameter"); } public static Class getDeclaringClass(AnnotatedElement element) { if (element instanceof Field) { return ((Field) element).getDeclaringClass(); } else { return ((Method) element).getDeclaringClass(); } } public static String getName(AnnotatedElement element) { if (element instanceof Field) { return ((Field) element).getName(); } else { return ((Method) element).getName(); } } static String describeElement(AnnotatedElement element) { String description; if (element instanceof Field) { description = "attribute '" + ((Field) element).getName() + "'"; } else { description = "method '" + ((Method) element).getName() + "'"; } return description + " of class " + getDeclaringClass(element).getName(); } private static void processAnnotations(AnnotatedElement element, boolean processNested, List indexes, List tmp, Map> nestedReplacements, HeaderTransformer transformer, MethodFilter filter) { Parsed annotation = findAnnotation(element, Parsed.class); if (annotation != null) { TransformedHeader header = new TransformedHeader(element, transformer); if (filter == MethodFilter.ONLY_GETTERS && header.getHeaderIndex() >= 0 && indexes.contains(header.getHeaderIndex())) { //allows the same column to be mapped to multiple fields when parsing, but not when writing. throw new IllegalArgumentException("Duplicate field index '" + header.getHeaderIndex() + "' found in " + describeElement(element)); } tmp.add(header); indexes.add(header.getHeaderIndex()); } if (processNested) { Nested nested = findAnnotation(element, Nested.class); if (nested != null) { tmp.add(new TransformedHeader(element, null)); Class nestedBeanType = AnnotationRegistry.getValue(element, nested, "type", nested.type()); if (nestedBeanType == Object.class) { nestedBeanType = getType(element); } Class transformerType = AnnotationRegistry.getValue(element, nested, "headerTransformer", nested.headerTransformer()); if (transformerType != HeaderTransformer.class) { String[] args = AnnotationRegistry.getValue(element, nested, "args", nested.args()); HeaderTransformer innerTransformer = AnnotationHelper.newInstance(HeaderTransformer.class, transformerType, args); nestedReplacements.put(element, getFieldSequence(nestedBeanType, true, indexes, innerTransformer, filter)); } else { nestedReplacements.put(element, getFieldSequence(nestedBeanType, true, indexes, transformer, filter)); } } } } /** * Returns a list of fields with {@link Parsed} annotations in the sequence they should be processed for parsing * or writing. The sequence is ordered taking into account their original order in the annotated class, unless * {@link Parsed#index()} is set to a non-negative number. * * @param beanClass the class whose field sequence will be returned. * @param processNested flag indicating whether {@link Nested} annotations should be processed * @param transformer a {@link HeaderTransformer} instance to be used for transforming headers of a given {@link Nested} attribute. * @param filter filter to apply over annotated methods when the class is being used for reading data from beans (to write values to an output) * or when writing values into beans (while parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. * * @return a list of fields ordered by their processing sequence */ public static List getFieldSequence(Class beanClass, boolean processNested, HeaderTransformer transformer, MethodFilter filter) { List indexes = new ArrayList(); List tmp = getFieldSequence(beanClass, processNested, indexes, transformer, filter); Collections.sort(tmp, new Comparator() { @Override public int compare(TransformedHeader t1, TransformedHeader t2) { int i1 = t1.getHeaderIndex(); int i2 = t2.getHeaderIndex(); return i1 < i2 ? -1 : (i1 == i2 ? 0 : 1); } }); Collections.sort(indexes); int col = -1; for (int i : indexes) { col++; if (i < 0) { continue; } if (i != col) { while (i >= tmp.size()) { tmp.add(null); } Collections.swap(tmp, i, col); } } return tmp; } private static List getFieldSequence(Class beanClass, boolean processNested, List indexes, HeaderTransformer transformer, MethodFilter filter) { List tmp = new ArrayList(); Map> nestedReplacements = new LinkedHashMap>(); for (Field field : getAllFields(beanClass).keySet()) { processAnnotations(field, processNested, indexes, tmp, nestedReplacements, transformer, filter); } for (Method method : getAnnotatedMethods(beanClass, filter)) { processAnnotations(method, processNested, indexes, tmp, nestedReplacements, transformer, filter); } if (!nestedReplacements.isEmpty()) { int size = tmp.size(); for (int i = size - 1; i >= 0; i--) { TransformedHeader field = tmp.get(i); List nestedFields = nestedReplacements.remove(field.getTarget()); if (nestedFields != null) { tmp.remove(i); tmp.addAll(i, nestedFields); if (nestedReplacements.isEmpty()) { break; } } } } return tmp; } /** * Returns all fields available from a given class. * * @param beanClass a class whose fields will be returned. * * @return a map of {@link Field} and the corresponding {@link PropertyWrapper} */ public static Map getAllFields(Class beanClass) { Map properties = new LinkedHashMap(); try { for (PropertyWrapper property : BeanHelper.getPropertyDescriptors(beanClass)) { String name = property.getName(); if (name != null) { properties.put(name, property); } } } catch (Exception e) { //ignore and proceed to get fields directly } Set used = new HashSet(); Class clazz = beanClass; Map out = new LinkedHashMap(); do { Field[] declared = clazz.getDeclaredFields(); for (Field field : declared) { if (used.contains(field.getName())) { continue; } used.add(field.getName()); out.put(field, properties.get(field.getName())); } clazz = clazz.getSuperclass(); } while (clazz != null && clazz != Object.class); return out; } /** * Returns all methods available from a given class that have a specific annotation. * * @param beanClass a class whose methods will be returned. * @param filter filter to apply over annotated methods when the class is being used for reading data from beans (to write values to an output) * or when writing values into beans (while parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. * @param annotationType the annotation type to consider * * @param the expected annotation type * * @return a list of {@link Method} with at least one annotation */ public static List getAnnotatedMethods(Class beanClass, MethodFilter filter, Class annotationType) { List out = new ArrayList(); Class clazz = beanClass; do { Method[] declared = clazz.getDeclaredMethods(); outer: for (Method method : declared) { if (!method.isSynthetic() && annotationType == NO_ANNOTATIONS.class) { if (!filter.reject(method)) { out.add(method); } } else { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if ((annotationType == null && isCustomAnnotation(annotation)) || annotationType == annotation.annotationType()) { if (filter.reject(method)) { continue outer; } out.add(method); continue outer; } } } } clazz = clazz.getSuperclass(); } while (clazz != null && clazz != Object.class); return out; } private static final class NO_ANNOTATIONS implements Annotation { @Override public Class annotationType() { return NO_ANNOTATIONS.class; } } /** * Returns all methods available from a given class * * @param beanClass a class whose methods will be returned. * @param filter filter to apply over annotated methods when the class is being used for reading data from beans (to write values to an output) * or when writing values into beans (while parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. * * @return a list of {@link Method}s that conform to the given filter. */ public static List getAllMethods(Class beanClass, MethodFilter filter) { return getAnnotatedMethods(beanClass, filter, NO_ANNOTATIONS.class); } /** * Returns all methods available from a given class that have an annotation. * * @param beanClass a class whose methods will be returned. * @param filter filter to apply over annotated methods when the class is being used for reading data from beans (to write values to an output) * or when writing values into beans (while parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. * * @return a list of {@link Method} with at least one annotation */ public static List getAnnotatedMethods(Class beanClass, MethodFilter filter) { return getAnnotatedMethods(beanClass, filter, null); } /** * Returns all attributes available from a given class that have an annotation. * * @param beanClass a class whose methods will be returned. * * @return a list of {@link Field} with at least one annotation */ public static List getAnnotatedFields(Class beanClass) { return getAnnotatedFields(beanClass, null); } /** * Returns all attributes available from a given class that have an annotation. * * @param beanClass a class whose methods will be returned. * @param annotationType the type of annotation to consider * @param the expected annotation type * * @return a list of {@link Field} with at least one annotation */ public static List getAnnotatedFields(Class beanClass, Class annotationType) { List out = new ArrayList(); Class clazz = beanClass; do { Field[] declared = clazz.getDeclaredFields(); outer: for (Field field : declared) { Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if ((annotationType == null && isCustomAnnotation(annotation)) || annotationType == annotation.annotationType()) { out.add(field); continue outer; } } } clazz = clazz.getSuperclass(); } while (clazz != null && clazz != Object.class); return out; } /** * Searches for an annotation of a given type that's been applied to an element either directly (as a regular annotation) * or indirectly (as a meta-annotations, i.e. an annotation that has annotations). * * @param annotatedElement the element whose annotations will be searched * @param annotationType the type of annotation to search for * @param the type of the annotation being searched for * * @return the annotation associated with the given element, or {@code null} if not found. */ public synchronized static A findAnnotation(AnnotatedElement annotatedElement, Class annotationType) { if (annotatedElement == null || annotationType == null) { return null; } if (annotatedElement.equals(lastProcessedElement) && annotationType == lastProcessedAnnotationType) { return (A) lastAnnotationFound; } lastProcessedElement = annotatedElement; lastProcessedAnnotationType = annotationType; Stack path = new Stack(); A annotation = findAnnotation(annotatedElement, annotationType, new HashSet(), path); if (annotation == null || path.isEmpty()) { lastAnnotationFound = annotation; return annotation; } while (!path.isEmpty()) { Annotation parent = path.pop(); Annotation target = path.isEmpty() ? annotation : path.peek(); for (Method method : parent.annotationType().getDeclaredMethods()) { Copy copy = method.getAnnotation(Copy.class); if (copy != null) { Class targetClass = copy.to(); String targetProperty = copy.property(); if (targetProperty.trim().isEmpty()) { targetProperty = method.getName(); } Object value; Object existingValue = AnnotationRegistry.getValue(annotatedElement, target, method.getName()); if (existingValue != null) { value = existingValue; } else { value = invoke(parent, method); } Class sourceValueType = method.getReturnType(); Class targetPropertyType = findAnnotationMethodType(targetClass, targetProperty); if (targetPropertyType != null && targetPropertyType.isArray() && !value.getClass().isArray()) { Object array = Array.newInstance(sourceValueType, 1); Array.set(array, 0, value); value = array; } if (targetClass == target.annotationType()) { AnnotationRegistry.setValue(annotatedElement, annotation, targetProperty, value); } else { A ann = (A) findAnnotation(annotatedElement, targetClass, new HashSet(), new Stack()); if (ann != null) { AnnotationRegistry.setValue(annotatedElement, ann, targetProperty, value); } else { throw new IllegalStateException("Can't process @Copy annotation on '" + method + "'. " + "Annotation '" + targetClass.getName() + "' not used in " + parent.annotationType().getName() + ". Unable to process field " + annotatedElement + "'"); } } } } } lastAnnotationFound = annotation; return annotation; } private static Class findAnnotationMethodType(Class type, String methodName) { for (Method method : type.getDeclaredMethods()) { if (method.getName().equals(methodName)) { return method.getReturnType(); } } return null; } private static Object invoke(Annotation annotation, Method method) { try { return method.invoke(annotation, (Object[]) null); } catch (Exception e) { throw new IllegalStateException("Can't read value from annotation " + annotation, e); } } private static A findAnnotation(AnnotatedElement annotatedElement, Class annotationType, Set visited, Stack path) { Annotation[] declaredAnnotations = annotatedElement.getDeclaredAnnotations(); for (int i = 0; i < declaredAnnotations.length; i++) { Annotation ann = declaredAnnotations[i]; if (ann.annotationType() == annotationType) { return (A) ann; } } for (int i = 0; i < declaredAnnotations.length; i++) { Annotation ann = declaredAnnotations[i]; if (isCustomAnnotation(ann) && visited.add(ann)) { A annotation = findAnnotation(ann.annotationType(), annotationType, visited, path); path.push(ann); if (annotation != null) { return annotation; } } } return null; } private static final Set javaLangAnnotationTypes = new HashSet(); private static final Set customAnnotationTypes = new HashSet(); private static boolean isCustomAnnotation(Annotation annotation) { Class annotationType = annotation.annotationType(); if (customAnnotationTypes.contains(annotationType)) { return true; } if (javaLangAnnotationTypes.contains(annotationType)) { return false; } if (annotationType.getName().startsWith("java.lang.annotation")) { javaLangAnnotationTypes.add(annotationType); return false; } else { customAnnotationTypes.add(annotationType); return true; } } /** * Returns all annotations applied to an element, excluding the ones not in a given package. * * @param annotatedElement the element (method, field, etc) whose annotations will be extracted * @param aPackage the package of the annotations that should be returned * * @return the list of annotation elements applied to the given element, that are also members of the given package. */ public static List findAllAnnotationsInPackage(AnnotatedElement annotatedElement, Package aPackage) { final ArrayList found = new ArrayList(); findAllAnnotationsInPackage(annotatedElement, aPackage, found, new HashSet()); return found; } private static void findAllAnnotationsInPackage(AnnotatedElement annotatedElement, Package aPackage, ArrayList found, Set visited) { Annotation[] declaredAnnotations = annotatedElement.getDeclaredAnnotations(); for (int i = 0; i < declaredAnnotations.length; i++) { Annotation ann = declaredAnnotations[i]; if (aPackage.equals(ann.annotationType().getPackage())) { found.add(ann); } if (isCustomAnnotation(ann) && visited.add(ann)) { findAllAnnotationsInPackage(ann.annotationType(), aPackage, found, visited); } } } /** * Returns Java's default value for a given type, in a primitive type wrapper. * * @param type the primitive type whose default value will be returned. * * @return the default value for the given primitive type, or {@code null} if the type is not primitive. */ public static final Object getDefaultPrimitiveValue(Class type) { if (type == int.class) { return Integer.valueOf(0); } else if (type == double.class) { return 0.0D; } else if (type == boolean.class) { return Boolean.FALSE; } else if (type == long.class) { return Long.valueOf(0L); } else if (type == float.class) { return 0.0F; } else if (type == byte.class) { return Byte.valueOf((byte) 0); } else if (type == char.class) { return Character.valueOf('\0'); } else if (type == short.class) { return Short.valueOf((short) 0); } return null; } } AnnotationRegistry.java000066400000000000000000000134241475274123300366370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.helpers; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; /** * An internal registry of annotated elements and their properties that have been set via a {@link com.univocity.parsers.annotations.Copy} annotation. */ public class AnnotationRegistry { private static final Map modifiedAnnotations = new HashMap(); /** * Associates a value to a given annotation attribute * @param annotatedElement a method or field that has an annotation whose properties are changed by a {@link com.univocity.parsers.annotations.Copy} annotation * @param annotation the altered annotation of the given annotatedElement * @param attribute the attribute of the altered annotation * @param newValue the value of the given attribute of the altered annotation. */ static synchronized final void setValue(AnnotatedElement annotatedElement, Annotation annotation, String attribute, Object newValue) { FieldAnnotations attributes = modifiedAnnotations.get(annotatedElement); if (attributes == null) { attributes = new FieldAnnotations(); modifiedAnnotations.put(annotatedElement, attributes); } attributes.setValue(annotation, attribute, newValue); } /** * Returns the a value to a given annotation attribute that might have been modified by a {@link com.univocity.parsers.annotations.Copy} annotation * * @param annotatedElement a method or field that has an annotation whose properties might have been changed by a {@link com.univocity.parsers.annotations.Copy} annotation * @param annotation the possibly altered annotation of the given annotatedElement * @param attribute the attribute of the possibly altered annotation * @param valueIfNull the value to return from the unmodified annotation, if it has not been changed by a {@link com.univocity.parsers.annotations.Copy} * * @param the expected value type to be returned by this method. * * @return the value associated with the given annotation property. */ public static synchronized final T getValue(AnnotatedElement annotatedElement, Annotation annotation, String attribute, T valueIfNull) { if (annotatedElement == null) { return valueIfNull; } Object value = getValue(annotatedElement, annotation, attribute); if (value == null) { return valueIfNull; } return (T) value; } /** * Returns the a value to a given annotation attribute that might have been modified by a {@link com.univocity.parsers.annotations.Copy} annotation * * @param annotatedElement a method or field that has an annotation whose properties might have been changed by a {@link com.univocity.parsers.annotations.Copy} annotation * @param annotation the possibly altered annotation of the given annotatedElement * @param attribute the attribute of the possibly altered annotation * * @return the value associated with the given annotation property, or {@code null} if it has not been modified by a {@link com.univocity.parsers.annotations.Copy} */ static synchronized final Object getValue(AnnotatedElement annotatedElement, Annotation annotation, String attribute) { FieldAnnotations attributes = modifiedAnnotations.get(annotatedElement); if (attributes == null) { return null; } return attributes.getValue(annotation, attribute); } public static final void reset() { modifiedAnnotations.clear(); } private static class FieldAnnotations { private Map annotations = new HashMap(); private void setValue(Annotation annotation, String attribute, Object newValue) { AnnotationAttributes attributes = annotations.get(annotation); if (attributes == null) { attributes = new AnnotationAttributes(); annotations.put(annotation, attributes); } attributes.setAttribute(attribute, newValue); } private Object getValue(Annotation annotation, String attribute) { AnnotationAttributes attributes = annotations.get(annotation); if (attributes == null) { return null; } return attributes.getAttribute(attribute); } } private static class AnnotationAttributes { private Map attributes = new HashMap(); private void setAttribute(String attribute, Object newValue) { if (!attributes.containsKey(attribute)) { attributes.put(attribute, newValue); } else { Object existingValue = attributes.get(attribute); if (existingValue == null || newValue == null) { return; } //handles single values copied to a parent annotation that accepts an array Class originalClass = existingValue.getClass(); Class newClass = newValue.getClass(); if (originalClass != newClass && newClass.isArray() && newClass.getComponentType() == existingValue.getClass()) { Object array = Array.newInstance(originalClass, 1); Array.set(array, 0, existingValue); attributes.put(attribute, array); } } } private Object getAttribute(String attribute) { return attributes.get(attribute); } } } FieldMapping.java000066400000000000000000000307071475274123300353360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.helpers; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.beans.*; import java.lang.reflect.*; import static com.univocity.parsers.annotations.helpers.AnnotationHelper.*; /** * A helper class with information about the location of an field annotated with {@link Parsed} in a record. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class FieldMapping { private final Class parentClass; private final AnnotatedElement target; private int index; private NormalizedString fieldName; private final Class beanClass; private final Method readMethod; private final Method writeMethod; private boolean accessible; private final boolean primitive; private final Object defaultPrimitiveValue; private Boolean applyDefault = null; private Class fieldType; private boolean primitiveNumber; /** * Creates the mapping and identifies how it is mapped (by name or by index) * * @param beanClass the class that contains a the given field. * @param target a {@link java.lang.reflect.Field} or {@link java.lang.reflect.Method} annotated with {@link Parsed} * @param property the property descriptor of this field, if any. If this bean does not have getters/setters, it will be accessed directly. * @param transformer an optional {@link HeaderTransformer} to modify header names/positions in attributes of {@link Nested} classes. * @param headers list of headers parsed from the input or manually set with {@link CommonSettings#setHeaders(String...)} */ public FieldMapping(Class beanClass, AnnotatedElement target, PropertyWrapper property, HeaderTransformer transformer, NormalizedString[] headers) { this.beanClass = beanClass; this.target = target; if (target instanceof Field) { this.readMethod = property != null ? property.getReadMethod() : null; this.writeMethod = property != null ? property.getWriteMethod() : null; } else { Method method = (Method) target; this.readMethod = method.getReturnType() != Void.class ? method : null; this.writeMethod = method.getParameterTypes().length != 0 ? method : null; } Class typeToSet; if (target != null) { typeToSet = getType(target); parentClass = getDeclaringClass(target); } else if (writeMethod != null && writeMethod.getParameterTypes().length == 1) { typeToSet = writeMethod.getParameterTypes()[0]; parentClass = writeMethod.getDeclaringClass(); } else { typeToSet = Object.class; if (readMethod != null) { parentClass = readMethod.getDeclaringClass(); } else { parentClass = beanClass; } } primitive = typeToSet.isPrimitive(); defaultPrimitiveValue = getDefaultPrimitiveValue(typeToSet); primitiveNumber = (defaultPrimitiveValue instanceof Number); fieldType = typeToSet; determineFieldMapping(transformer, headers); } private void determineFieldMapping(HeaderTransformer transformer, NormalizedString[] headers) { Parsed parsed = findAnnotation(target, Parsed.class); String name = ""; if (parsed != null) { //field can be annotated with @Nested only. In this case we get the original field name index = AnnotationRegistry.getValue(target, parsed, "index", parsed.index()); if (index >= 0) { fieldName = null; if (transformer != null) { index = transformer.transformIndex(target, index); } return; } String[] fields = AnnotationRegistry.getValue(target, parsed, "field", parsed.field()); if (fields.length > 1 && headers != null) { for (int i = 0; i < headers.length; i++) { NormalizedString header = headers[i]; if (header == null) { continue; } for (int j = 0; j < fields.length; j++) { String field = fields[j]; if (header.equals(field)) { name = field; break; } } } } if (name.isEmpty()) { name = fields.length == 0 ? "" : fields[0]; } } if (name.isEmpty()) { name = getName(target); } fieldName = NormalizedString.valueOf(name); //Not a @Nested field if (parsed != null && transformer != null) { if (index >= 0) { index = transformer.transformIndex(target, index); } else if (fieldName != null) { fieldName = NormalizedString.valueOf(transformer.transformName(target, fieldName.toString())); } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FieldMapping that = (FieldMapping) o; if (index != that.index) { return false; } if (!target.equals(that.target)) { return false; } if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { return false; } return beanClass.equals(that.beanClass); } @Override public int hashCode() { int result = target.hashCode(); result = 31 * result + index; result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0); result = 31 * result + beanClass.hashCode(); return result; } /** * Returns {@code true} if the field is mapped to a column index, otherwise {@code false} * * @return {@code true} if the field is mapped to a column index, otherwise {@code false} */ public boolean isMappedToIndex() { return index >= 0; } /** * Returns {@code true} if the field is mapped to a column name, otherwise {@code false} * * @return {@code true} if the field is mapped to a column name, otherwise {@code false} */ public boolean isMappedToField() { return index < 0; } /** * Returns the column index against which this field is mapped. * * @return the column index associated with this field, or -1 if there's no such association. */ public int getIndex() { return index; } /** * Defines the column index against which this field is mapped, overriding any current position derived from * annotations. * * @param index the column index associated with this field */ public void setIndex(int index) { this.index = index; } /** * Defines the column name against which this field is mapped, overriding any current name derived from * annotations or from the attribute name itself. * * @param fieldName the column name associated with this field */ public void setFieldName(String fieldName) { this.fieldName = NormalizedString.valueOf(fieldName); } /** * Defines the column name against which this field is mapped, overriding any current name derived from * annotations or from the attribute name itself. * * @param fieldName the column name associated with this field */ public void setFieldName(NormalizedString fieldName) { this.fieldName = fieldName; } /** * Returns the column name against which this field is mapped. * * @return the column name associated with this field, or {@code null} if there's no such association. */ public NormalizedString getFieldName() { return fieldName; } /** * Returns the {@link Field} mapped to a column * * @return the {@link Field} mapped to a column */ public AnnotatedElement getTarget() { return target; } private void setAccessible() { if (!accessible) { if (target instanceof Field) { final Field field = ((Field) target); if (!field.isAccessible()) { field.setAccessible(true); } } else if (target instanceof Method) { final Method method = (Method) target; if (!method.isAccessible()) { method.setAccessible(true); } } accessible = true; } } /** * Returns the parent class that contains the mapped field. * * @return the field's parent class */ public Class getFieldParent() { return parentClass; } /** * Returns the type of the mapped field * * @return the field type. */ public Class getFieldType() { return fieldType; } /** * Queries whether this field mapping can be applied over a given object instance. * * @param instance the object whose type will be verified in order to identify if it contains the mapped field * * @return {@code true} if the given instance contains the field/accessor method and can use this field mapping to modify its internal state; otherwise {@code false} */ public boolean canWrite(Object instance) { if (!primitive) { if (instance == null) { return true; } return fieldType.isAssignableFrom(instance.getClass()); } else if (instance instanceof Number) { return primitiveNumber; } else if (instance instanceof Boolean) { return fieldType == boolean.class; } else if (instance instanceof Character) { return fieldType == char.class; } return false; } /** * Reads the value accessible by this field mapping from a given object * * @param instance the object whose field, mapped by this field mapping, will be read * * @return the value contained in the given instance's field */ public Object read(Object instance) { return read(instance, false); } private Object read(Object instance, boolean ignoreErrors) { setAccessible(); try { if (readMethod != null) { return readMethod.invoke(instance); } else { return ((Field) target).get(instance); } } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = e.getCause(); } if (!ignoreErrors) { String msg = "Unable to get value from field: " + toString(); if (e instanceof DataProcessingException) { DataProcessingException ex = (DataProcessingException) e; ex.setDetails(msg); throw ex; } throw new DataProcessingException(msg, e); } } return null; } /** * Writes a value to the field of a given object instance, whose field is accessible through this field mapping. * * @param instance the object whose field will be set * @param value the value to set on the given object's field. */ public void write(Object instance, Object value) { setAccessible(); try { if (primitive) { if (value == null) { if (applyDefault == null) { Object currentValue = read(instance, true); applyDefault = defaultPrimitiveValue.equals(currentValue); } if (applyDefault == Boolean.TRUE) { value = defaultPrimitiveValue; } else { return; } } else if (defaultPrimitiveValue.getClass() != value.getClass() && value instanceof Number) { Number number = ((Number) value); if (fieldType == int.class) { value = number.intValue(); } else if (fieldType == long.class) { value = number.longValue(); } else if (fieldType == double.class) { value = number.doubleValue(); } else if (fieldType == float.class) { value = number.floatValue(); } else if (fieldType == byte.class) { value = number.byteValue(); } else if (fieldType == short.class) { value = number.shortValue(); } } } if (writeMethod != null) { writeMethod.invoke(instance, value); } else { ((Field) target).set(instance, value); } } catch (Throwable e) { String valueTypeName = value == null ? null : value.getClass().getName(); String msg; String details = null; if (valueTypeName != null) { msg = "Unable to set value '{value}' of type '" + valueTypeName + "' to " + toString(); } else { msg = "Unable to set value 'null' to " + toString(); } if (e instanceof InvocationTargetException) { e = e.getCause(); details = msg; } if (e instanceof DataProcessingException) { DataProcessingException ex = (DataProcessingException) e; ex.markAsNonFatal(); ex.setValue(value); ex.setDetails(details); throw (DataProcessingException) e; } DataProcessingException ex = new DataProcessingException(msg, e); ex.markAsNonFatal(); ex.setValue(value); throw ex; } } @Override public String toString() { return AnnotationHelper.describeElement(target); } } MethodDescriptor.java000066400000000000000000000121511475274123300362470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.helpers; import java.lang.reflect.*; /** * A very basic descriptor or getter/setter methods */ public final class MethodDescriptor { private final String prefixedName; private final String name; private final String prefix; private final Class parameterType; private final Class returnType; private final String string; private MethodDescriptor(String name, Class parameterType, Class returnType) { prefixedName = name; int lastDot = name.lastIndexOf('.'); if (lastDot == -1) { this.name = name; this.prefix = ""; } else { this.name = name.substring(lastDot + 1); this.prefix = name.substring(0, lastDot); } this.parameterType = parameterType; this.returnType = returnType; this.string = generateString(); } private MethodDescriptor(String prefix, String name, Class parameterType, Class returnType) { this.prefixedName = prefix + '.' + name; this.name = name; this.prefix = prefix; this.parameterType = parameterType; this.returnType = returnType; this.string = generateString(); } private String generateString() { StringBuilder out = new StringBuilder("method "); if (returnType != null) { out.append(returnType.getName()); out.append(' '); } if (prefix.isEmpty()) { out.append(name); } else { out.append(prefix); out.append('.'); out.append(name); } if (parameterType != null) { out.append('('); out.append(parameterType.getName()); out.append(')'); } else { out.append("()"); } return out.toString(); } /** * Creates a descriptor for a setter method * @param name name of the setter method * @param parameterType the parameter type accepted by the given setter method * @return a "setter" method descriptor */ public static MethodDescriptor setter(String name, Class parameterType) { return new MethodDescriptor(name, parameterType, null); } /** * Creates a descriptor for a getter method * @param name name of the getter method * @param returnType the return type of the given getter method * @return a "getter" method descriptor */ public static MethodDescriptor getter(String name, Class returnType) { return new MethodDescriptor(name, null, returnType); } /** * Creates a descriptor for a setter method * @param prefix a dot separated string denoting a path of nested object names * @param method a actual class method to be associated with this prefix * @return a "setter" method descriptor */ static MethodDescriptor setter(String prefix, Method method) { return new MethodDescriptor(prefix, method.getName(), method.getParameterTypes()[0], null); } /** * Creates a descriptor for a getter method * @param prefix a dot separated string denoting a path of nested object names * @param method a actual class method to be associated with this prefix * @return a "getter" method descriptor */ static MethodDescriptor getter(String prefix, Method method) { return new MethodDescriptor(prefix, method.getName(), null, method.getReturnType()); } /** * Returns the method name, without the prefix * @return the method name */ public String getName() { return name; } /** * Returns the prefix: a dot separated string denoting a path of nested object names (e.g. customer.contact). * * @return the object nesting path associated with a method. */ public String getPrefix() { return prefix; } /** * Returns the parameter type associated with a method, if available * @return the type of parameter accepted by this method if it is a setter, or {@code null} if a getter is being represented. */ public Class getParameterType() { return parameterType; } /** * Returns the return type associated with a method, if available * @return the return type of this method if it is a getter, or {@code null} if a setter is being represented. */ public Class getReturnType() { return returnType; } /** * Returns full path to a method, (e.g. {@code getName} or {@code person.getName} * @return the path to the given method. */ public String getPrefixedName() { return prefixedName; } public String toString() { return string; } @Override public boolean equals(Object o) { if (o == null || o.getClass() != this.getClass()) { return false; } return string.equals(o.toString()); } @Override public int hashCode() { return string.hashCode(); } } MethodFilter.java000066400000000000000000000053141475274123300353610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.helpers; import java.lang.reflect.*; /** * A filter for annotated methods. Used internally to exclude setters or getters from the list of fields to be processed, * accordingly to the use case: when parsing into beans, only setter methods are to be considered. When writing values * in beans to an output, only the getter methods should be used. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public enum MethodFilter { /** * Rejects any method that returns {@code void} or has a parameter list. */ ONLY_GETTERS(new Filter() { @Override public boolean reject(Method method) { return method.getReturnType() == void.class || method.getParameterTypes().length != 0; } }), /** * Rejects any method that doesn't accept a single parameter. */ ONLY_SETTERS(new Filter() { @Override public boolean reject(Method method) { return method.getParameterTypes().length != 1; } }); private Filter filter; MethodFilter(Filter filter) { this.filter = filter; } /** * Tests whether a method is not a getter or setter and should be rejected. * * @param method the method to be tested * * @return {@code true} if the given method should be rejected, {@code false} otherwise */ public boolean reject(Method method) { return filter.reject(method); } private interface Filter { boolean reject(Method method); } /** * Creates a descriptor for a getter or setter method * * @param prefix a dot separated string denoting a path of nested object names * @param method a actual class method to be associated with this prefix * @return a descriptor for the given method */ public MethodDescriptor toDescriptor(String prefix, Method method) { if (reject(method)) { return null; } if (this == MethodFilter.ONLY_SETTERS) { return MethodDescriptor.setter(prefix, method); } else { return MethodDescriptor.getter(prefix, method); } } } TransformedHeader.java000066400000000000000000000112301475274123300363620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/annotations/helpers/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.helpers; import com.univocity.parsers.annotations.*; import java.lang.reflect.*; import static com.univocity.parsers.annotations.helpers.AnnotationHelper.*; /** * A pair associating a Field of an annotated class to an optional {@link HeaderTransformer} obtained from * {@link Nested#headerTransformer()} when nested classes are used to process beans. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public class TransformedHeader { private final AnnotatedElement target; private final Field field; private final Method method; private final HeaderTransformer transformer; private int index = -2; public TransformedHeader(AnnotatedElement target, HeaderTransformer transformer) { if (target instanceof Field) { field = (Field) target; method = null; } else { method = (Method) target; field = null; } this.target = target; this.transformer = transformer; } /** * Returns the name to be used as a header based on a given field and its {@link Parsed} annotation. * * @return the header name to be used for the given field. */ public String getHeaderName() { if (target == null) { return null; } String name = null; Parsed annotation = findAnnotation(target, Parsed.class); if (annotation != null) { String[] field = AnnotationRegistry.getValue(target, annotation, "field", annotation.field()); if (field.length == 0) { name = getTargetName(); } else { name = field[0]; } if (name.length() == 0) { name = getTargetName(); } } if (transformer != null) { if (field != null) { return transformer.transformName(field, name); } else { return transformer.transformName(method, name); } } return name; } /** * Returns the index that determines which column the current field represents, as specified by {@link Parsed#index()} * * @return the current header index. */ public int getHeaderIndex() { if (index == -2) { Parsed annotation = findAnnotation(target, Parsed.class); if (annotation != null) { index = AnnotationRegistry.getValue(target, annotation, "index", annotation.index()); if (index != -1) { if (transformer != null) { if (field != null) { index = transformer.transformIndex(field, index); } else { index = transformer.transformIndex(method, index); } } } } else { index = -1; } } return index; } /** * Returns the original attribute name of the field in its containing class. * * @return the original attribute name of the field */ public String getTargetName() { if (target == null) { return null; } if (field != null) { return field.getName(); } else { return method.getName(); } } /** * Returns the {@link AnnotatedElement} used to read/write values from/to. * * @return the field or method being manipulated by the parser/writer when processing java beans */ public AnnotatedElement getTarget() { return target; } /** * Returns {@code true} if this {@link AnnotatedElement} is a {@link Method} with parameters and can only be used * for writing values into the java bean. * * @return a flag indicating whether this is a method that allows writing values only. */ public boolean isWriteOnly() { if (method != null) { return method.getParameterTypes().length != 0; } return false; } /** * Returns {@code true} if this {@link AnnotatedElement} is a {@link Method} with no parameters and a return type which can only be used * for reading values from the java bean. * * @return a flag indicating whether this is a method that allows reading values only. */ public boolean isReadOly() { if (method != null) { return method.getParameterTypes().length == 0 && method.getReturnType() != void.class; } return false; } public String describe() { return AnnotationHelper.describeElement(target); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/000077500000000000000000000000001475274123300274755ustar00rootroot00000000000000AbstractException.java000066400000000000000000000111311475274123300337000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.util.*; /** * Parent class of the Exception classes thrown by univocity-parsers. This class provides utility methods to print out the internal state of the parser/writer * at the time an error occurred. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ abstract class AbstractException extends RuntimeException { private static final long serialVersionUID = -2993096896413328423L; protected int errorContentLength = -1; protected AbstractException(String message, Throwable cause) { super(message, cause); } /** * Returns a detailed message describing the error, and the internal state of the parser/writer. * * @return a detailed message describing the error */ @Override public final String getMessage() { String msg = super.getMessage(); msg = msg == null ? getErrorDescription() + ": " : msg; String details = getDetails(); if (details != null && !details.isEmpty()) { msg = msg + "\nInternal state when error was thrown: " + details; } msg = updateMessage(msg); return msg; } /** * Allows subclasses to alter the exception message that should be displayed to end users. * By default the original message is kept unchanged. * * @param msg the original message * @return the updated message. */ protected String updateMessage(String msg){ return msg; } /** * Subclasses must implement this method to return as much information as possible about the internal state of the parser/writer. * Use {@link #printIfNotEmpty(String, String, Object)} to create a comma-separated list of relevant properties and their (non null) values. * * The result of this method is used by the {@link #getMessage()} method to print out these details after the error message. * * @return a String describing the internal state of the parser/writer. */ protected abstract String getDetails(); /** * Returns a generic description of the error. The result of this method is used by {@link #getMessage()} to print out a general description of the error before a detailed message of the root cause. * * @return a generic description of the error. */ protected abstract String getErrorDescription(); protected static String printIfNotEmpty(String previous, String description, Object o) { String value; if (o == null || o.toString().isEmpty()) { return previous; } else if (o instanceof Number && ((Number) o).intValue() < 0) { return previous; } else if (o.getClass().isArray()) { //noinspection ConstantConditions value = Arrays.toString((Object[]) o); } else { value = String.valueOf(o); } String out = description + '=' + value; if (!previous.isEmpty()) { out = previous + ", " + out; } return out; } public static String restrictContent(int errorContentLength, CharSequence content) { return ArgumentUtils.restrictContent(errorContentLength,content); } public static Object[] restrictContent(int errorContentLength, Object[] content) { if (content == null || errorContentLength == 0) { return null; } return content; } public void setErrorContentLength(int errorContentLength) { this.errorContentLength = errorContentLength; Throwable cause = this.getCause(); if(cause != null && cause instanceof AbstractException){ AbstractException e = ((AbstractException) cause); if(e.errorContentLength != errorContentLength) { //prevents an unintended recursion cycle. e.setErrorContentLength(errorContentLength); } } } protected String restrictContent(CharSequence content) { return restrictContent(errorContentLength, content); } protected String restrictContent(Object content) { return ArgumentUtils.restrictContent(errorContentLength, content); } protected Object[] restrictContent(Object[] content) { return restrictContent(errorContentLength, content); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/AbstractParser.java000066400000000000000000001522601475274123300332660ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.input.EOFException; import com.univocity.parsers.common.input.*; import com.univocity.parsers.common.iterators.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.common.record.*; import java.io.*; import java.nio.charset.*; import java.util.*; import static com.univocity.parsers.common.ArgumentUtils.*; /** * The AbstractParser class provides a common ground for all parsers in univocity-parsers. *

It handles all settings defined by {@link CommonParserSettings}, and delegates the parsing algorithm implementation to its subclasses through the * abstract method {@link AbstractParser#parseRecord()} *

The following (absolutely required) attributes are exposed to subclasses: *

    *
  • input ({@link CharInputReader}): the character input provider that reads characters from a given input into an internal buffer
  • *
  • output ({@link ParserOutput}): the output handler for every record parsed from the input. Implementors must use this object to handle the input (such as appending characters and notifying of values parsed)
  • *
  • ch (char): the current character read from the input
  • *
* * @param The specific parser settings configuration class, which can potentially provide additional configuration options supported by the parser * implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.csv.CsvParser * @see com.univocity.parsers.csv.CsvParserSettings * @see com.univocity.parsers.fixed.FixedWidthParser * @see com.univocity.parsers.fixed.FixedWidthParserSettings * @see com.univocity.parsers.common.input.CharInputReader * @see com.univocity.parsers.common.ParserOutput */ public abstract class AbstractParser> { protected final T settings; protected final ParserOutput output; private final long recordsToRead; protected final char comment; private final LineReader lineReader = new LineReader(); protected ParsingContext context; protected Processor processor; protected CharInputReader input; protected char ch; private final ProcessorErrorHandler errorHandler; private final long rowsToSkip; protected final Map comments; protected String lastComment; private final boolean collectComments; private final int errorContentLength; private boolean extractingHeaders = false; private final boolean extractHeaders; protected final int whitespaceRangeStart; protected boolean ignoreTrailingWhitespace; protected boolean ignoreLeadingWhitespace; private final boolean processComments; /** * All parsers must support, at the very least, the settings provided by {@link CommonParserSettings}. The AbstractParser requires its configuration to be * properly initialized. * * @param settings the parser configuration */ public AbstractParser(T settings) { settings.autoConfigure(); this.settings = settings; this.errorContentLength = settings.getErrorContentLength(); this.ignoreTrailingWhitespace = settings.getIgnoreTrailingWhitespaces(); this.ignoreLeadingWhitespace = settings.getIgnoreLeadingWhitespaces(); this.output = new ParserOutput(this, settings); this.processor = settings.getProcessor(); this.recordsToRead = settings.getNumberOfRecordsToRead(); this.comment = settings.getFormat().getComment(); this.errorHandler = settings.getProcessorErrorHandler(); this.rowsToSkip = settings.getNumberOfRowsToSkip(); this.collectComments = settings.isCommentCollectionEnabled(); this.comments = collectComments ? new TreeMap() : Collections.emptyMap(); this.extractHeaders = settings.isHeaderExtractionEnabled(); this.whitespaceRangeStart = settings.getWhitespaceRangeStart(); this.processComments = settings.isCommentProcessingEnabled(); } protected void processComment() { if (collectComments) { long line = input.lineCount(); String comment = input.readComment(); if (comment != null) { lastComment = comment; comments.put(line, lastComment); } } else { try { input.skipLines(1); } catch (IllegalArgumentException e) { //end of input reached, ignore. } } } /** * Parses the entirety of a given input and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param reader The input to be parsed. */ public final void parse(Reader reader) { beginParsing(reader); try { while (!context.isStopped()) { input.markRecordStart(); ch = input.nextChar(); if (processComments && inComment()) { processComment(); continue; } if (output.pendingRecords.isEmpty()) { parseRecord(); } String[] row = output.rowParsed(); if (row != null) { if (recordsToRead >= 0 && context.currentRecord() >= recordsToRead) { context.stop(); if (recordsToRead == 0) { stopParsing(); return; } } if (processor != NoopProcessor.instance) { rowProcessed(row); } } } stopParsing(); } catch (EOFException ex) { try { handleEOF(); while (!output.pendingRecords.isEmpty()) { handleEOF(); } } finally { stopParsing(); } } catch (Throwable ex) { try { ex = handleException(ex); } finally { stopParsing(ex); } } } /** * Parser-specific implementation for reading a single record from the input. *

The AbstractParser handles the initialization and processing of the input until it is ready to be parsed. *

It then delegates the input to the parser-specific implementation defined by {@link #parseRecord()}. In general, an implementation of * {@link AbstractParser#parseRecord()} will perform the following steps: *

    *
  • Test the character stored in ch and take some action on it (e.g. is while (ch != '\n'){doSomething()})
  • *
  • Request more characters by calling ch = input.nextChar();
  • *
  • Append the desired characters to the output by executing, for example, output.appender.append(ch)
  • *
  • Notify a value of the record has been fully read by executing output.valueParsed(). This will clear the output appender ({@link CharAppender}) so the next call to output.appender.append(ch) will be store the character of the next parsed value
  • *
  • Rinse and repeat until all values of the record are parsed
  • *
*

Once the {@link #parseRecord()} returns, the AbstractParser takes over and handles the information (generally, reorganizing it and passing it on to a {@link RowProcessor}). *

After the record processing, the AbstractParser reads the next characters from the input, delegating control again to the parseRecord() implementation for processing of the next record. *

This cycle repeats until the reading process is stopped by the user, the input is exhausted, or an error happens. *

In case of errors, the unchecked exception {@link TextParsingException} will be thrown and all resources in use will be closed automatically * unless {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false}. The exception should contain the cause and more information about where in the input the error happened. * * @see com.univocity.parsers.common.input.CharInputReader * @see com.univocity.parsers.common.input.CharAppender * @see com.univocity.parsers.common.ParserOutput * @see com.univocity.parsers.common.TextParsingException * @see com.univocity.parsers.common.processor.RowProcessor */ protected abstract void parseRecord(); /** * Allows the parser implementation to handle any value that was being consumed when the end of the input was reached * * @return a flag indicating whether the parser was processing a value when the end of the input was reached. */ protected boolean consumeValueOnEOF() { return false; } private String[] handleEOF() { String[] row = null; try { boolean consumeValueOnEOF = consumeValueOnEOF(); if (output.column != 0 || (consumeValueOnEOF && !context.isStopped())) { if (output.appender.length() > 0 || consumeValueOnEOF) { output.valueParsed(); } else if (input.currentParsedContentLength() > 0) { output.emptyParsed(); } row = output.rowParsed(); } else if (output.appender.length() > 0 || input.currentParsedContentLength() > 0) { if (output.appender.length() == 0) { output.emptyParsed(); } else { output.valueParsed(); } row = output.rowParsed(); } else if (!output.pendingRecords.isEmpty()) { row = output.pendingRecords.poll(); } } catch (Throwable e) { throw handleException(e); } if (row != null && processor != NoopProcessor.instance) { rowProcessed(row); } return row; } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param reader The input to be parsed. */ public final void beginParsing(Reader reader) { output.reset(); if (reader instanceof LineReader) { input = new DefaultCharInputReader(settings.getFormat().getLineSeparator(), settings.getFormat().getNormalizedNewline(), settings.getInputBufferSize(), whitespaceRangeStart, true); } else { input = settings.newCharInputReader(whitespaceRangeStart); } input.enableNormalizeLineEndings(true); context = createParsingContext(); if (processor instanceof DefaultConversionProcessor) { DefaultConversionProcessor conversionProcessor = ((DefaultConversionProcessor) processor); conversionProcessor.errorHandler = errorHandler; conversionProcessor.context = context; } if (input instanceof AbstractCharInputReader) { AbstractCharInputReader inputReader = ((AbstractCharInputReader) input); inputReader.addInputAnalysisProcess(getInputAnalysisProcess()); for(InputAnalysisProcess p : settings.getInputAnalysisProcesses()){ inputReader.addInputAnalysisProcess(p); } } try { input.start(reader); } catch (Throwable t) { throw handleException(t); } input.skipLines(rowsToSkip); initialize(); processor.processStarted(context); } void extractHeadersIfRequired() { while (extractHeaders && output.parsedHeaders == null && !context.isStopped() && !extractingHeaders) { Processor userProvidedProcessor = processor; try { processor = NoopProcessor.instance; //disables any users provided processors to capture headers extractingHeaders = true; parseNext(); } finally { extractingHeaders = false; processor = userProvidedProcessor; } } } protected ParsingContext createParsingContext() { DefaultParsingContext out = new DefaultParsingContext(this, errorContentLength); out.stopped = false; return out; } protected void initialize() { } /** * Allows the parser implementation to traverse the input buffer before the parsing process starts, in order to enable automatic configuration and discovery * of data formats. * * @return a custom implementation of {@link InputAnalysisProcess}. By default, {@code null} is returned and no special input analysis will be performed. */ protected InputAnalysisProcess getInputAnalysisProcess() { return null; } private String getParsedContent(CharSequence tmp) { return "Parsed content: " + AbstractException.restrictContent(errorContentLength, tmp); } private TextParsingException handleException(Throwable ex) { if (context != null) { context.stop(); } if (ex instanceof DataProcessingException) { DataProcessingException error = (DataProcessingException) ex; error.restrictContent(errorContentLength); error.setContext(this.context); throw error; } String message = ex.getClass().getName() + " - " + ex.getMessage(); char[] chars = output.appender.getChars(); if (chars != null) { int length = output.appender.length(); if (length > chars.length) { message = "Length of parsed input (" + length + ") exceeds the maximum number of characters defined in" + " your parser settings (" + settings.getMaxCharsPerColumn() + "). "; length = chars.length; } String tmp = new String(chars); if (tmp.contains("\n") || tmp.contains("\r")) { tmp = displayLineSeparators(tmp, true); String lineSeparator = displayLineSeparators(settings.getFormat().getLineSeparatorString(), false); message += "\nIdentified line separator characters in the parsed content. This may be the cause of the error. " + "The line separator in your parser settings is set to '" + lineSeparator + "'. " + getParsedContent(tmp); } int nullCharacterCount = 0; //ensuring the StringBuilder won't grow over Integer.MAX_VALUE to avoid OutOfMemoryError int maxLength = length > Integer.MAX_VALUE / 2 ? Integer.MAX_VALUE / 2 - 1 : length; StringBuilder s = new StringBuilder(maxLength); for (int i = 0; i < maxLength; i++) { if (chars[i] == '\0') { s.append('\\'); s.append('0'); nullCharacterCount++; } else { s.append(chars[i]); } } tmp = s.toString(); if (nullCharacterCount > 0) { message += "\nIdentified " + nullCharacterCount + " null characters ('\0') on parsed content. This may " + "indicate the data is corrupt or its encoding is invalid. Parsed content:\n\t" + getParsedContent(tmp); } } if (ex instanceof ArrayIndexOutOfBoundsException) { try { int index = Integer.parseInt(ex.getMessage()); if (index == settings.getMaxCharsPerColumn()) { message += "\nHint: Number of characters processed may have exceeded limit of " + index + " characters per column. Use settings.setMaxCharsPerColumn(int) to define the maximum number of characters a column can have"; } if (index == settings.getMaxColumns()) { message += "\nHint: Number of columns processed may have exceeded limit of " + index + " columns. Use settings.setMaxColumns(int) to define the maximum number of columns your input can have"; } message += "\nEnsure your configuration is correct, with delimiters, quotes and escape sequences that match the input format you are trying to parse"; } catch (Throwable t) { //ignore; } } try { if (!message.isEmpty()) { message += "\n"; } message += "Parser Configuration: " + settings.toString(); } catch (Exception t) { //ignore } if (errorContentLength == 0) { output.appender.reset(); } TextParsingException out = new TextParsingException(context, message, ex); out.setErrorContentLength(errorContentLength); return out; } /** * In case of errors, stops parsing and closes all open resources. Avoids hiding the original exception in case another error occurs when stopping. */ private void stopParsing(Throwable error) { if (error != null) { try { stopParsing(); } catch (Throwable ex) { // ignore and throw original error. } if (error instanceof DataProcessingException) { DataProcessingException ex = (DataProcessingException) error; ex.setContext(context); throw ex; } else if (error instanceof RuntimeException) { throw (RuntimeException) error; } else if (error instanceof Error) { throw (Error) error; } else { throw new IllegalStateException(error.getMessage(), error); } } else { stopParsing(); } } /** * Stops parsing and closes all open resources. */ public final void stopParsing() { try { ch = '\0'; try { if (context != null) { context.stop(); } } finally { try { if (processor != null) { processor.processEnded(context); } } finally { if (output != null) { output.appender.reset(); } if (input != null) { input.stop(); } } } } catch (Throwable error) { throw handleException(error); } } private List beginParseAll(boolean validateReader, Reader reader, int expectedRowCount) { if (reader == null) { if (validateReader) { throw new IllegalStateException("Input reader must not be null"); } else { if (context == null) { throw new IllegalStateException("Input not defined. Please call method 'beginParsing()' with a valid input."); } else if (context.isStopped()) { return Collections.emptyList(); } } } List out = new ArrayList(expectedRowCount <= 0 ? 10000 : expectedRowCount); if (reader != null) { beginParsing(reader); } return out; } /** * Parses all remaining rows from the input and returns them in a list. * * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all remaining records parsed from the input. */ public List parseAll(int expectedRowCount) { return internalParseAll(false, null, expectedRowCount); } /** * Parses all remaining rows from the input and returns them in a list. * * @return the list of all remaining records parsed from the input. */ public List parseAll() { return internalParseAll(false, null, -1); } /** * Parses all remaining {@link Record}s from the input and returns them in a list. * * @param expectedRowCount expected number of {@link Record}s to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all remaining records parsed from the input. */ public List parseAllRecords(int expectedRowCount) { return internalParseAllRecords(false, null, expectedRowCount); } /** * Parses all remaining {@link Record}s from the input and returns them in a list. * * @return the list of all remaining {@link Record}s parsed from the input. */ public List parseAllRecords() { return internalParseAllRecords(false, null, -1); } /** * Parses all records from the input and returns them in a list. * * @param reader the input to be parsed * * @return the list of all records parsed from the input. */ public final List parseAll(Reader reader) { return parseAll(reader, 0); } /** * Parses all records from the input and returns them in a list. * * @param reader the input to be parsed * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAll(Reader reader, int expectedRowCount) { return internalParseAll(true, reader, expectedRowCount); } private final List internalParseAll(boolean validateReader, Reader reader, int expectedRowCount) { List out = beginParseAll(validateReader, reader, expectedRowCount); String[] row; while ((row = parseNext()) != null) { out.add(row); } return out; } protected boolean inComment() { return ch == comment; } /** * Parses the next record from the input. Note that {@link AbstractParser#beginParsing(Reader)} must have been invoked once before calling this method. * If the end of the input is reached, then this method will return null. Additionally, all resources will be closed automatically at the end of the input * or if any error happens while parsing, * unless {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false}. * * @return The record parsed from the input or null if there's no more characters to read. */ public final String[] parseNext() { try { while (!context.isStopped()) { input.markRecordStart(); ch = input.nextChar(); if (processComments && inComment()) { processComment(); continue; } if (output.pendingRecords.isEmpty()) { parseRecord(); } String[] row = output.rowParsed(); if (row != null) { if (recordsToRead >= 0 && context.currentRecord() >= recordsToRead) { context.stop(); if (recordsToRead == 0L) { stopParsing(); return null; } } if (processor != NoopProcessor.instance) { rowProcessed(row); } return row; } else if (extractingHeaders) { return null; } } if (output.column != 0) { return output.rowParsed(); } stopParsing(); return null; } catch (EOFException ex) { String[] row = handleEOF(); if (output.pendingRecords.isEmpty()) { stopParsing(); } return row; } catch (NullPointerException ex) { if (context == null) { throw new IllegalStateException("Cannot parse without invoking method beginParsing(Reader) first"); } else { if (input != null) { stopParsing(); } throw new IllegalStateException("Error parsing next record.", ex); } } catch (Throwable ex) { try { ex = handleException(ex); } finally { stopParsing(ex); } } return null; } /** * Reloads headers from settings. */ protected final void reloadHeaders() { this.output.initializeHeaders(); if (context instanceof DefaultParsingContext) { ((DefaultParsingContext) context).reset(); } } /** * Parses a single line from a String in the format supported by the parser implementation. * * @param line a line of text to be parsed * * @return the {@link Record} containing the values parsed from the input line */ public final Record parseRecord(String line) { String[] values = parseLine(line); if (values == null) { return null; } return context.toRecord(values); } /** * Parses a single line from a String in the format supported by the parser implementation. * * @param line a line of text to be parsed * * @return the values parsed from the input line */ public final String[] parseLine(String line) { if (line == null || line.isEmpty()) { return null; } lineReader.setLine(line); if (context == null || context.isStopped()) { beginParsing(lineReader); } else { if (input instanceof DefaultCharInputReader) { ((DefaultCharInputReader) input).reloadBuffer(); } else if (input instanceof LookaheadCharInputReader) { ((LookaheadCharInputReader) input).reloadBuffer(); } } try { while (!context.isStopped()) { input.markRecordStart(); ch = input.nextChar(); if (processComments && inComment()) { processComment(); return null; } if (output.pendingRecords.isEmpty()) { parseRecord(); } String[] row = output.rowParsed(); if (row != null) { if (processor != NoopProcessor.instance) { rowProcessed(row); } return row; } } return null; } catch (EOFException ex) { return handleEOF(); } catch (NullPointerException ex) { if (input != null) { stopParsing(null); } throw new IllegalStateException("Error parsing next record.", ex); } catch (Throwable ex) { try { ex = handleException(ex); } finally { stopParsing(ex); } } return null; } private void rowProcessed(String[] row) { Internal.process(row, processor, context, errorHandler); } /** * Parses the entirety of a given file and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param file The file to be parsed. */ public final void parse(File file) { parse(ArgumentUtils.newReader(file)); } /** * Parses the entirety of a given file and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param file The file to be parsed. * @param encoding the encoding of the file */ public final void parse(File file, String encoding) { parse(ArgumentUtils.newReader(file, encoding)); } /** * Parses the entirety of a given file and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param file The file to be parsed. * @param encoding the encoding of the file */ public final void parse(File file, Charset encoding) { parse(ArgumentUtils.newReader(file, encoding)); } /** * Parses the entirety of a given input and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param input The input to be parsed. The input stream will be closed automatically, unless {@link CommonParserSettings#isAutoClosingEnabled()} evaluates * to {@code false}. */ public final void parse(InputStream input) { parse(ArgumentUtils.newReader(input)); } /** * Parses the entirety of a given input and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param input The input to be parsed. The input stream will be closed automatically, unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false}. * @param encoding the encoding of the input stream */ public final void parse(InputStream input, String encoding) { parse(ArgumentUtils.newReader(input, encoding)); } /** * Parses the entirety of a given input and delegates each parsed row to an instance of {@link RowProcessor}, defined by * {@link CommonParserSettings#getRowProcessor()}. * * @param input The input to be parsed. The input stream will be closed automatically, unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false}. * @param encoding the encoding of the input stream */ public final void parse(InputStream input, Charset encoding) { parse(ArgumentUtils.newReader(input, encoding)); } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param file The file to be parsed. */ public final void beginParsing(File file) { beginParsing(ArgumentUtils.newReader(file)); } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param file The file to be parsed. * @param encoding the encoding of the file */ public final void beginParsing(File file, String encoding) { beginParsing(ArgumentUtils.newReader(file, encoding)); } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param file The file to be parsed. * @param encoding the encoding of the file */ public final void beginParsing(File file, Charset encoding) { beginParsing(ArgumentUtils.newReader(file, encoding)); } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param input The input to be parsed. The input stream will be closed automatically in case of errors unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false}. */ public final void beginParsing(InputStream input) { beginParsing(ArgumentUtils.newReader(input)); } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param input The input to be parsed. The input stream will be closed automatically in case of errors unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false}. * @param encoding the encoding of the input stream */ public final void beginParsing(InputStream input, String encoding) { beginParsing(ArgumentUtils.newReader(input, encoding)); } /** * Starts an iterator-style parsing cycle. If a {@link RowProcessor} is provided in the configuration, it will be used to perform additional processing. * The parsed records must be read one by one with the invocation of {@link AbstractParser#parseNext()}. * The user may invoke @link {@link AbstractParser#stopParsing()} to stop reading from the input. * * @param input The input to be parsed. The input stream will be closed automatically in case of errors unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false}. * @param encoding the encoding of the input stream */ public final void beginParsing(InputStream input, Charset encoding) { beginParsing(ArgumentUtils.newReader(input, encoding)); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the file. */ public final List parseAll(File file, int expectedRowCount) { return parseAll(ArgumentUtils.newReader(file), expectedRowCount); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the file. */ public final List parseAll(File file, String encoding, int expectedRowCount) { return parseAll(ArgumentUtils.newReader(file, encoding), expectedRowCount); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the file. */ public final List parseAll(File file, Charset encoding, int expectedRowCount) { return parseAll(ArgumentUtils.newReader(file, encoding), expectedRowCount); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false} * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAll(InputStream input, int expectedRowCount) { return parseAll(ArgumentUtils.newReader(input), expectedRowCount); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false} * @param encoding the encoding of the input stream * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAll(InputStream input, String encoding, int expectedRowCount) { return parseAll(ArgumentUtils.newReader(input, encoding), expectedRowCount); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false} * @param encoding the encoding of the input stream * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAll(InputStream input, Charset encoding, int expectedRowCount) { return parseAll(ArgumentUtils.newReader(input, encoding), expectedRowCount); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * * @return the list of all records parsed from the file. */ public final List parseAll(File file) { return parseAll(ArgumentUtils.newReader(file)); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * * @return the list of all records parsed from the file. */ public final List parseAll(File file, String encoding) { return parseAll(ArgumentUtils.newReader(file, encoding)); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * * @return the list of all records parsed from the file. */ public final List parseAll(File file, Charset encoding) { return parseAll(ArgumentUtils.newReader(file, encoding)); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false} * * @return the list of all records parsed from the input. */ public final List parseAll(InputStream input) { return parseAll(ArgumentUtils.newReader(input)); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false} * @param encoding the encoding of the input stream * * @return the list of all records parsed from the input. */ public final List parseAll(InputStream input, String encoding) { return parseAll(ArgumentUtils.newReader(input, encoding)); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false} * @param encoding the encoding of the input stream * * @return the list of all records parsed from the input. */ public final List parseAll(InputStream input, Charset encoding) { return parseAll(ArgumentUtils.newReader(input, encoding)); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the file. */ public final List parseAllRecords(File file, int expectedRowCount) { return parseAllRecords(ArgumentUtils.newReader(file), expectedRowCount); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the file. */ public final List parseAllRecords(File file, String encoding, int expectedRowCount) { return parseAllRecords(ArgumentUtils.newReader(file, encoding), expectedRowCount); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the file. */ public final List parseAllRecords(File file, Charset encoding, int expectedRowCount) { return parseAllRecords(ArgumentUtils.newReader(file, encoding), expectedRowCount); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false} * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAllRecords(InputStream input, int expectedRowCount) { return parseAllRecords(ArgumentUtils.newReader(input), expectedRowCount); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false} * @param encoding the encoding of the input stream * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAllRecords(InputStream input, String encoding, int expectedRowCount) { return parseAllRecords(ArgumentUtils.newReader(input, encoding), expectedRowCount); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless * {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false} * @param encoding the encoding of the input stream * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAllRecords(InputStream input, Charset encoding, int expectedRowCount) { return parseAllRecords(ArgumentUtils.newReader(input, encoding), expectedRowCount); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * * @return the list of all records parsed from the file. */ public final List parseAllRecords(File file) { return parseAllRecords(ArgumentUtils.newReader(file)); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * * @return the list of all records parsed from the file. */ public final List parseAllRecords(File file, String encoding) { return parseAllRecords(ArgumentUtils.newReader(file, encoding)); } /** * Parses all records from a file and returns them in a list. * * @param file the input file to be parsed * @param encoding the encoding of the file * * @return the list of all records parsed from the file. */ public final List parseAllRecords(File file, Charset encoding) { return parseAllRecords(ArgumentUtils.newReader(file, encoding)); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false} * * @return the list of all records parsed from the input. */ public final List parseAllRecords(InputStream input) { return parseAllRecords(ArgumentUtils.newReader(input)); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false} * @param encoding the encoding of the input stream * * @return the list of all records parsed from the input. */ public final List parseAllRecords(InputStream input, String encoding) { return parseAllRecords(ArgumentUtils.newReader(input, encoding)); } /** * Parses all records from an input stream and returns them in a list. * * @param input the input stream to be parsed. The input stream will be closed automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} * evaluates to {@code false} * @param encoding the encoding of the input stream * * @return the list of all records parsed from the input. */ public final List parseAllRecords(InputStream input, Charset encoding) { return parseAllRecords(ArgumentUtils.newReader(input, encoding)); } /** * Parses all records from the input and returns them in a list. * * @param reader the input to be parsed * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} * * @return the list of all records parsed from the input. */ public final List parseAllRecords(Reader reader, int expectedRowCount) { return internalParseAllRecords(true, reader, expectedRowCount); } private List internalParseAllRecords(boolean validateReader, Reader reader, int expectedRowCount) { List out = beginParseAll(validateReader, reader, expectedRowCount); if (context.isStopped()) { return out; } Record record; while ((record = parseNextRecord()) != null) { out.add(record); } return out; } /** * Parses all records from the input and returns them in a list. * * @param reader the input to be parsed * * @return the list of all records parsed from the input. */ public final List parseAllRecords(Reader reader) { return parseAllRecords(reader, 0); } /** * Parses the next record from the input. Note that {@link AbstractParser#beginParsing(Reader)} must have been invoked once before calling this method. * If the end of the input is reached, then this method will return null. Additionally, all resources will be closed automatically at the end of the input * or if any error happens while parsing. * * @return The record parsed from the input or null if there's no more characters to read. */ public final Record parseNextRecord() { String[] row = this.parseNext(); if (row != null) { return context.toRecord(row); } return null; } /** * Returns all comments collected by the parser so far. * An empty map will be returned if {@link CommonParserSettings#isCommentCollectionEnabled()} evaluates to {@code false}. * * @return a map containing the line numbers and comments found in each. */ final Map getComments() { return comments; } /** * Returns the last comment found in the input. * {@code null} will be returned if {@link CommonParserSettings#isCommentCollectionEnabled()} is evaluated to {@code false}. * * @return the last comment found in the input. */ final String getLastComment() { return lastComment; } /** * Returns the headers parsed from the input, if and only if {@link CommonParserSettings#headerExtractionEnabled} is {@code true}. * The result of this method won't return the list of headers manually set by the user in {@link CommonParserSettings#getHeaders()}. * * @return the headers parsed from the input, when {@link CommonParserSettings#headerExtractionEnabled} is {@code true}. */ final String[] getParsedHeaders() { extractHeadersIfRequired(); return output.parsedHeaders; } /** * Returns the current parsing context with information about the status of the parser at any given time. * * @return the parsing context */ public final ParsingContext getContext() { return context; } /** * Returns the metadata associated with {@link Record}s parsed from the input using {@link AbstractParser#parseAllRecords(File)} or * {@link AbstractParser#parseNextRecord()}. * * @return the metadata of {@link Record}s generated with the current input. */ public final RecordMetaData getRecordMetadata() { if (context == null) { throw new IllegalStateException("Record metadata not available. The parser has not been started."); } return context.recordMetaData(); } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the input {@code File} * @param encoding the encoding of the input {@code File} * * @return an iterator for rows parsed from the input. */ public final IterableResult iterate(final File input, String encoding) { return iterate(input, Charset.forName(encoding)); } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the input {@code File} * @param encoding the encoding of the input {@code File} * * @return an iterator for rows parsed from the input. */ public final IterableResult iterate(final File input, final Charset encoding) { return new RowIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input, encoding); } }; } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the input {@code File} * * @return an iterator for rows parsed from the input. */ public final IterableResult iterate(final File input) { return new RowIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input); } }; } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the input {@code Reader} * * @return an {@code iterable} over the results of parsing the {@code Reader} */ public final IterableResult iterate(final Reader input) { return new RowIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input); } }; } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the the {@code InputStream} with contents to be parsed * @param encoding the character encoding to be used for processing the given input. * * @return an iterator for rows parsed from the input. */ public final IterableResult iterate(final InputStream input, String encoding) { return iterate(input, Charset.forName(encoding)); } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the the {@code InputStream} with contents to be parsed * @param encoding the character encoding to be used for processing the given input. * * @return an iterator for rows parsed from the input. */ public final IterableResult iterate(final InputStream input, final Charset encoding) { return new RowIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input, encoding); } }; } /** * Provides an {@link IterableResult} for iterating rows parsed from the input. * * @param input the the {@code InputStream} with contents to be parsed * * @return an iterator for rows parsed from the input. */ public final IterableResult iterate(final InputStream input) { return new RowIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input); } }; } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the input {@code File} * @param encoding the encoding of the input {@code File} * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final File input, String encoding) { return iterateRecords(input, Charset.forName(encoding)); } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the input {@code File} * @param encoding the encoding of the input {@code File} * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final File input, final Charset encoding) { return new RecordIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input, encoding); } }; } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the input {@code File} * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final File input) { return new RecordIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input); } }; } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the input {@code Reader} * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final Reader input) { return new RecordIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input); } }; } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the the {@code InputStream} with contents to be parsed * @param encoding the character encoding to be used for processing the given input. * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final InputStream input, String encoding) { return iterateRecords(input, Charset.forName(encoding)); } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the the {@code InputStream} with contents to be parsed * @param encoding the character encoding to be used for processing the given input. * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final InputStream input, final Charset encoding) { return new RecordIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input, encoding); } }; } /** * Provides an {@link IterableResult} for iterating records parsed from the input. * * @param input the the {@code InputStream} with contents to be parsed * * @return an iterator for records parsed from the input. */ public final IterableResult iterateRecords(final InputStream input) { return new RecordIterator(this) { @Override protected void beginParsing() { parser.beginParsing(input); } }; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/AbstractWriter.java000066400000000000000000003220461475274123300333070ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.input.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.common.record.*; import com.univocity.parsers.fixed.*; import java.io.*; import java.nio.charset.*; import java.util.*; /** * The AbstractWriter class provides a common ground for all writers in univocity-parsers. * * It handles all settings defined by {@link CommonWriterSettings}, and delegates the writing algorithm implementation to its subclasses through the abstract * method {@link AbstractWriter#processRow(Object[])} * * The following (absolutely required) attributes are exposed to subclasses: *

    *
  • appender ({@link WriterCharAppender}): the character writer that appends characters from a given input into an internal buffer
  • *
* * @param The specific writer settings configuration class, which can potentially provide additional configuration options supported by the writer * implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.csv.CsvWriter * @see com.univocity.parsers.csv.CsvWriterSettings * @see com.univocity.parsers.fixed.FixedWidthWriter * @see com.univocity.parsers.fixed.FixedWidthWriterSettings * @see com.univocity.parsers.tsv.TsvWriter * @see com.univocity.parsers.tsv.TsvWriterSettings * @see com.univocity.parsers.common.input.WriterCharAppender * @see com.univocity.parsers.common.processor.RowWriterProcessor */ public abstract class AbstractWriter> { @SuppressWarnings("rawtypes") private final RowWriterProcessor writerProcessor; private Writer writer; private final boolean skipEmptyLines; protected final char comment; private final WriterCharAppender rowAppender; private final boolean isHeaderWritingEnabled; private Object[] outputRow; private int[] indexesToWrite; private final char[] lineSeparator; protected NormalizedString[] headers; protected long recordCount = 0; protected final String nullValue; protected final String emptyValue; protected final WriterCharAppender appender; private final Object[] partialLine; private int partialLineIndex = 0; private Map> headerIndexes; private int largestRowLength = -1; protected boolean writingHeaders = false; protected boolean[] headerTrimFlags; private NormalizedString[] dummyHeaderRow; protected boolean expandRows; private boolean usingSwitch; private boolean enableNewlineAfterRecord = true; protected boolean usingNullOrEmptyValue; protected final int whitespaceRangeStart; private final boolean columnReorderingEnabled; protected boolean ignoreLeading; protected boolean ignoreTrailing; private final CommonSettings internalSettings = new CommonSettings() { @Override protected DummyFormat createDefaultFormat() { return DummyFormat.instance; } }; private final int errorContentLength; /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * Important: by not providing an instance of {@link java.io.Writer} to this constructor, only the operations that write to Strings are * available. * * @param settings the writer configuration */ public AbstractWriter(S settings) { this((Writer) null, settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param file the output file that will be written with the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param settings the writer configuration */ public AbstractWriter(File file, S settings) { this(ArgumentUtils.newWriter(file), settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param file the output file that will be written with the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param encoding the encoding of the file * @param settings the writer configuration */ public AbstractWriter(File file, String encoding, S settings) { this(ArgumentUtils.newWriter(file, encoding), settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param file the output file that will be written with the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param encoding the encoding of the file * @param settings the writer configuration */ public AbstractWriter(File file, Charset encoding, S settings) { this(ArgumentUtils.newWriter(file, encoding), settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param output the output stream that will be written with the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param settings the writer configuration */ public AbstractWriter(OutputStream output, S settings) { this(ArgumentUtils.newWriter(output), settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param output the output stream that will be written with the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param encoding the encoding of the stream * @param settings the writer configuration */ public AbstractWriter(OutputStream output, String encoding, S settings) { this(ArgumentUtils.newWriter(output, encoding), settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param output the output stream that will be written with the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param encoding the encoding of the stream * @param settings the writer configuration */ public AbstractWriter(OutputStream output, Charset encoding, S settings) { this(ArgumentUtils.newWriter(output, encoding), settings); } /** * All writers must support, at the very least, the settings provided by {@link CommonWriterSettings}. The AbstractWriter requires its configuration to be * properly initialized. * * @param writer the output resource that will receive the format-specific records as defined by subclasses of {@link AbstractWriter}. * @param settings the writer configuration */ public AbstractWriter(Writer writer, S settings) { settings.autoConfigure(); this.ignoreLeading = settings.getIgnoreLeadingWhitespaces(); this.ignoreTrailing = settings.getIgnoreTrailingWhitespaces(); internalSettings.setMaxColumns(settings.getMaxColumns()); this.errorContentLength = settings.getErrorContentLength(); this.nullValue = settings.getNullValue(); this.emptyValue = settings.getEmptyValue(); this.lineSeparator = settings.getFormat().getLineSeparator(); this.comment = settings.getFormat().getComment(); this.skipEmptyLines = settings.getSkipEmptyLines(); this.writerProcessor = settings.getRowWriterProcessor(); this.usingSwitch = writerProcessor instanceof RowWriterProcessorSwitch; this.expandRows = settings.getExpandIncompleteRows(); this.columnReorderingEnabled = settings.isColumnReorderingEnabled(); this.whitespaceRangeStart = settings.getWhitespaceRangeStart(); this.appender = new WriterCharAppender(settings.getMaxCharsPerColumn(), "", whitespaceRangeStart, settings.getFormat()); this.rowAppender = new WriterCharAppender(settings.getMaxCharsPerColumn(), "", whitespaceRangeStart, settings.getFormat()); this.writer = writer; this.headers = NormalizedString.toIdentifierGroupArray(settings.getHeaders()); updateIndexesToWrite(settings); this.partialLine = new Object[settings.getMaxColumns()]; this.isHeaderWritingEnabled = settings.isHeaderWritingEnabled(); if (writerProcessor instanceof DefaultConversionProcessor) { DefaultConversionProcessor conversionProcessor = (DefaultConversionProcessor) writerProcessor; conversionProcessor.context = null; conversionProcessor.errorHandler = settings.getProcessorErrorHandler(); } initialize(settings); } protected void enableNewlineAfterRecord(boolean enableNewlineAfterRecord) { this.enableNewlineAfterRecord = enableNewlineAfterRecord; } /** * Initializes the concrete implementation of this class with format-specific settings. * * @param settings the settings object specific to the format being written. */ protected abstract void initialize(S settings); /** * Update indexes to write based on the field selection provided by the user. */ private void updateIndexesToWrite(CommonSettings settings) { FieldSelector selector = settings.getFieldSelector(); if (selector != null) { if (headers != null && headers.length > 0) { indexesToWrite = selector.getFieldIndexes(headers); if (columnReorderingEnabled) { //column reordering enabled? int size = ArgumentUtils.removeAll(indexesToWrite, -1).length; outputRow = new Object[size]; } else { outputRow = new Object[headers.length]; } } else if (!(selector instanceof FieldNameSelector) && !(selector instanceof ExcludeFieldNameSelector)) { int rowLength = largestRowLength; if ((selector instanceof FieldIndexSelector)) { boolean gotLengthFromSelection = false; for (Integer index : ((FieldIndexSelector) selector).get()) { if (rowLength <= index) { rowLength = index; gotLengthFromSelection = true; } } if (gotLengthFromSelection) { rowLength++; } if (rowLength < largestRowLength) { rowLength = largestRowLength; } } else { rowLength = settings.getMaxColumns(); } indexesToWrite = selector.getFieldIndexes(new NormalizedString[rowLength]); //generates a dummy header array - only the indexes matter so we are good if (columnReorderingEnabled) { //column reordering enabled? int size = ArgumentUtils.removeAll(indexesToWrite, -1).length; outputRow = new Object[size]; } else { outputRow = new Object[rowLength]; } } else { throw new IllegalStateException("Cannot select fields by name with no headers defined"); } } else { outputRow = null; indexesToWrite = null; } } /** * Updates the selection of fields to write. This is useful if the input rows * change during the writing process and their values need be allocated to specific columns. * * @param newFieldSelection the new selection of fields to write. */ public void updateFieldSelection(String... newFieldSelection) { if (headers == null) { throw new IllegalStateException("Cannot select fields by name. Headers not defined."); } internalSettings.selectFields(newFieldSelection); updateIndexesToWrite(internalSettings); } /** * Updates the selection of fields to write. This is useful if the input rows * change during the writing process and their values need be allocated to specific columns. * * @param newFieldSelectionByIndex the new selection of fields to write. */ public void updateFieldSelection(Integer... newFieldSelectionByIndex) { internalSettings.selectIndexes(newFieldSelectionByIndex); updateIndexesToWrite(internalSettings); } /** * Updates the selection of fields to exclude when writing. This is useful if the input rows * change during the writing process and their values need be allocated to specific columns. * * @param fieldsToExclude the selection of fields to exclude from the output. */ public void updateFieldExclusion(String... fieldsToExclude) { if (headers == null) { throw new IllegalStateException("Cannot de-select fields by name. Headers not defined."); } internalSettings.excludeFields(fieldsToExclude); updateIndexesToWrite(internalSettings); } /** * Updates the selection of fields to exclude when writing. This is useful if the input rows * change during the writing process and their values need be allocated to specific columns. * * @param fieldIndexesToExclude the selection of fields to exclude from the output. */ public void updateFieldExclusion(Integer... fieldIndexesToExclude) { internalSettings.excludeIndexes(fieldIndexesToExclude); updateIndexesToWrite(internalSettings); } /** * Submits a row for processing by the format-specific implementation. * * @param row the data to be written for a single record in the output. */ private void submitRow(Object[] row) { if (largestRowLength < row.length) { largestRowLength = row.length; } if (writingHeaders) { headerTrimFlags = new boolean[headers.length]; for (int i = 0; i < headers.length; i++) { headerTrimFlags[i] = !headers[i].isLiteral(); } } processRow(row); } /** * Format-specific implementation for writing a single record into the output. * * The AbstractWriter handles the initialization and processing of the output until it is ready to be written (generally, reorganizing it and passing it on * to a {@link RowWriterProcessor}). * It then delegates the record to the writer-specific implementation defined by {@link #processRow(Object[])}. In general, an implementation of {@link * AbstractWriter#processRow(Object[])} will perform the following steps: *
    *
  • Iterate over each object in the given input and convert it to the expected String representation.
  • *
  • The conversion must happen using the provided {@link AbstractWriter#appender} object. The an individual value is processed, the {@link AbstractWriter#appendValueToRow()} method must be called. * This will clear the accumulated value in {@link AbstractWriter#appender} and add it to the output row.
  • *
  • Format specific separators and other characters must be introduced to the output row using {@link AbstractWriter#appendToRow(char)}
  • *
* Once the {@link #processRow(Object[])} method returns, a row will be written to the output with the processed information, and a newline will be automatically written after the given contents, unless this is a * {@link com.univocity.parsers.fixed.FixedWidthWriter} whose {@link FixedWidthWriterSettings#getWriteLineSeparatorAfterRecord()} evaluates to {@code false}. The newline character sequence will conform to what is specified in {@link Format#getLineSeparator()} * This cycle repeats until the writing process is stopped by the user or an error happens. * In case of errors, the unchecked exception {@link TextWritingException} will be thrown and all resources in use will be closed automatically. The exception should contain the cause and more information about the output state when the error happened. * * @param row the data to be written to the output in the expected format. * * @see com.univocity.parsers.common.input.CharAppender * @see com.univocity.parsers.common.CommonWriterSettings */ protected abstract void processRow(Object[] row); /** * Appends the processed sequence of characters in {@link AbstractWriter#appender} to the output row. */ protected final void appendValueToRow() { rowAppender.append(appender); } /** * Appends the given character to the output row. * * @param ch the character to append to the output row */ protected final void appendToRow(char ch) { rowAppender.append(ch); } /** * Appends the given character sequence to the output row * * @param chars the sequence of characters to append to the output row */ protected final void appendToRow(char[] chars) { rowAppender.append(chars); } /** * Writes the headers defined in {@link CommonSettings#getHeaders()} * A {@link TextWritingException} will be thrown if no headers were defined or if records were already written to the output. */ public final void writeHeaders() { writeHeaders(NormalizedString.toArray(this.headers)); } /** * Writes the given collection of headers to the output. * A {@link TextWritingException} will be thrown if no headers were defined or if records were already written to the output. * * @param headers the headers to write to the output. */ public final void writeHeaders(Collection headers) { if (headers != null && headers.size() > 0) { writeHeaders(headers.toArray(new String[headers.size()])); } else { throw throwExceptionAndClose("No headers defined."); } } /** * Writes the given collection of headers to the output. * A {@link TextWritingException} will be thrown if no headers were defined or if records were already written to the output. * * @param headers the headers to write to the output. */ public final void writeHeaders(String... headers) { if (recordCount > 0) { throw throwExceptionAndClose("Cannot write headers after records have been written.", headers, null); } if (headers != null && headers.length > 0) { writingHeaders = true; if (columnReorderingEnabled && outputRow != null) { fillOutputRow(headers); headers = Arrays.copyOf(outputRow, outputRow.length, String[].class); } this.headers = NormalizedString.toIdentifierGroupArray(headers); submitRow(headers); internalWriteRow(); writingHeaders = false; } else { throw throwExceptionAndClose("No headers defined.", headers, null); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them, then finally and closes the output * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param allRecords the records to be transformed by a {@link RowWriterProcessor} and then written to the output */ public final void processRecordsAndClose(Iterable allRecords) { try { processRecords(allRecords); } finally { close(); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them, then finally and closes the output * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param allRecords the records to be transformed by a {@link RowWriterProcessor} and then written to the output */ public final void processRecordsAndClose(Object[] allRecords) { try { processRecords(allRecords); } finally { close(); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them. * The output will remain open for further writing. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param records the records to be transformed by a {@link RowWriterProcessor} and then written to the output */ public final void processRecords(Iterable records) { for (Object record : records) { processRecord(record); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them. * The output will remain open for further writing. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param records the records to transformed by a {@link RowWriterProcessor} and then written to the output */ public final void processRecords(Object[] records) { for (Object record : records) { processRecord(record); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them. * The output will remain open for further writing. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param records the records to transformed by a {@link RowWriterProcessor} and then written to the output * @param the concrete Record type */ public final void processRecords(T[] records) { for (T record : records) { processRecord(record); } } /** * Processes the data given for an individual record with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes it. * The output will remain open for further writing. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param record the information of a single record to be transformed by a {@link RowWriterProcessor} and then written to the output */ public final void processRecord(Object... record) { processRecord((Object) record); } public final void processRecord(T record) { processRecord((Object) (record == null ? null : record.getValues())); } /** * Processes the data given for an individual record with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes it. * The output will remain open for further writing. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param record the information of a single record to be transformed by a {@link RowWriterProcessor} and then written to the output */ @SuppressWarnings("unchecked") public final void processRecord(Object record) { if (this.writerProcessor == null) { String recordDescription; if (record instanceof Object[]) { recordDescription = Arrays.toString((Object[]) record); } else { recordDescription = String.valueOf(record); } String message = "Cannot process record '" + recordDescription + "' without a writer processor. Please define a writer processor instance in the settings or use the 'writeRow' methods."; this.throwExceptionAndClose(message); } Object[] row; try { if (usingSwitch) { dummyHeaderRow = ((RowWriterProcessorSwitch) writerProcessor).getHeaders(record); if (dummyHeaderRow == null) { dummyHeaderRow = this.headers; } row = writerProcessor.write(record, dummyHeaderRow, indexesToWrite); } else { row = writerProcessor.write(record, getRowProcessorHeaders(), indexesToWrite); } } catch (DataProcessingException e) { e.setErrorContentLength(errorContentLength); throw e; } if (row != null) { writeRow(row); } } private NormalizedString[] getRowProcessorHeaders() { if (headers == null && indexesToWrite == null) { return null; } return headers; } /** * Iterates over all records, writes them and closes the output. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecordsAndClose(Iterable)} for that. * * @param Collection of objects containing values of a row * @param allRows the rows to be written to the output */ public final > void writeRowsAndClose(Iterable allRows) { try { writeRows(allRows); } finally { close(); } } /** * Iterates over all records, writes them and closes the output. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecordsAndClose(Object[])} for that. * * @param allRows the rows to be written to the output */ public final void writeRowsAndClose(Collection allRows) { try { writeRows(allRows); } finally { close(); } } /** * Iterates over all records, writes them and closes the output. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecordsAndClose(Iterable)} for that. * * @param allRows the rows to be written to the output */ public final void writeStringRowsAndClose(Collection allRows) { try { writeStringRows(allRows); } finally { close(); } } /** * Iterates over all records, writes them and closes the output. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecordsAndClose(Iterable)} for that. * * @param allRows the rows to be written to the output */ public final void writeRecordsAndClose(Collection allRows) { try { writeRecords(allRows); } finally { close(); } } /** * Iterates over all records, writes them and closes the output. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecordsAndClose(Object[])} for that. * * @param allRows the rows to be written to the output */ public final void writeRowsAndClose(Object[][] allRows) { try { writeRows(allRows); } finally { close(); } } /** * Iterates over all records and writes them to the output. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Object[])} for that. * * @param rows the rows to be written to the output */ public final void writeRows(Object[][] rows) { for (Object[] row : rows) { writeRow(row); } } /** * Iterates over all records and writes them to the output. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param Collection of objects containing values of a row * @param rows the rows to be written to the output */ public final > void writeRows(Iterable rows) { for (Collection row : rows) { writeRow(row); } } /** * Iterates over all records and writes them to the output. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param rows the rows to be written to the output */ public final void writeStringRows(Collection rows) { for (String[] row : rows) { writeRow(row); } } /** * Iterates over all records and writes them to the output. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param rows the rows to be written to the output */ public final void writeRecords(Collection rows) { for (Record row : rows) { writeRecord(row); } } /** * Iterates over all records and writes them to the output. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param Collection of objects containing values of a row * @param rows the rows to be written to the output */ public final > void writeStringRows(Iterable rows) { for (Collection row : rows) { writeRow(row.toArray()); } } /** * Iterates over all records and writes them to the output. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param rows the rows to be written to the output */ public final void writeRows(Collection rows) { for (Object[] row : rows) { writeRow(row); } } /** * Writes the data given for an individual record. * The output will remain open for further writing. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to the output */ public final void writeRow(Collection row) { if (row == null) { return; } writeRow(row.toArray()); } /** * Writes the data given for an individual record. * The output will remain open for further writing. * If the given data is null or empty, and {@link CommonSettings#getSkipEmptyLines()} is true, the input will be just ignored. * If {@link CommonSettings#getSkipEmptyLines()} is false, then an empty row will be written to the output (as specified by {@link * AbstractWriter#writeEmptyRow()}). * In case of any errors, a {@link TextWritingException} will be thrown and the {@link java.io.Writer} given in the constructor will be closed. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to the output */ public final void writeRow(String[] row) { writeRow((Object[]) row); } /** * Writes the data given for an individual record. * The output will remain open for further writing. * If the given data is null or empty, and {@link CommonSettings#getSkipEmptyLines()} is true, the input will be just ignored. * If {@link CommonSettings#getSkipEmptyLines()} is false, then an empty row will be written to the output (as specified by {@link * AbstractWriter#writeEmptyRow()}). * In case of any errors, a {@link TextWritingException} will be thrown and the {@link java.io.Writer} given in the constructor will be closed. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to the output * @param the concrete Record type */ public final void writeRecord(T row) { if (row == null) { if (skipEmptyLines) { return; } else { writeEmptyRow(); return; } } if (recordCount == 0 && isHeaderWritingEnabled && headers == null) { String[] headers = row.getMetaData().headers(); if (headers != null) { this.headers = NormalizedString.toArray(headers); } } writeRow((Object[]) row.getValues()); } /** * Writes the data given for an individual record. * The output will remain open for further writing. * If the given data is null or empty, and {@link CommonSettings#getSkipEmptyLines()} is true, the input will be just ignored. * If {@link CommonSettings#getSkipEmptyLines()} is false, then an empty row will be written to the output (as specified by {@link * AbstractWriter#writeEmptyRow()}). * In case of any errors, a {@link TextWritingException} will be thrown and the {@link java.io.Writer} given in the constructor will be closed. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to the output */ public final void writeRow(Object... row) { try { if (recordCount == 0 && isHeaderWritingEnabled && headers != null) { writeHeaders(); } if (row == null || (row.length == 0 && !expandRows)) { if (skipEmptyLines) { return; } else { writeEmptyRow(); return; } } row = adjustRowLength(row); submitRow(row); internalWriteRow(); } catch (Throwable ex) { throw throwExceptionAndClose("Error writing row.", row, ex); } } protected Object[] expand(Object[] row, int length, Integer h2) { if (row.length < length) { return Arrays.copyOf(row, length); } else if (h2 != null && row.length < h2) { return Arrays.copyOf(row, h2); } if (length == -1 && h2 == null && row.length < largestRowLength) { return Arrays.copyOf(row, largestRowLength); } return row; } /** * Writes a plain (potentially free-text) String as a line to the output. * A newline will automatically written after the given contents, unless this is a * {@link com.univocity.parsers.fixed.FixedWidthWriter} whose * {@link FixedWidthWriterSettings#getWriteLineSeparatorAfterRecord()} evaluates to {@code false}. * The newline character sequence will conform to what is specified in {@link Format#getLineSeparator()} * The writer implementation has no control over the format of this content. * The output will remain open for further writing. * * @param row the line to be written to the output */ public final void writeRow(String row) { try { writer.write(row); if (enableNewlineAfterRecord) { writer.write(lineSeparator); } } catch (Throwable ex) { throw throwExceptionAndClose("Error writing row.", row, ex); } } /** * Writes an empty line to the output, unless this is a {@link com.univocity.parsers.fixed.FixedWidthWriter} whose * {@link FixedWidthWriterSettings#getWriteLineSeparatorAfterRecord()} evaluates to {@code false}. * The newline character sequence will conform to what is specified in {@link Format#getLineSeparator()} * The output will remain open for further writing. */ public final void writeEmptyRow() { try { if (enableNewlineAfterRecord) { writer.write(lineSeparator); } } catch (Throwable ex) { throw throwExceptionAndClose("Error writing empty row.", Arrays.toString(lineSeparator), ex); } } /** * Writes a comment row to the output. * A newline will automatically written after the given contents, unless this is a * {@link com.univocity.parsers.fixed.FixedWidthWriter} whose * {@link FixedWidthWriterSettings#getWriteLineSeparatorAfterRecord()} evaluates to {@code false}. * The newline character sequence will conform to what is specified in {@link Format#getLineSeparator()} * The output will remain open for further writing. * * @param comment the contents to be written as a comment to the output */ public final void commentRow(String comment) { writeRow(this.comment + comment); } /** * Used when fields were selected and the input rows have a different order than the output. This method * fills the internal #outputRow array with the values provided by the user in the correct order. * * @param row user-provided data which has to be rearranged to the expected record sequence before writing to the output. */ private void fillOutputRow(T[] row) { if (!columnReorderingEnabled && row.length > outputRow.length) { outputRow = Arrays.copyOf(outputRow, row.length); } if (indexesToWrite.length < row.length) { if (columnReorderingEnabled) { for (int i = 0; i < indexesToWrite.length; i++) { outputRow[i] = row[indexesToWrite[i]]; } } else { for (int i = 0; i < indexesToWrite.length; i++) { outputRow[indexesToWrite[i]] = row[indexesToWrite[i]]; } } } else { for (int i = 0; i < row.length && i < indexesToWrite.length; i++) { if (indexesToWrite[i] != -1) { outputRow[indexesToWrite[i]] = row[i]; } } } } /** * Writes the accumulated value of a record to the output, followed by a newline, and increases the record count. * The newline character sequence will conform to what is specified in {@link Format#getLineSeparator()} * The contents of {@link AbstractWriter#rowAppender} depend on the concrete implementation of {@link AbstractWriter#processRow(Object[])} */ private void internalWriteRow() { try { if (skipEmptyLines && rowAppender.length() == 0) { return; } if (enableNewlineAfterRecord) { rowAppender.appendNewLine(); } rowAppender.writeCharsAndReset(writer); recordCount++; } catch (Throwable ex) { throw throwExceptionAndClose("Error writing row.", rowAppender.getAndReset(), ex); } } /** * Identifies the starting character index of a value being written if leading whitespaces are to be discarded. * Implementation note whitespaces are considered all characters where {@code ch <= ' '} evaluates to {@code true} * * @param whitespaceRangeStart starting range after which characters will be considered whitespace * @param element the String to be scanned for leading whitespaces. * * @return the index of the first non-whitespace character in the given element. */ protected static int skipLeadingWhitespace(int whitespaceRangeStart, String element) { if (element.isEmpty()) { return 0; } for (int i = 0; i < element.length(); i++) { char nextChar = element.charAt(i); if (!(nextChar <= ' ' && whitespaceRangeStart < nextChar)) { return i; } } return element.length(); } /** * Flushes the {@link java.io.Writer} given in this class constructor. * An IllegalStateException will be thrown in case of any errors, and the writer will be closed. */ public final void flush() { try { writer.flush(); } catch (Throwable ex) { throw throwExceptionAndClose("Error flushing output.", rowAppender.getAndReset(), ex); } } /** * Closes the {@link java.io.Writer} given in this class constructor. * An IllegalStateException will be thrown in case of any errors. */ public final void close() { try { this.headerIndexes = null; if (writer != null) { writer.close(); writer = null; } } catch (Throwable ex) { throw new IllegalStateException("Error closing the output.", ex); } if (this.partialLineIndex != 0) { throw new TextWritingException("Not all values associated with the last record have been written to the output. " + "\n\tHint: use 'writeValuesToRow()' or 'writeValuesToString()' to flush the partially written values to a row.", recordCount, getContent(Arrays.copyOf(partialLine, partialLineIndex))); } } /** * In case of any exceptions, a {@link TextWritingException} is thrown, and the output {@link java.io.Writer} is closed. * * @param message Description of the error */ private TextWritingException throwExceptionAndClose(String message) { return throwExceptionAndClose(message, (Object[]) null, null); } /** * In case of any exceptions, a {@link TextWritingException} is thrown, and the output {@link java.io.Writer} is closed. * * @param message Description of the error * @param cause the exception to be wrapped by a {@link TextWritingException} */ private TextWritingException throwExceptionAndClose(String message, Throwable cause) { return throwExceptionAndClose(message, (Object[]) null, cause); } /** * In case of any exceptions, a {@link TextWritingException} is thrown, and the output {@link java.io.Writer} is closed. * * @param message Description of the error * @param recordCharacters characters used to write to the output at the time the exception happened * @param cause the exception to be wrapped by a {@link TextWritingException} */ private TextWritingException throwExceptionAndClose(String message, String recordCharacters, Throwable cause) { try { if (cause instanceof NullPointerException && writer == null) { message = message + " No writer provided in the constructor of " + getClass().getName() + ". You can only use operations that write to Strings."; } throw new TextWritingException(message, recordCount, getContent(recordCharacters), cause); } finally { close(); } } /** * In case of any exceptions, a {@link TextWritingException} is thrown, and the output {@link java.io.Writer} is closed. * * @param message Description of the error * @param recordValues values used to write to the output at the time the exception happened * @param cause the exception to be wrapped by a {@link TextWritingException} */ private TextWritingException throwExceptionAndClose(String message, Object[] recordValues, Throwable cause) { try { throw new TextWritingException(message, recordCount, getContent(recordValues), cause); } finally { try { close(); } catch (Throwable t) { //ignore and let original error go. } } } /** * Converts a given object to its String representation for writing to a {@code String} *
    *
  • If the object is null, then {@link AbstractWriter#nullValue} is returned.
  • *
  • If the String representation of this object is an empty String, then {@link AbstractWriter#emptyValue} is returned
  • *
* * @param element the object to be converted into a String. * * @return the String representation of the given object */ protected String getStringValue(Object element) { usingNullOrEmptyValue = false; if (element == null) { usingNullOrEmptyValue = true; return nullValue; } String string = String.valueOf(element); if (string.isEmpty()) { usingNullOrEmptyValue = true; return emptyValue; } if (this.ignoreLeading) { int start = skipLeadingWhitespace(whitespaceRangeStart, string); if (start == string.length()) { usingNullOrEmptyValue = true; return emptyValue; } } return string; } /** * Writes a sequence of values to a row in memory. Subsequent calls to this method will add the given values in a new column of the same row, until {@link * #writeValuesToRow} is called to flush * all values accumulated and effectively write a new record to the output * * @param values the values to be written */ public final void addValues(Object... values) { try { System.arraycopy(values, 0, partialLine, partialLineIndex, values.length); partialLineIndex += values.length; } catch (Throwable t) { throw throwExceptionAndClose("Error adding values to in-memory row", values, t); } } /** * Writes a sequence of Strings to a row in memory. Subsequent calls to this method will add the given values in a new column of the same row, until {@link * #writeValuesToRow} is called to flush * all values accumulated and effectively write a new record to the output * * @param values the values to be written */ public final void addStringValues(Collection values) { if (values != null) { try { for (String o : values) { partialLine[partialLineIndex++] = o; } } catch (Throwable t) { throw throwExceptionAndClose("Error adding values to in-memory row", values.toArray(), t); } } } /** * Writes a sequence of values to a row in memory. Subsequent calls to this method will add the given values in a new column of the same row, until {@link * #writeValuesToRow} is called to flush * all values accumulated and effectively write a new record to the output * * @param values the values to be written */ public final void addValues(Collection values) { if (values != null) { try { for (Object o : values) { partialLine[partialLineIndex++] = o; } } catch (Throwable t) { throw throwExceptionAndClose("Error adding values to in-memory row", values.toArray(), t); } } } /** * Writes a value to a row in memory. Subsequent calls to this method will add the given values in a new column of the same row, until {@link * #writeValuesToRow} is called to flush * all values accumulated and effectively write a new record to the output * * @param value the value to be written */ public final void addValue(Object value) { try { partialLine[partialLineIndex++] = value; } catch (Throwable t) { throw throwExceptionAndClose("Error adding value to in-memory row", new Object[]{value}, t); } } private void fillPartialLineToMatchHeaders() { if (headers != null && partialLineIndex < headers.length) { while (partialLineIndex < headers.length) { partialLine[partialLineIndex++] = null; } } } /** * Writes the contents accumulated in an internal in-memory row (using {@link #addValues(Object...) or #writeValue()} to a new record in the output. */ public final void writeValuesToRow() { fillPartialLineToMatchHeaders(); writeRow(Arrays.copyOf(partialLine, partialLineIndex)); discardValues(); } /** * Writes a value to a row in memory. Subsequent calls to this method will add the given values in a new column of the same row, until {@link * #writeValuesToRow} is called to flush * all values accumulated and effectively write a new record to the output * * @param index the position in the row that should receive the value. * @param value the value to be written */ public final void addValue(int index, Object value) { if (index >= partialLine.length) { throw throwExceptionAndClose("Cannot write '" + value + "' to index '" + index + "'. Maximum number of columns (" + partialLine.length + ") exceeded.", new Object[]{value}, null); } partialLine[index] = value; if (partialLineIndex <= index) { partialLineIndex = index + 1; } } /** * Writes a value to a row in memory. Subsequent calls to this method will add the given values in a new column of the same row, until {@link * #writeValuesToRow} is called to flush * all values accumulated and effectively write a new record to the output * * @param headerName the name of the column of the new row that should receive the value. * @param value the value to be written */ public final void addValue(String headerName, Object value) { addValue(getFieldIndex(headers, NormalizedString.valueOf(headerName), false), value); } private final void addValue(NormalizedString[] headersInContext, NormalizedString headerName, boolean ignoreOnMismatch, Object value) { int index = getFieldIndex(headersInContext, headerName, ignoreOnMismatch); if (index != -1) { addValue(index, value); } } /** * Calculates the index of a header name in relation to the original {@link #headers} array defined in this writer * * @param headersInContext headers currently in use (they might change). * @param headerName the name of the header whose position will be identified * @param ignoreOnMismatch flag indicating that if the header is not found, no exception is to be thrown, and -1 should be returned instead. * * @return the position of the given header, or -1 if it's not found when ignoreOnMismatch is set to {@code true} */ private int getFieldIndex(NormalizedString[] headersInContext, NormalizedString headerName, boolean ignoreOnMismatch) { if (headerIndexes == null) { headerIndexes = new HashMap>(); } Map indexes = headerIndexes.get(headersInContext); if (indexes == null) { indexes = new HashMap(); headerIndexes.put(headersInContext, indexes); } Integer index = indexes.get(headerName); if (index == null) { if (headersInContext == null) { throw throwExceptionAndClose("Cannot calculate position of header '" + headerName + "' as no headers were defined.", null); } index = ArgumentUtils.indexOf(NormalizedString.toArray(headersInContext), NormalizedString.valueOf(headerName)); if (index == -1) { if (!ignoreOnMismatch) { throw throwExceptionAndClose("Header '" + headerName + "' could not be found. Defined headers are: " + Arrays.toString(headersInContext) + '.', null); } } indexes.put(headerName, index); } return index; } /** * Discards the contents written to the internal in-memory row (using {@link #addValues(Object...) or #writeValue()}. */ public final void discardValues() { Arrays.fill(partialLine, 0, partialLineIndex, null); partialLineIndex = 0; } /** * Writes the headers defined in {@link CommonSettings#getHeaders()} to a {@code String} * * @return a formatted {@code String} containing the headers defined in {@link CommonSettings#getHeaders()} */ public final String writeHeadersToString() { return writeHeadersToString(NormalizedString.toArray(this.headers)); } /** * Writes the given collection of headers to a {@code String} * A {@link TextWritingException} will be thrown if no headers were defined. * * @param headers the headers to write to a {@code String} * * @return a formatted {@code String} containing the given headers */ public final String writeHeadersToString(Collection headers) { if (headers != null && headers.size() > 0) { return writeHeadersToString(headers.toArray(new String[headers.size()])); } else { throw throwExceptionAndClose("No headers defined"); } } /** * Writes the given collection of headers to a {@code String} * A {@link TextWritingException} will be thrown if no headers were defined or if records were already written to a {@code String} * * @param headers the headers to write to a {@code String} * * @return a formatted {@code String} containing the given headers */ public final String writeHeadersToString(String... headers) { if (headers != null && headers.length > 0) { writingHeaders = true; submitRow(headers); writingHeaders = false; this.headers = NormalizedString.toIdentifierGroupArray(headers); return internalWriteRowToString(); } else { throw throwExceptionAndClose("No headers defined."); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them to a {@code List} of {@code String}. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param records the records to be transformed by a {@link RowWriterProcessor} and then written to a {@code List} of {@code String}. * * @return a {@code List} containing the information transformed from the given records as formatted {@code String}s */ public final List processRecordsToString(Iterable records) { try { List out = new ArrayList(1000); for (Object record : records) { out.add(processRecordToString(record)); } return out; } catch (Throwable t) { throw throwExceptionAndClose("Unable process input records", t); } } /** * Iterates over all records, processes each one with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, and * writes them them to a {@code List} of {@code String}. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param records the records to transformed by a {@link RowWriterProcessor} and then written a {@code String}. * * @return a {@code List} containing the information transformed from the given records as formatted {@code String}s */ public final List processRecordsToString(Object[] records) { try { List out = new ArrayList(1000); for (Object record : records) { out.add(processRecordToString(record)); } return out; } catch (Throwable t) { throw throwExceptionAndClose("Unable process input records", records, t); } } /** * Processes the data given for an individual record with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes it to a {@code String}. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param record the information of a single record to be transformed by a {@link RowWriterProcessor} and then written to a {@code String}. * * @return a formatted {@code String} containing the information transformed from the given record */ public final String processRecordToString(Object... record) { return processRecordToString((Object) record); } /** * Processes the data given for an individual record with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes it to a {@code String}. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param record the information of a single record to be transformed by a {@link RowWriterProcessor} and then written to a {@code String}. * @param the concrete Record type * * @return a formatted {@code String} containing the information transformed from the given record */ public final String processRecordToString(T record) { return processRecordToString((Object) (record == null ? null : record.getValues())); } /** * Processes the data given for an individual record with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes it. * The output will remain open for further writing. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param record the information of a single record to be transformed by a {@link RowWriterProcessor} and then written to a {@code String}. * * @return a formatted {@code String} containing the information transformed from the given record */ @SuppressWarnings("unchecked") public final String processRecordToString(Object record) { if (this.writerProcessor == null) { throw throwExceptionAndClose("Cannot process record '" + record + "' without a writer processor. Please define a writer processor instance in the settings or use the 'writeRow' methods."); } try { Object[] row = writerProcessor.write(record, getRowProcessorHeaders(), indexesToWrite); if (row != null) { return writeRowToString(row); } } catch (Throwable t) { throw throwExceptionAndClose("Could not process record '" + record + "'", t); } return null; } /** * Iterates over all records and writes them to a {@code List} of {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Object[])} for that. * * @param rows the rows to be written to a {@code List} of {@code String}. * * @return a {@code List} containing the given rows as formatted {@code String}s */ public final List writeRowsToString(Object[][] rows) { try { List out = new ArrayList(rows.length); for (Object[] row : rows) { String string = writeRowToString(row); if (string != null) { out.add(string); } } return out; } catch (Throwable t) { throw throwExceptionAndClose("Error writing input rows", t); } } /** * Iterates over all records and writes them to a {@code List} of {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param Collection of objects containing values of a row * @param rows the rows to be written to a {@code List} of {@code String}. * * @return a {@code List} containing the given rows as formatted {@code String}s */ public final > List writeRowsToString(Iterable rows) { try { List out = new ArrayList(1000); for (Collection row : rows) { out.add(writeRowToString(row)); } return out; } catch (Throwable t) { throw throwExceptionAndClose("Error writing input rows", t); } } /** * Iterates over all records and writes them to a {@code List} of {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param Collection of objects containing values of a row * @param rows the rows to be written to a {@code List} of {@code String}. * * @return a {@code List} containing the given rows as formatted {@code String}s */ public final > List writeStringRowsToString(Iterable rows) { try { List out = new ArrayList(1000); for (Collection row : rows) { String string = writeRowToString(row); if (string != null) { out.add(string); } } return out; } catch (Throwable t) { throw throwExceptionAndClose("Error writing input rows", t); } } /** * Iterates over all records and writes them to a {@code List} of {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param rows the rows to be written to a {@code List} of {@code String}. * * @return a {@code List} containing the given rows as formatted {@code String}s */ public final List writeRowsToString(Collection rows) { try { List out = new ArrayList(rows.size()); for (Object[] row : rows) { out.add(writeRowToString(row)); } return out; } catch (Throwable t) { throw throwExceptionAndClose("Error writing input rows", t); } } /** * Iterates over all records and writes them to a {@code List} of {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param rows the rows to be written to a {@code List} of {@code String}. * * @return a {@code List} containing the given rows as formatted {@code String}s */ public final List writeStringRowsToString(Collection rows) { try { List out = new ArrayList(rows.size()); for (String[] row : rows) { out.add(writeRowToString(row)); } return out; } catch (Throwable t) { throw throwExceptionAndClose("Error writing input rows", t); } } /** * Iterates over all records and writes them to a {@code List} of {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecords(Iterable)} for that. * * @param rows the rows to be written to a {@code List} of {@code String}. * * @return a {@code List} containing the given rows as formatted {@code String}s */ public final List writeRecordsToString(Collection rows) { try { List out = new ArrayList(rows.size()); for (Record row : rows) { out.add(writeRecordToString(row)); } return out; } catch (Throwable t) { throw throwExceptionAndClose("Error writing input rows", t); } } /** * Writes the data given for an individual record to a {@code String}. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to a {@code String} * * @return a formatted {@code String} containing the information of the given record */ public final String writeRowToString(Collection row) { try { if (row == null) { return null; } return writeRowToString(row.toArray()); } catch (Throwable t) { throw throwExceptionAndClose("Error writing input row ", t); } } /** * Writes the data given for an individual record to a {@code String}. * If the given data is null or empty, and {@link CommonSettings#getSkipEmptyLines()} is true, {@code null} will be returned * In case of any errors, a {@link TextWritingException} will be thrown. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to a {@code String}. * * @return a formatted {@code String} containing the information of the given record */ public final String writeRowToString(String[] row) { return writeRowToString((Object[]) row); } /** * Writes the data given for an individual record to a {@code String}. * If the given data is null or empty, and {@link CommonSettings#getSkipEmptyLines()} is true, {@code null} will be returned * In case of any errors, a {@link TextWritingException} will be thrown. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to a {@code String}. * * @return a formatted {@code String} containing the information of the given record */ public final String writeRecordToString(T row) { return writeRowToString((Object[]) (row == null ? null : row.getValues())); } /** * Writes the data given for an individual record to a {@code String}. * If the given data is null or empty, and {@link CommonSettings#getSkipEmptyLines()} is true, {@code null} will be returned * In case of any errors, a {@link TextWritingException} will be thrown. * Note this method will not use the {@link RowWriterProcessor}. Use {@link AbstractWriter#processRecord(Object)} for that. * * @param row the information of a single record to be written to a {@code String}. * * @return a formatted {@code String} containing the information of the given record */ public final String writeRowToString(Object... row) { try { if (row == null || (row.length == 0 && !expandRows)) { if (skipEmptyLines) { return null; } } row = adjustRowLength(row); submitRow(row); return internalWriteRowToString(); } catch (Throwable ex) { throw throwExceptionAndClose("Error writing row.", row, ex); } } private Object[] adjustRowLength(Object[] row) { if (outputRow != null) { fillOutputRow(row); row = outputRow; } else if (expandRows) { if (usingSwitch) { row = expand(row, dummyHeaderRow == null ? -1 : dummyHeaderRow.length, headers == null ? null : headers.length); dummyHeaderRow = null; } else { row = expand(row, headers == null ? -1 : headers.length, null); } } return row; } /** * Writes a comment row to a {@code String} * * @param comment the contents to be written as a comment to a {@code String}. * * @return a formatted {@code String} containing the comment. */ public final String commentRowToString(String comment) { return writeRowToString(this.comment + comment); } /** * Writes the accumulated value of a record to the output, followed by a newline, and increases the record count. * The newline character sequence will conform to what is specified in {@link Format#getLineSeparator()} * The contents of {@link AbstractWriter#rowAppender} depend on the concrete implementation of {@link AbstractWriter#processRow(Object[])} * * @return a formatted {@code String} containing the comment. */ private String internalWriteRowToString() { if (skipEmptyLines && rowAppender.length() == 0) { return null; } String out = rowAppender.getAndReset(); recordCount++; return out; } /** * Writes the contents accumulated in an internal in-memory row (using {@link #addValues(Object...) or #addValue()} as a {@code String} * * @return a formatted {@code String} containing the information accumulated in the internal in-memory row. */ public final String writeValuesToString() { fillPartialLineToMatchHeaders(); String out = writeRowToString(Arrays.copyOf(partialLine, partialLineIndex)); discardValues(); return out; } /** * Writes the contents accumulated in an internal in-memory row (using {@link #addValues(Object...) or #addValue()} to a new record in the output. * The objects added to this row will be processed with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * The output will remain open for further writing. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. */ public final void processValuesToRow() { fillPartialLineToMatchHeaders(); processRecord(Arrays.copyOf(partialLine, partialLineIndex)); discardValues(); } /** * Writes the contents accumulated in an internal in-memory row (using {@link #addValues(Object...) or #addValue()} to a {@code String} * The objects added to this row will be processed with the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * The output will remain open for further writing. * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @return a formatted {@code String} containing the result produced by the {@link RowWriterProcessor} using the values accumulated in internal in-memory row. */ public final String processValuesToString() { fillPartialLineToMatchHeaders(); String out = processRecordToString(Arrays.copyOf(partialLine, partialLineIndex)); discardValues(); return out; } /** * Returns the number of records written to the output so far * * @return the number of records written to the output so far */ public final long getRecordCount() { return recordCount; } /** * Writes values from an implementation of {@link java.util.Map} to a partial output record, ready to be * written to the output. * * Values will be stored under a column identified by the headers. If no headers are defined, * the keys of the map will be used to initialize an internal header row. * * A map of headers can be optionally provided to assign a name to the keys of the input map. This is useful when * the input map has keys will generate unwanted header names. * * @param headerMapping an optional map associating keys of the rowData map with expected header names * @param rowData the data to be written. Its keys will be used to form a header row in case no headers are available. * @param type of the key in both rowData and headerMapping maps. */ private void writeValuesFromMap(Map headerMapping, Map rowData) { try { if (rowData != null && !rowData.isEmpty()) { dummyHeaderRow = this.headers; if (usingSwitch) { dummyHeaderRow = ((RowWriterProcessorSwitch) writerProcessor).getHeaders(headerMapping, rowData); if (dummyHeaderRow == null) { dummyHeaderRow = this.headers; } } if (dummyHeaderRow != null) { if (headerMapping == null) { for (Map.Entry e : rowData.entrySet()) { addValue(dummyHeaderRow, NormalizedString.valueOf(e.getKey()), true, e.getValue()); } } else { for (Map.Entry e : rowData.entrySet()) { String header = headerMapping.get(e.getKey()); if (header != null) { addValue(dummyHeaderRow, NormalizedString.valueOf(header), true, e.getValue()); } } } } else if (headerMapping != null) { setHeadersFromMap(headerMapping, false); writeValuesFromMap(headerMapping, rowData); } else { setHeadersFromMap(rowData, true); writeValuesFromMap(null, rowData); } } } catch (Throwable t) { throw throwExceptionAndClose("Error processing data from input map", t); } } /** * Iterates over the keys of a map and builds an internal header row. * * @param map the input map whose keys will be used to generate headers for the output. * @param keys indicates whether to take the map keys or values to build the header rows. */ private void setHeadersFromMap(Map map, boolean keys) { this.headers = new NormalizedString[map.size()]; int i = 0; for (Object header : keys ? map.keySet() : map.values()) { headers[i++] = NormalizedString.valueOf(header); } } /** * Writes the values of a given map to a {@code String} formatted to according to the specified output format. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a {@code String}. * * @return a {@code String} containing the given data as a formatted {@code String} */ public final String writeRowToString(Map rowData) { return writeRowToString(null, (Map) rowData); } /** * Writes the values of a given map into new output record * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a new record */ public final void writeRow(Map rowData) { writeRow(null, (Map) rowData); } /** * Writes the values of a given map to a {@code String} formatted to according to the specified output format. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code String}. * @param the key type * * @return a {@code String} containing the given data as a formatted {@code String} */ public final String writeRowToString(Map headerMapping, Map rowData) { writeValuesFromMap(headerMapping, rowData); return writeValuesToString(); } /** * Writes the values of a given map into new output record * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a new record * @param the key type */ public final void writeRow(Map headerMapping, Map rowData) { writeValuesFromMap(headerMapping, rowData); writeValuesToRow(); } /** * Writes the values of a given map to a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * @param the iterable type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final > List writeRowsToString(Map rowData) { return writeRowsToString(null, rowData); } /** * Writes the values of a given map to multiple output records * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void writeRows(Map rowData) { writeRows(null, rowData, null, false); } /** * Writes the values of a given map to a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * @param the iterable type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final > List writeRowsToString(Map headerMapping, Map rowData) { List writtenRows = new ArrayList(); writeRows(headerMapping, rowData, writtenRows, false); return writtenRows; } /** * Writes the values of a given map to multiple output records * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void writeRows(Map headerMapping, Map rowData) { writeRows(headerMapping, rowData, null, false); } /** * Writes the values of a given map to a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param outputList an output {@code List} to fill with formatted {@code String}s, each {@code String} representing * one successful iteration over at least one * element of the iterators in the map. * @param the key type * @param the iterable type */ private > void writeRows(Map headerMapping, Map rowData, List outputList, boolean useRowProcessor) { try { Iterator[] iterators = new Iterator[rowData.size()]; Object[] keys = new Object[rowData.size()]; final Map rowValues = new LinkedHashMap(rowData.size()); if (outputList != null && headers == null) { if (headerMapping != null) { setHeadersFromMap(headerMapping, true); } else { setHeadersFromMap(rowData, true); } } if (recordCount == 0 && headers != null && isHeaderWritingEnabled) { outputList.add(writeHeadersToString()); } int length = 0; for (Map.Entry rowEntry : rowData.entrySet()) { iterators[length] = rowEntry.getValue() == null ? null : rowEntry.getValue().iterator(); keys[length] = rowEntry.getKey(); rowValues.put(rowEntry.getKey(), null); length++; } boolean nullsOnly; do { nullsOnly = true; for (int i = 0; i < length; i++) { Iterator iterator = iterators[i]; boolean isNull = iterator == null || !iterator.hasNext(); nullsOnly &= isNull; if (isNull) { rowValues.put(keys[i], null); } else { rowValues.put(keys[i], iterator.next()); } } if (!nullsOnly) { if (outputList == null) { if (useRowProcessor) { processRecord((Map) headerMapping, (Map) rowValues); } else { writeRow((Map) headerMapping, (Map) rowValues); } } else { if (useRowProcessor) { outputList.add(processRecordToString((Map) headerMapping, (Map) rowValues)); } else { outputList.add(writeRowToString((Map) headerMapping, (Map) rowValues)); } } } } while (!nullsOnly); } catch (Throwable t) { throw throwExceptionAndClose("Error processing input rows from map", t); } } /** * Writes the values of a given map to a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final List writeStringRowsToString(Map headerMapping, Map rowData) { List writtenRows = new ArrayList(); writeRows(headerMapping, wrapStringArray(rowData), writtenRows, false); return writtenRows; } /** * Writes the values of a given map to a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final List writeRecordsToString(Map headerMapping, Map rowData) { List writtenRows = new ArrayList(); writeRows(headerMapping, wrapRecordValues(rowData), writtenRows, false); return writtenRows; } /** * Writes the values of a given map to multiple output records * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeStringRows(Map headerMapping, Map rowData) { writeRows(headerMapping, wrapStringArray(rowData), null, false); } /** * Writes the values of a given map to multiple output records * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeRecords(Map headerMapping, Map rowData) { writeRows(headerMapping, wrapRecordValues(rowData), null, false); } /** * Writes the values of a given map to a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final List writeObjectRowsToString(Map headerMapping, Map rowData) { List writtenRows = new ArrayList(); writeRows(headerMapping, wrapObjectArray(rowData), writtenRows, false); return writtenRows; } /** * Writes the values of a given map to multiple output records * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeObjectRows(Map headerMapping, Map rowData) { writeRows(headerMapping, wrapObjectArray(rowData), null, false); } private Map> wrapObjectArray(Map rowData) { Map> out = new LinkedHashMap>(rowData.size()); for (Map.Entry e : rowData.entrySet()) { if (e.getValue() == null) { out.put(e.getKey(), Collections.emptyList()); } else { out.put(e.getKey(), Arrays.asList(e.getValue())); } } return out; } private Map> wrapStringArray(Map rowData) { Map> out = new LinkedHashMap>(rowData.size()); for (Map.Entry e : rowData.entrySet()) { if (e.getValue() == null) { out.put(e.getKey(), Collections.emptyList()); } else { out.put(e.getKey(), Arrays.asList(e.getValue())); } } return out; } private Map> wrapRecordValues(Map rowData) { Map> out = new LinkedHashMap>(rowData.size()); for (Map.Entry e : rowData.entrySet()) { if (e.getValue() == null) { out.put(e.getKey(), Collections.emptyList()); } else { out.put(e.getKey(), Arrays.asList(e.getValue().getValues())); } } return out; } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeObjectRowsAndClose(Map headerMapping, Map rowData) { try { writeObjectRows(headerMapping, rowData); } finally { close(); } } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeStringRowsAndClose(Map headerMapping, Map rowData) { try { writeStringRows(headerMapping, rowData); } finally { close(); } } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeRecordsAndClose(Map headerMapping, Map rowData) { try { writeRecords(headerMapping, rowData); } finally { close(); } } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeObjectRowsAndClose(Map rowData) { writeObjectRowsAndClose(null, rowData); } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeStringRowsAndClose(Map rowData) { writeStringRowsAndClose(null, rowData); } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void writeRecordsAndClose(Map rowData) { writeRecordsAndClose(null, rowData); } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void writeRowsAndClose(Map headerMapping, Map rowData) { try { writeRows(headerMapping, rowData); } finally { close(); } } /** * Writes the values of a given map to multiple output records and closes the output when finished. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * Note this method will not use the {@link RowWriterProcessor}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void writeRowsAndClose(Map rowData) { writeRowsAndClose(null, rowData); } /** * Processes the values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into {@code String} formatted according to the specified output format. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * * @return a {@code String} containing the given data as a formatted {@code String} */ public final String processRecordToString(Map rowData) { return processRecordToString(null, (Map) rowData); } /** * Processes the values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into a new output record * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. */ public final void processRecord(Map rowData) { processRecord(null, (Map) rowData); } /** * Processes the values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into {@code String} formatted according to the specified output format. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * * @return a {@code String} containing the given data as a formatted {@code String} */ public final String processRecordToString(Map headerMapping, Map rowData) { writeValuesFromMap(headerMapping, rowData); return processValuesToString(); } /** * Processes the values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into a new output record * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type */ public final void processRecord(Map headerMapping, Map rowData) { writeValuesFromMap(headerMapping, rowData); processValuesToRow(); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * @param the iterable type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final > List processRecordsToString(Map rowData) { return processRecordsToString(null, rowData); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output . * * The output will remain open for further write operations. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void processRecords(Map rowData) { writeRows(null, rowData, null, true); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * @param the iterable type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final > List processRecordsToString(Map headerMapping, Map rowData) { List writtenRows = new ArrayList(); writeRows(headerMapping, rowData, writtenRows, true); return writtenRows; } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output . * * The output will remain open for further write operations. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void processRecords(Map headerMapping, Map rowData) { writeRows(headerMapping, rowData, null, true); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final List processObjectRecordsToString(Map rowData) { return processObjectRecordsToString(null, rowData); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()} * and writes the result into a {@code List} of {@code String} formatted to according to the specified output format. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a {@code List} of {@code String}. * @param the key type * * @return a {@code List} of formatted {@code String}, each {@code String} representing one successful iteration over at least one * element of the iterators in the map. */ public final List processObjectRecordsToString(Map headerMapping, Map rowData) { List writtenRows = new ArrayList(); writeRows(headerMapping, wrapObjectArray(rowData), writtenRows, true); return writtenRows; } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output . * * The output will remain open for further write operations. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void processObjectRecords(Map headerMapping, Map rowData) { writeRows(headerMapping, wrapObjectArray(rowData), null, true); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output and closes the writer. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void processObjectRecordsAndClose(Map headerMapping, Map rowData) { try { processObjectRecords(headerMapping, rowData); } finally { close(); } } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output and closes the writer. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type */ public final void processObjectRecordsAndClose(Map rowData) { processRecordsAndClose(null, wrapObjectArray(rowData)); } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output and closes the writer. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param headerMapping a mapping associating the keys of the input map to their corresponding header names. * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void processRecordsAndClose(Map headerMapping, Map rowData) { try { processRecords(headerMapping, rowData); } finally { close(); } } /** * Processes the data in all values of a map using the {@link RowWriterProcessor} provided by {@link CommonWriterSettings#getRowWriterProcessor()}, * then writes all values to the output and closes the writer. * * Each value is expected to be iterable and the result of this method will produce the number of records equal to the longest iterable. * * A new record will be created each time at least one {@link Iterator#hasNext()} returns {@code true}. {@code Null} will be written * when a iterator has been fully read. * * A {@link TextWritingException} will be thrown if no {@link RowWriterProcessor} is provided by {@link CommonWriterSettings#getRowWriterProcessor()}. * * @param rowData the map whose values will be used to generate a number of output records * @param the key type * @param the iterable type */ public final > void processRecordsAndClose(Map rowData) { processRecordsAndClose(null, rowData); } private Object[] getContent(Object[] tmp) { return AbstractException.restrictContent(errorContentLength, tmp); } private String getContent(CharSequence tmp) { return AbstractException.restrictContent(errorContentLength, tmp); } /** * Checks whether the writer can remove trailing/leading whitespaces from a value being written. * Applies to headers where names can be conflicting if trimmed for example {@code ' a '} and * {@code 'a'} will become the same value if the spaces are removed) * * @param fieldIndex index of the field to be written. * * @return {@code true} if the value being written is not a header name, or it is a header name that won't * conflict with another header if its surrounding whitespaces are trimmed. */ protected final boolean allowTrim(int fieldIndex) { return !writingHeaders || fieldIndex >= headerTrimFlags.length || headerTrimFlags[fieldIndex]; } }jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ArgumentUtils.java000066400000000000000000000467041475274123300331560ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.input.*; import java.io.*; import java.nio.charset.*; import java.util.*; import static java.lang.reflect.Array.*; /** * An utility class for validating inputs. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class ArgumentUtils { /** * An empty String array. */ public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final NormalizedString[] EMPTY_NORMALIZED_STRING_ARRAY = new NormalizedString[0]; /** * Throws an IllegalArgumentException if the given array is null or empty. * * @param argDescription the description of the elements * @param args the elements to be validated. * @param Type of arguments to be validated */ public static void notEmpty(String argDescription, T... args) { if (args == null) { throw new IllegalArgumentException(argDescription + " must not be null"); } if (args.length == 0) { throw new IllegalArgumentException(argDescription + " must not be empty"); } } /** * Throws an IllegalArgumentException if the given array is null,empty, or contains null values * * @param argDescription the description of the elements * @param args the elements to be validated. * @param Type of arguments to be validated */ public static void noNulls(String argDescription, T... args) { notEmpty(argDescription, args); for (T arg : args) { if (arg == null) { if (args.length > 0) { throw new IllegalArgumentException(argDescription + " must not contain nulls"); } else { throw new IllegalArgumentException(argDescription + " must not be null"); } } } } /** * Returns the index of a header, when headers are selected using a {@link FieldSelector}. * * @param array the element array * @param element the element to be looked for in the array. * @param fieldSelector a field selector that indicates which elements of the given array are selected. * * @return the index of the given element in the array, or -1 if the element could not be found. */ public static int indexOf(NormalizedString[] array, NormalizedString element, FieldSelector fieldSelector) { int index = indexOf(array, element); if (fieldSelector == null || index == -1) { return index; } int[] indexes = fieldSelector.getFieldIndexes(array); for (int i = 0; i < indexes.length; i++) { if (indexes[i] == index) { return i; } } return -1; } /** * Returns the indexes of an element in a given array. * * @param array the element array * @param element the element to be looked for in the array. * * @return the indexes of the given element in the array, or an empty array if no element could be found */ public static int[] indexesOf(Object[] array, Object element) { int[] tmp = new int[0]; int i = 0; int o = 0; while (i < array.length) { i = indexOf(array, element, i); if (i == -1) { break; } tmp = Arrays.copyOf(tmp, tmp.length + 1); tmp[o++] = i; i++; } return tmp; } /** * Returns the index of an element in a given array. * * @param array the element array * @param element the element to be looked for in the array. * * @return the index of the given element in the array, or -1 if the element could not be found. */ public static int indexOf(Object[] array, Object element) { return indexOf(array, element, 0); } /** * Returns the index of a character in a given array. * * @param array the character array * @param element the character to be looked for in the array. * @param from the starting position of the array from where to start the search * * @return the index of the given character in the array, or -1 if the character could not be found. */ public static int indexOf(char[] array, char element, int from) { for (int i = from; i < array.length; i++) { if (array[i] == element) { return i; } } return -1; } /** * Returns the index of an element in a given array. * * @param array the element array * @param element the element to be looked for in the array. * @param from the starting position of the array from where to start the search * * @return the index of the given element in the array, or -1 if the element could not be found. */ private static int indexOf(Object[] array, Object element, int from) { if (array == null) { throw new NullPointerException("Null array"); } if (element == null) { for (int i = from; i < array.length; i++) { if (array[i] == null) { return i; } } } else { if (element.getClass() != array.getClass().getComponentType()) { throw new IllegalStateException("a"); } if (element instanceof String && array instanceof String[]) { for (int i = from; i < array.length; i++) { String e = String.valueOf(array[i]); if (element.toString().equalsIgnoreCase(e)) { return i; } } } else { for (int i = from; i < array.length; i++) { if (element.equals(array[i])) { return i; } } } } return -1; } /** * Searches for elements in a given array and returns the elements not found. * * @param array An array with elements * @param elements the elements to be found * * @return the elements not found in the array. */ public static Object[] findMissingElements(Object[] array, Collection elements) { return findMissingElements(array, elements.toArray()); } /** * Searches for elements in a given array and returns the elements not found. * * @param array An array with elements * @param elements the elements to be found * * @return the elements not found in the array. */ public static Object[] findMissingElements(Object[] array, Object[] elements) { List out = new ArrayList(); for (Object element : elements) { if (indexOf(array, element) == -1) { out.add(element); } } return out.toArray(); } /** * Creates a {@link java.io.Writer} from an output stream * * @param output the output stream * * @return {@link java.io.Writer} wrapping the given output stream */ public static Writer newWriter(OutputStream output) { return newWriter(output, (Charset) null); } /** * Creates a {@link java.io.Writer} from an output stream * * @param output the output stream * @param encoding the encoding to use when writing to the output stream * * @return {@link java.io.Writer} wrapping the given output stream */ public static Writer newWriter(OutputStream output, String encoding) { return newWriter(output, Charset.forName(encoding)); } /** * Creates a {@link java.io.Writer} from an output stream * * @param output the output stream * @param encoding the encoding to use when writing to the output stream * * @return {@link java.io.Writer} wrapping the given output stream */ public static Writer newWriter(OutputStream output, Charset encoding) { if (encoding != null) { return new OutputStreamWriter(output, encoding); } else { return new OutputStreamWriter(output); } } /** * Creates a {@link java.io.Writer} from a file * * @param file the file to be written * * @return {@link java.io.Writer} for the given file */ public static Writer newWriter(File file) { return newWriter(file, (Charset) null); } /** * Creates a {@link java.io.Writer} from a file * * @param file the file to be written * @param encoding the encoding to use when writing to the file * * @return {@link java.io.Writer} for the given file */ public static Writer newWriter(File file, String encoding) { return newWriter(file, Charset.forName(encoding)); } /** * Creates a {@link java.io.Writer} from a file * * @param file the file to be written * @param encoding the encoding to use when writing to the file * * @return {@link java.io.Writer} for the given file */ public static Writer newWriter(File file, Charset encoding) { if (!file.exists()) { File parent = file.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } try { file.createNewFile(); } catch (IOException e) { throw new IllegalArgumentException("Unable to create file '" + file.getAbsolutePath() + "', please ensure your application has permission to create files in that path", e); } } FileOutputStream os; try { os = new FileOutputStream(file); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } return newWriter(os, encoding); } /** * Creates a {@link java.io.Reader} from an input stream * * @param input the input stream * * @return a {@link java.io.Reader} wrapping the given input stream */ public static Reader newReader(InputStream input) { return newReader(input, (Charset) null); } /** * Creates a {@link java.io.Reader} from an input stream * * @param input the input stream * @param encoding the encoding to use when reading from the input stream * * @return a {@link java.io.Reader} wrapping the given input stream */ public static Reader newReader(InputStream input, String encoding) { return newReader(input, encoding == null ? (Charset) null : Charset.forName(encoding)); } /** * Creates a {@link java.io.Reader} from an input stream * * @param input the input stream * @param encoding the encoding to use when reading from the input stream * * @return a {@link java.io.Reader} wrapping the given input stream */ public static Reader newReader(InputStream input, Charset encoding) { if (encoding == null) { BomInput bomInput = new BomInput(input); if (bomInput.getEncoding() != null) { //charset detected. Just set the encoding and keep using the original input stream. encoding = bomInput.getCharset(); } if (bomInput.hasBytesStored()) { //there are bytes to be processed. We should use the BomInput wrapper to read the first bytes already consumed when trying to match the BOM. input = bomInput; } //else the original input can be used and the wrapper is not necessary, as a BOM has been matched and the bytes discarded. } if (encoding != null) { return new InputStreamReader(input, encoding); } else { return new InputStreamReader(input); } } /** * Creates a {@link java.io.Reader} for a given a file * * @param file the file to be read * * @return a {@link java.io.Reader} for reading the given file */ public static Reader newReader(File file) { return newReader(file, (Charset) null); } /** * Creates a {@link java.io.Reader} for a given a file * * @param file the file to be read * @param encoding the encoding to be used when reading from the file * * @return a {@link java.io.Reader} for reading the given file */ public static Reader newReader(File file, String encoding) { return newReader(file, Charset.forName(encoding)); } /** * Creates a {@link java.io.Reader} for a given a file * * @param file the file to be read * @param encoding the encoding to be used when reading from the file * * @return a {@link java.io.Reader} for reading the given file */ public static Reader newReader(File file, Charset encoding) { FileInputStream input; try { input = new FileInputStream(file); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } return newReader(input, encoding); } /** * Converts a list of enumerations to an array of their {@link Enum#toString()} representation * * @param enums a list of enumerations to convert * * @return an array of {@code String} with the values produced by each element's {@link Enum#toString()} method. */ @SuppressWarnings("rawtypes") public static String[] toArray(List enums) { String[] out = new String[enums.size()]; for (int i = 0; i < out.length; i++) { out[i] = enums.get(i).toString(); } return out; } /** * Converts any collection of {@code Integer} into an {@code int} array. * * @param ints a collection of (boxed) integers. * * @return a primitive {@code int} array with the unboxed integer values. */ public static int[] toIntArray(Collection ints) { int[] out = new int[ints.size()]; int i = 0; for (Integer boxed : ints) { out[i++] = boxed.intValue(); } return out; } /** * Converts any collection of {@code Character} into a char array. * * @param characters a collection of (boxed) characters. * * @return a primitive {@code char} array with the unboxed character values. */ public static char[] toCharArray(Collection characters) { char[] out = new char[characters.size()]; int i = 0; for (Character boxed : characters) { out[i++] = boxed.charValue(); } return out; } /** * Restricts the length of a given content. * * @param length the maximum length to be displayed. If {@code 0}, the {@code ""} string will be returned. * @param content the content whose length should be restricted. * * @return the restricted content. */ public static String restrictContent(int length, CharSequence content) { if (content == null) { return null; } if (length == 0) { return ""; } if (length == -1) { return content.toString(); } int errorMessageStart = content.length() - length; if (length > 0 && errorMessageStart > 0) { return "..." + content.subSequence(errorMessageStart, content.length()).toString(); } return content.toString(); } /** * Restricts the length of a given content. * * @param length the maximum length to be displayed. If {@code 0}, the {@code ""} string will be returned. * @param content the content whose length should be restricted. * * @return the restricted content. */ public static String restrictContent(int length, Object content) { if (content == null) { return null; } if (content instanceof Object[]) { return restrictContent(length, Arrays.toString((Object[]) content)); } return restrictContent(length, String.valueOf(content)); } /** * Allows rethrowing a checked exception instead of wrapping it into a runtime exception. For internal use only * as this generally causes more trouble than it solves (your exception-specific catch statement may not catch this * error - make sure you are catching a Throwable) * * @param error the (potentially checked) exception to the thrown. */ public static void throwUnchecked(Throwable error) { ArgumentUtils.throwsUnchecked(error); } private static void throwsUnchecked(Throwable toThrow) throws T { throw (T) toThrow; } /** * Converts a sequence of int numbers into a byte array. * * @param ints the integers to be cast to by * * @return the resulting byte array. */ public static byte[] toByteArray(int... ints) { byte[] out = new byte[ints.length]; for (int i = 0; i < ints.length; i++) { out[i] = (byte) ints[i]; } return out; } /** * Identifies duplicate values in a given array and returns them * * @param array the search array * @param the type of elements held in the given array. * * @return all duplicate values found in the given array, or empty array if no duplicates, or {@code null} if the input is {@code null}. */ public static T[] findDuplicates(T[] array) { if (array == null || array.length == 0) { return array; } Set elements = new HashSet(array.length); ArrayList duplicates = new ArrayList(1); for (T element : array) { if (!elements.contains(element)) { elements.add(element); } else { duplicates.add(element); } } return duplicates.toArray((T[]) newInstance(array.getClass().getComponentType(), duplicates.size())); } /** * Removes surrounding spaces from a given {@code String}, from its right or left side, or both. * * @param input the content to trim * @param left flag to indicate whether spaces on the left side of the string should be removed. * @param right flag to indicate whether spaces on the right side of the string should be removed. * * @return the trimmed string. */ public static String trim(String input, boolean left, boolean right) { if (input.length() == 0 || !left && !right) { return input; } int begin = 0; while (left && begin < input.length() && input.charAt(begin) <= ' ') { begin++; } if (begin == input.length()) { return ""; } int end = begin + input.length() - 1; if (end >= input.length()) { end = input.length() - 1; } while (right && input.charAt(end) <= ' ') { end--; } if (begin == end) { return ""; } if (begin == 0 && end == input.length() - 1) { return input; } return input.substring(begin, end + 1); } /** * Displays line separators in a string by replacing all instances * of `\r` and `\n` with `[cr]` and `[lf]`. * If `\r` is followed by `\n` or vice versa, then `[crlf]` or `[lfcr]` will be printed. * * @param str the string to have its line separators displayed * @param addNewLine flag indicating whether the original `\r` or `\n` characters should be kept in the string. * if {@code true}, `\r` will be replaced by `[cr]\r` for example. * * @return the updated string with any line separators replaced by visible character sequences. */ public static String displayLineSeparators(String str, boolean addNewLine) { StringBuilder out = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '\r' || ch == '\n') { out.append('['); out.append(ch == '\r' ? "cr" : "lf"); char next = '\0'; if (i + 1 < str.length()) { next = str.charAt(i + 1); if (next != ch && (next == '\r' || next == '\n')) { out.append(next == '\r' ? "cr" : "lf"); i++; } else { next = '\0'; } } out.append(']'); if (addNewLine) { out.append(ch); if (next != '\0') { out.append(next); } } } else { out.append(ch); } } return out.toString(); } /** * Removes all instances of a given element from an int array. * * @param array the array to be checked * @param e the element to be removed * * @return an updated array that does not contain the given element anywhere, * or the original array if the element has not been found. */ public static int[] removeAll(int[] array, int e) { if (array == null || array.length == 0) { return array; } int removeCount = 0; for (int i = 0; i < array.length; i++) { if (array[i] == e) { removeCount++; } } if (removeCount == 0) { return array; } int[] tmp = new int[array.length - removeCount]; for (int i = 0, j = 0; i < array.length; i++) { if (array[i] != e) { tmp[j++] = array[i]; } } return tmp; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ColumnMap.java000066400000000000000000000106501475274123300322350ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.fields.*; import java.util.*; /** * Class responsible for calculating and storing the position of fields parsed from the input. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public class ColumnMap { private Map columnMap; private int[] enumMap; private int[] extractedIndexes = null; private final Context context; private final ParserOutput output; public ColumnMap(Context context, ParserOutput output) { this.context = context; this.output = output; } /** * Returns the position of a header (0 based). * * @param header the header whose position will be returned * * @return the position of the given header, or -1 if it could not be found. */ public int indexOf(String header) { if (columnMap != null && columnMap.isEmpty()) { return -1; } validateHeader(header); NormalizedString normalizedHeader = NormalizedString.valueOf(header); if (columnMap == null) { NormalizedString[] headers = NormalizedString.toIdentifierGroupArray(context.headers()); if (headers == null) { columnMap = Collections.emptyMap(); return -1; } columnMap = new HashMap(headers.length); extractedIndexes = context.extractedFieldIndexes(); if (extractedIndexes != null) { if (context.columnsReordered()) { int[] selection = ArgumentUtils.removeAll(extractedIndexes, -1); for (int i = 0; i < selection.length; i++) { int originalIndex = selection[i]; NormalizedString h = headers[originalIndex]; columnMap.put(h, i); } } else { for (int i = 0; i < extractedIndexes.length && i < headers.length; i++) { columnMap.put(headers[i], i); } } } else { for (int i = 0; i < headers.length; i++) { columnMap.put(headers[i], i); } } } Integer index = columnMap.get(normalizedHeader); if (index == null) { return -1; } return index.intValue(); } private void validateHeader(Object header) { if (header == null) { if (context.headers() == null) { throw new IllegalArgumentException("Header name cannot be null."); } throw new IllegalArgumentException("Header name cannot be null. Use one of the available column names: " + Arrays.asList(context.headers())); } } /** * Returns the position of a header (0 based). * * @param header the header whose position will be returned * * @return the position of the given header, or -1 if it could not be found. */ public int indexOf(Enum header) { if (enumMap != null && enumMap.length == 0) { return -1; } validateHeader(header); if (enumMap == null) { NormalizedString[] headers = NormalizedString.toIdentifierGroupArray(context.headers()); if (headers == null) { enumMap = new int[0]; return -1; } Enum[] constants = header.getClass().getEnumConstants(); int lastOrdinal = Integer.MIN_VALUE; for (int i = 0; i < constants.length; i++) { if (lastOrdinal < constants[i].ordinal()) { lastOrdinal = constants[i].ordinal(); } } enumMap = new int[lastOrdinal + 1]; FieldSelector selector = output == null ? null : output.getFieldSelector(); if (!context.columnsReordered()) { selector = null; } for (int i = 0; i < constants.length; i++) { Enum constant = constants[i]; String name = constant.toString(); int index = ArgumentUtils.indexOf(headers, NormalizedString.valueOf(name), selector); enumMap[constant.ordinal()] = index; } } return enumMap[header.ordinal()]; } void reset() { columnMap = null; enumMap = null; extractedIndexes = null; } } CommonParserSettings.java000066400000000000000000000625701475274123300344210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.input.*; import com.univocity.parsers.common.input.concurrent.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * This is the parent class for all configuration classes used by parsers ({@link AbstractParser}) * *

By default, all parsers work with, at least, the following configuration options in addition to the ones provided by {@link CommonSettings}: * *

    *
  • rowProcessor: a callback implementation of the interface {@link RowProcessor} which handles the life cycle of the parsing process and processes each record extracted from the input
  • *
  • headerExtractionEnabled (defaults to false): indicates whether or not the first valid record parsed from the input should be considered as the row containing the names of each column
  • *
  • columnReorderingEnabled (defaults to true): indicates whether fields selected using the field selection methods (defined by the parent class {@link CommonSettings}) should be reordered. *

    When disabled, each parsed record will contain values for all columns, in the order they occur in the input. Fields which were not selected will not be parsed but and the record will contain empty values. *

    When enabled, each parsed record will contain values only for the selected columns. The values will be ordered according to the selection. *

  • inputBufferSize (defaults to 1024*1024 characters): The number of characters held by the parser's buffer when processing the input. *
  • readInputOnSeparateThread (defaults true if the number of available processors at runtime is greater than 1): *

    When enabled, a reading thread (in {@code input.concurrent.ConcurrentCharInputReader}) will be started and load characters from the input, while the parser is processing its input buffer. * This yields better performance, especially when reading from big input (greater than 100 mb) *

    When disabled, the parsing process will briefly pause so the buffer can be replenished every time it is exhausted (in {@link DefaultCharInputReader} it is not as bad or slow as it sounds, and can even be (slightly) more efficient if your input is small) *

  • numberOfRecordsToRead (defaults to -1): Defines how many (valid) records are to be parsed before the process is stopped. A negative value indicates there's no limit.
  • *
  • lineSeparatorDetectionEnabled (defaults to false): Attempts to identify what is the line separator being used in the input. * The first row of the input will be read until a sequence of '\r\n', or characters '\r' or '\n' is found. If a match is found, then it will be used as the line separator to use to parse the input
  • *
* * @param the format supported by this parser. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.processor.RowProcessor * @see com.univocity.parsers.csv.CsvParserSettings * @see com.univocity.parsers.fixed.FixedWidthParserSettings */ public abstract class CommonParserSettings extends CommonSettings { protected Boolean headerExtractionEnabled = null; private Processor processor; private boolean columnReorderingEnabled = true; private int inputBufferSize = 1024 * 1024; private boolean readInputOnSeparateThread = Runtime.getRuntime().availableProcessors() > 1; private long numberOfRecordsToRead = -1L; private boolean lineSeparatorDetectionEnabled = false; private long numberOfRowsToSkip = 0L; private boolean commentCollectionEnabled = false; private boolean autoClosingEnabled = true; private boolean commentProcessingEnabled = true; private List inputAnalysisProcesses = new ArrayList(); /** * Indicates whether or not a separate thread will be used to read characters from the input while parsing (defaults true if the number of available * processors at runtime is greater than 1) *

When enabled, a reading thread (in {@code com.univocity.parsers.common.input.concurrent.ConcurrentCharInputReader}) * will be started and load characters from the input, while the parser is processing its input buffer. * This yields better performance, especially when reading from big input (greater than 100 mb) *

When disabled, the parsing process will briefly pause so the buffer can be replenished every time it is exhausted * (in {@link DefaultCharInputReader} it is not as bad or slow as it sounds, and can even be (slightly) more efficient if your input is small) * * @return true if the input should be read on a separate thread, false otherwise */ public boolean getReadInputOnSeparateThread() { return readInputOnSeparateThread; } /** * Defines whether or not a separate thread will be used to read characters from the input while parsing (defaults true if the number of available * processors at runtime is greater than 1) *

When enabled, a reading thread (in {@code com.univocity.parsers.common.input.concurrent.ConcurrentCharInputReader}) will be * started and load characters from the input, while the * parser is processing its input buffer. This yields better performance, especially when reading from big input (greater than 100 mb) *

When disabled, the parsing process will briefly pause so the buffer can be replenished every time it is exhausted (in {@link DefaultCharInputReader} * it is not as bad or slow as it sounds, and can even be (slightly) more efficient if your input is small) * * @param readInputOnSeparateThread the flag indicating whether or not the input should be read on a separate thread */ public void setReadInputOnSeparateThread(boolean readInputOnSeparateThread) { this.readInputOnSeparateThread = readInputOnSeparateThread; } /** * Indicates whether or not the first valid record parsed from the input should be considered as the row containing the names of each column * * @return true if the first valid record parsed from the input should be considered as the row containing the names of each column, false otherwise */ public boolean isHeaderExtractionEnabled() { return headerExtractionEnabled == null ? false : headerExtractionEnabled; } /** * Defines whether or not the first valid record parsed from the input should be considered as the row containing the names of each column * * @param headerExtractionEnabled a flag indicating whether the first valid record parsed from the input should be considered as the row containing the * names of each column */ public void setHeaderExtractionEnabled(boolean headerExtractionEnabled) { this.headerExtractionEnabled = headerExtractionEnabled; } /** * Returns the callback implementation of the interface {@link RowProcessor} which handles the lifecycle of the parsing process and processes each record * extracted from the input * * @return Returns the RowProcessor used by the parser to handle each record * * @see com.univocity.parsers.common.processor.ObjectRowProcessor * @see com.univocity.parsers.common.processor.ObjectRowListProcessor * @see com.univocity.parsers.common.processor.MasterDetailProcessor * @see com.univocity.parsers.common.processor.MasterDetailListProcessor * @see com.univocity.parsers.common.processor.BeanProcessor * @see com.univocity.parsers.common.processor.BeanListProcessor * @deprecated Use the {@link #getProcessor()} method as it allows format-specific processors to be built to work with different implementations of {@link Context}. * Implementations based on {@link RowProcessor} allow only parsers who provide a {@link ParsingContext} to be used. */ @Deprecated public RowProcessor getRowProcessor() { if (processor == null) { return NoopRowProcessor.instance; } return (RowProcessor) processor; } /** * Defines the callback implementation of the interface {@link RowProcessor} which handles the lifecycle of the parsing process and processes each record * extracted from the input * * @param processor the RowProcessor instance which should used by the parser to handle each record * * @see com.univocity.parsers.common.processor.ObjectRowProcessor * @see com.univocity.parsers.common.processor.ObjectRowListProcessor * @see com.univocity.parsers.common.processor.MasterDetailProcessor * @see com.univocity.parsers.common.processor.MasterDetailListProcessor * @see com.univocity.parsers.common.processor.BeanProcessor * @see com.univocity.parsers.common.processor.BeanListProcessor * @deprecated Use the {@link #setProcessor(Processor)} method as it allows format-specific processors to be built to work with different implementations of * {@link Context}. * Implementations based on {@link RowProcessor} allow only parsers who provide a {@link ParsingContext} to be used. */ @Deprecated public void setRowProcessor(RowProcessor processor) { this.processor = processor; } /** * Returns the callback implementation of the interface {@link Processor} which handles the lifecycle of the parsing process and processes each record * extracted from the input * * @param the context type supported by the parser implementation. * * @return Returns the {@link Processor} used by the parser to handle each record * * @see AbstractObjectProcessor * @see AbstractObjectListProcessor * @see AbstractMasterDetailProcessor * @see AbstractMasterDetailListProcessor * @see AbstractBeanProcessor * @see AbstractBeanListProcessor */ public Processor getProcessor() { if (processor == null) { return NoopProcessor.instance; } return (Processor) processor; } /** * Defines the callback implementation of the interface {@link Processor} which handles the lifecycle of the parsing process and processes each record * extracted from the input * * @param processor the {@link Processor} instance which should used by the parser to handle each record * * @see AbstractObjectProcessor * @see AbstractObjectListProcessor * @see AbstractMasterDetailProcessor * @see AbstractMasterDetailListProcessor * @see AbstractBeanProcessor * @see AbstractBeanListProcessor * @see AbstractColumnProcessor * @see AbstractColumnProcessor */ public void setProcessor(Processor processor) { this.processor = processor; } /** * An implementation of {@link CharInputReader} which loads the parser buffer in parallel or sequentially, as defined by the readInputOnSeparateThread * property * * @param whitespaceRangeStart starting range of characters considered to be whitespace. * * @return The input reader as chosen with the readInputOnSeparateThread property. */ protected CharInputReader newCharInputReader(int whitespaceRangeStart) { if (readInputOnSeparateThread) { if (lineSeparatorDetectionEnabled) { return new ConcurrentCharInputReader(getFormat().getNormalizedNewline(), this.getInputBufferSize(), 10, whitespaceRangeStart, autoClosingEnabled); } else { return new ConcurrentCharInputReader(getFormat().getLineSeparator(), getFormat().getNormalizedNewline(), this.getInputBufferSize(), 10, whitespaceRangeStart, autoClosingEnabled); } } else { if (lineSeparatorDetectionEnabled) { return new DefaultCharInputReader(getFormat().getNormalizedNewline(), this.getInputBufferSize(), whitespaceRangeStart, autoClosingEnabled); } else { return new DefaultCharInputReader(getFormat().getLineSeparator(), getFormat().getNormalizedNewline(), this.getInputBufferSize(), whitespaceRangeStart, autoClosingEnabled); } } } /** * The number of valid records to be parsed before the process is stopped. A negative value indicates there's no limit (defaults to -1). * * @return the number of records to read before stopping the parsing process. */ public long getNumberOfRecordsToRead() { return numberOfRecordsToRead; } /** * Defines the number of valid records to be parsed before the process is stopped. A negative value indicates there's no limit (defaults to -1). * * @param numberOfRecordsToRead the number of records to read before stopping the parsing process. */ public void setNumberOfRecordsToRead(long numberOfRecordsToRead) { this.numberOfRecordsToRead = numberOfRecordsToRead; } /** * Indicates whether fields selected using the field selection methods (defined by the parent class {@link CommonSettings}) should be reordered (defaults to * true). *

When disabled, each parsed record will contain values for all columns, in the order they occur in the input. Fields which were not selected will not * be parsed but and the record will contain empty values. *

When enabled, each parsed record will contain values only for the selected columns. The values will be ordered according to the selection. * * @return true if the selected fields should be reordered and returned by the parser, false otherwise */ public boolean isColumnReorderingEnabled() { return !preventReordering() && columnReorderingEnabled; } /** * Returns the set of selected fields, if any * * @return the set of selected fields. Null if no field was selected/excluded */ @Override FieldSet getFieldSet() { return preventReordering() ? null : super.getFieldSet(); } /** * Returns the FieldSelector object, which handles selected fields. * * @return the FieldSelector object, which handles selected fields. Null if no field was selected/excluded */ @Override FieldSelector getFieldSelector() { return preventReordering() ? null : super.getFieldSelector(); } /** * Defines whether fields selected using the field selection methods (defined by the parent class {@link CommonSettings}) should be reordered (defaults to * true). *

When disabled, each parsed record will contain values for all columns, in the order they occur in the input. Fields which were not selected will not * be parsed but the record will contain empty values. *

When enabled, each parsed record will contain values only for the selected columns. The values will be ordered according to the selection. * * @param columnReorderingEnabled the flag indicating whether or not selected fields should be reordered and returned by the parser */ public void setColumnReorderingEnabled(boolean columnReorderingEnabled) { if (columnReorderingEnabled && preventReordering()) { throw new IllegalArgumentException("Cannot reorder columns when using a row processor that manipulates nested rows."); } this.columnReorderingEnabled = columnReorderingEnabled; } /** * Informs the number of characters held by the parser's buffer when processing the input (defaults to 1024*1024 characters). * * @return the number of characters held by the parser's buffer when processing the input */ public int getInputBufferSize() { return inputBufferSize; } /** * Defines the number of characters held by the parser's buffer when processing the input (defaults to 1024*1024 characters). * * @param inputBufferSize the new input buffer size (in number of characters) */ public void setInputBufferSize(int inputBufferSize) { this.inputBufferSize = inputBufferSize; } /** * Returns an instance of CharAppender with the configured limit of maximum characters per column and the default value used to represent a null value (when * the String parsed from the input is empty) * * @return an instance of CharAppender with the configured limit of maximum characters per column and the default value used to represent a null value (when * the String parsed from the input is empty) */ protected CharAppender newCharAppender() { int chars = getMaxCharsPerColumn(); if (chars != -1) { return new DefaultCharAppender(chars, getNullValue(), getWhitespaceRangeStart()); } else { return new ExpandingCharAppender(getNullValue(), getWhitespaceRangeStart()); } } /** * Indicates whether the parser should detect the line separator automatically. * * @return {@code true} if the first line of the input should be used to search for common line separator sequences (the matching sequence will be used as * the line separator for parsing). Otherwise {@code false}. */ public final boolean isLineSeparatorDetectionEnabled() { return lineSeparatorDetectionEnabled; } /** * Defines whether the parser should detect the line separator automatically. * * @param lineSeparatorDetectionEnabled a flag indicating whether the first line of the input should be used to search for common line separator sequences * (the matching sequence will be used as the line separator for parsing). */ public final void setLineSeparatorDetectionEnabled(boolean lineSeparatorDetectionEnabled) { this.lineSeparatorDetectionEnabled = lineSeparatorDetectionEnabled; } /** * Returns the number of rows to skip from the input before the parser can begin to execute. * * @return number of rows to skip before parsing */ public final long getNumberOfRowsToSkip() { return numberOfRowsToSkip; } /** * Defines a number of rows to skip from the input before the parser can begin to execute. * * @param numberOfRowsToSkip number of rows to skip before parsing */ public final void setNumberOfRowsToSkip(long numberOfRowsToSkip) { if (numberOfRowsToSkip < 0) { throw new IllegalArgumentException("Number of rows to skip from the input must be 0 or greater"); } this.numberOfRowsToSkip = numberOfRowsToSkip; } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); out.put("Header extraction enabled", headerExtractionEnabled); out.put("Processor", processor == null ? "none" : processor.getClass().getName()); out.put("Column reordering enabled", columnReorderingEnabled); out.put("Input buffer size", inputBufferSize); out.put("Input reading on separate thread", readInputOnSeparateThread); out.put("Number of records to read", numberOfRecordsToRead == -1 ? "all" : numberOfRecordsToRead); out.put("Line separator detection enabled", lineSeparatorDetectionEnabled); out.put("Auto-closing enabled", autoClosingEnabled); } private boolean preventReordering() { if (processor instanceof ColumnOrderDependent) { return ((ColumnOrderDependent) processor).preventColumnReordering(); } return false; } /** * Indicates that comments found in the input must be collected (disabled by default). If enabled, comment lines will be * stored by the parser and made available via {@code AbstractParser.getContext().comments()} and {@code AbstractParser.getContext().lastComment()} * * @return a flag indicating whether or not to enable collection of comments. */ public boolean isCommentCollectionEnabled() { return commentCollectionEnabled; } /** * Enables collection of comments found in the input (disabled by default). If enabled, comment lines will be * stored by the parser and made available via {@code AbstractParser.getContext().comments()} and {@code AbstractParser.getContext().lastComment()} * * @param commentCollectionEnabled flag indicating whether or not to enable collection of comments. */ public void setCommentCollectionEnabled(boolean commentCollectionEnabled) { this.commentCollectionEnabled = commentCollectionEnabled; } @Override final void runAutomaticConfiguration() { Class beanClass = null; if (processor instanceof AbstractBeanProcessor) { beanClass = ((AbstractBeanProcessor) processor).getBeanClass(); } else if (processor instanceof AbstractMultiBeanProcessor) { Class[] classes = ((AbstractMultiBeanProcessor) processor).getBeanClasses(); if (classes.length > 0) { beanClass = classes[0]; } } if (beanClass != null) { configureFromAnnotations(beanClass); } } /** * Configures the parser based on the annotations provided in a given class * * @param beanClass the classes whose annotations will be processed to derive configurations for parsing */ protected synchronized void configureFromAnnotations(Class beanClass) { if (!deriveHeadersFrom(beanClass)) { return; } Headers headerAnnotation = AnnotationHelper.findHeadersAnnotation(beanClass); String[] headersFromBean = ArgumentUtils.EMPTY_STRING_ARRAY; boolean allFieldsIndexBased = AnnotationHelper.allFieldsIndexBasedForParsing(beanClass); boolean extractHeaders = !allFieldsIndexBased; if (headerAnnotation != null) { if (headerAnnotation.sequence().length > 0) { headersFromBean = headerAnnotation.sequence(); } extractHeaders = headerAnnotation.extract(); } if (headerExtractionEnabled == null) { setHeaderExtractionEnabled(extractHeaders); } if (getHeaders() == null && headersFromBean.length > 0 && !headerExtractionEnabled) { setHeadersDerivedFromClass(beanClass, headersFromBean); } if (getFieldSet() == null) { if (allFieldsIndexBased) { selectIndexes(AnnotationHelper.getSelectedIndexes(beanClass, MethodFilter.ONLY_SETTERS)); } else if (headersFromBean.length > 0 && AnnotationHelper.allFieldsNameBasedForParsing(beanClass)) { selectFields(headersFromBean); } } } @Override protected CommonParserSettings clone(boolean clearInputSpecificSettings) { return (CommonParserSettings) super.clone(clearInputSpecificSettings); } @Override protected CommonParserSettings clone() { return (CommonParserSettings) super.clone(); } @Override protected void clearInputSpecificSettings() { super.clearInputSpecificSettings(); processor = null; numberOfRecordsToRead = -1L; numberOfRowsToSkip = 0L; } /** * Indicates whether automatic closing of the input (reader, stream, etc) * is enabled. If {@code true}, the parser will always close the input automatically * when all records have been parsed or when an error occurs. * * Defaults to {@code true} * * @return flag indicating whether automatic input closing is enabled. */ public boolean isAutoClosingEnabled() { return autoClosingEnabled; } /** * Configures whether the parser should always close the input (reader, stream, etc) automatically * when all records have been parsed or when an error occurs. * * Defaults to {@code true} * * @param autoClosingEnabled flag determining whether automatic input closing should be enabled. */ public void setAutoClosingEnabled(boolean autoClosingEnabled) { this.autoClosingEnabled = autoClosingEnabled; } /** * Indicates whether code will check for comment line in the data file * is enabled. If {@code true}, the parser will always check for the comment line * default value for comment check is # * Defaults to {@code true} * * @return flag indicating whether parser will check for the comment line * If disabled/false then parser wont treat any line as comment line including default(#) * this condition will supersede the comment character(#) */ public boolean isCommentProcessingEnabled() { return commentProcessingEnabled; } /** * Configures whether the parser will check for the comment line in the file * Defaults to {@code true} * * @param commentProcessingEnabled flag determining whether comment line check should be performed * If disabled/false then parser wont treat any line as comment line including default(#) * this condition will supersede the comment character(#) */ public void setCommentProcessingEnabled(boolean commentProcessingEnabled) { this.commentProcessingEnabled = commentProcessingEnabled; } /** * Provides a custom {@link InputAnalysisProcess} to analyze the input buffer and potentially discover configuration options such as * column separators is CSV, data formats, etc. The process will be execute only once. * * @param inputAnalysisProcess a custom process to analyze the contents of the first input buffer loaded when the parsing starts. */ public void addInputAnalysisProcess(InputAnalysisProcess inputAnalysisProcess) { if (inputAnalysisProcess == null) { return; } if (this.inputAnalysisProcesses == null) { inputAnalysisProcesses = new ArrayList(); } inputAnalysisProcesses.add(inputAnalysisProcess); } /** * Returns the sequence of {@link InputAnalysisProcess} to be used for analyzing the input buffer and potentially discover configuration options such as * column separators is CSV, data formats, etc. Each process will be execute only once. * * @return the list of custom processes to analyze the contents of the first input buffer loaded when the parsing starts. */ public List getInputAnalysisProcesses() { return inputAnalysisProcesses; } }jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/CommonSettings.java000066400000000000000000001011601475274123300333100ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.processor.*; import java.util.*; import java.util.Map.*; /** * This is the parent class for all configuration classes used by parsers ({@link AbstractParser}) and writers ({@link AbstractWriter}) * *

By default, all parsers and writers work with, at least, the following configuration options: * *

    *
  • format (each file format provides its default): the input/output format of a given file
  • *
  • nullValue (defaults to null): *

    when reading, if the parser does not read any character from the input, the nullValue is used instead of an empty string *

    when writing, if the writer has a null object to write to the output, the nullValue is used instead of an empty string

  • *
  • maxCharsPerColumn (defaults to 4096): The maximum number of characters allowed for any given value being written/read. *

    You need this to avoid OutOfMemoryErrors in case a file does not have a valid format. In such cases the parser might just keep reading from the input * until its end or the memory is exhausted. This sets a limit which avoids unwanted JVM crashes.

  • *
  • maxColumns (defaults to 512): a hard limit on how many columns a record can have. * You need this to avoid OutOfMemory errors in case of inputs that might be inconsistent with the format you are dealing with
  • *
  • skipEmptyLines (defaults to true): *

    when reading, if the parser reads a line that is empty, it will be skipped. *

    when writing, if the writer receives an empty or null row to write to the output, it will be ignored

  • *
  • ignoreTrailingWhitespaces (defaults to true): removes trailing whitespaces from values being read/written
  • *
  • ignoreLeadingWhitespaces (defaults to true): removes leading whitespaces from values being read/written
  • *
  • headers (defaults to null): the field names in the input/output, in the sequence they occur. *

    when reading, the given header names will be used to refer to each column irrespective of whether or not the input contains a header row *

    when writing, the given header names will be used to refer to each column and can be used for writing the header row

  • *
  • field selection (defaults to none): a selection of fields for reading and writing. Fields can be selected by their name or their position. *

    when reading, the selected fields only will be parsed and the remaining fields will be discarded. *

    when writing, the selected fields only will be written and the remaining fields will be discarded

  • *
* * @param the format supported by this settings class. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.CommonParserSettings * @see com.univocity.parsers.common.CommonWriterSettings * @see com.univocity.parsers.csv.CsvParserSettings * @see com.univocity.parsers.csv.CsvWriterSettings * @see com.univocity.parsers.fixed.FixedWidthParserSettings * @see com.univocity.parsers.fixed.FixedWidthWriterSettings */ public abstract class CommonSettings implements Cloneable { private F format; private String nullValue = null; private int maxCharsPerColumn = 4096; private int maxColumns = 512; private boolean skipEmptyLines = true; private boolean ignoreTrailingWhitespaces = true; private boolean ignoreLeadingWhitespaces = true; private FieldSelector fieldSelector = null; private boolean autoConfigurationEnabled = true; private ProcessorErrorHandler errorHandler; private int errorContentLength = -1; private boolean skipBitsAsWhitespace = true; private String[] headers; Class headerSourceClass; /** * Creates a new instance of this settings object using the default format specified by the concrete class that inherits from {@code CommonSettings} */ public CommonSettings() { setFormat(createDefaultFormat()); } /** * Returns the String representation of a null value (defaults to null) *

When reading, if the parser does not read any character from the input, the nullValue is used instead of an empty string *

When writing, if the writer has a null object to write to the output, the nullValue is used instead of an empty string * * @return the String representation of a null value */ public String getNullValue() { return nullValue; } /** * Sets the String representation of a null value (defaults to null) *

When reading, if the parser does not read any character from the input, the nullValue is used instead of an empty string *

When writing, if the writer has a null object to write to the output, the nullValue is used instead of an empty string * * @param emptyValue the String representation of a null value */ public void setNullValue(String emptyValue) { this.nullValue = emptyValue; } /** * The maximum number of characters allowed for any given value being written/read. Used to avoid OutOfMemoryErrors (defaults to 4096). * *

If set to {@code -1}, then the internal internal array will expand automatically, up to the limit allowed by the JVM

* * @return The maximum number of characters allowed for any given value being written/read */ public int getMaxCharsPerColumn() { return maxCharsPerColumn; } /** * Defines the maximum number of characters allowed for any given value being written/read. Used to avoid OutOfMemoryErrors (defaults to 4096). * *

To enable auto-expansion of the internal array, set this property to -1

* * @param maxCharsPerColumn The maximum number of characters allowed for any given value being written/read */ public void setMaxCharsPerColumn(int maxCharsPerColumn) { this.maxCharsPerColumn = maxCharsPerColumn; } /** * Returns whether or not empty lines should be ignored (defaults to true) *

when reading, if the parser reads a line that is empty, it will be skipped. *

when writing, if the writer receives an empty or null row to write to the output, it will be ignored * * @return true if empty lines are configured to be ignored, false otherwise */ public boolean getSkipEmptyLines() { return skipEmptyLines; } /** * Defines whether or not empty lines should be ignored (defaults to true) *

when reading, if the parser reads a line that is empty, it will be skipped. *

when writing, if the writer receives an empty or null row to write to the output, it will be ignored * * @param skipEmptyLines true if empty lines should be ignored, false otherwise */ public void setSkipEmptyLines(boolean skipEmptyLines) { this.skipEmptyLines = skipEmptyLines; } /** * Returns whether or not trailing whitespaces from values being read/written should be skipped (defaults to true) * * @return true if trailing whitespaces from values being read/written should be skipped, false otherwise */ public boolean getIgnoreTrailingWhitespaces() { return ignoreTrailingWhitespaces; } /** * Defines whether or not trailing whitespaces from values being read/written should be skipped (defaults to true) * * @param ignoreTrailingWhitespaces true if trailing whitespaces from values being read/written should be skipped, false otherwise */ public void setIgnoreTrailingWhitespaces(boolean ignoreTrailingWhitespaces) { this.ignoreTrailingWhitespaces = ignoreTrailingWhitespaces; } /** * Returns whether or not leading whitespaces from values being read/written should be skipped (defaults to true) * * @return true if leading whitespaces from values being read/written should be skipped, false otherwise */ public boolean getIgnoreLeadingWhitespaces() { return ignoreLeadingWhitespaces; } /** * Defines whether or not leading whitespaces from values being read/written should be skipped (defaults to true) * * @param ignoreLeadingWhitespaces true if leading whitespaces from values being read/written should be skipped, false otherwise */ public void setIgnoreLeadingWhitespaces(boolean ignoreLeadingWhitespaces) { this.ignoreLeadingWhitespaces = ignoreLeadingWhitespaces; } /** * Defines the field names in the input/output, in the sequence they occur (defaults to null). *

when reading, the given header names will be used to refer to each column irrespective of whether or not the input contains a header row *

when writing, the given header names will be used to refer to each column and can be used for writing the header row * * @param headers the field name sequence associated with each column in the input/output. */ public void setHeaders(String... headers) { if (headers == null || headers.length == 0) { this.headers = null; } else { this.headers = headers; } } /** * Defines the field names in the input/output derived from a given class with {@link Parsed} annotated attributes/methods. *

when reading, the given header names will be used to refer to each column irrespective of whether or not the input contains a header row *

when writing, the given header names will be used to refer to each column and can be used for writing the header row * * @param headerSourceClass the class from which the headers have been derived. * @param headers the field name sequence associated with each column in the input/output. */ void setHeadersDerivedFromClass(Class headerSourceClass, String... headers) { this.headerSourceClass = headerSourceClass; setHeaders(headers); } /** * Indicates whether headers should be derived from a given class. * * @param beanClass the class to derive headers from * * @return {@code true} if the headers used for parsing/writing should be derived from the given class; otherwise {@code false} */ boolean deriveHeadersFrom(Class beanClass) { if (headerSourceClass != null) { if (headerSourceClass != beanClass) { setHeaders(null); } else { return false; } } return true; } /** * Returns the field names in the input/output, in the sequence they occur (defaults to null). *

when reading, the given header names will be used to refer to each column irrespective of whether or not the input contains a header row *

when writing, the given header names will be used to refer to each column and can be used for writing the header row * * @return the field name sequence associated with each column in the input/output. */ public String[] getHeaders() { return this.headers; } /** * Returns the hard limit of how many columns a record can have (defaults to 512). * You need this to avoid OutOfMemory errors in case of inputs that might be inconsistent with the format you are dealing with . * * @return The maximum number of columns a record can have. */ public int getMaxColumns() { return maxColumns; } /** * Defines a hard limit of how many columns a record can have (defaults to 512). * You need this to avoid OutOfMemory errors in case of inputs that might be inconsistent with the format you are dealing with. * * @param maxColumns The maximum number of columns a record can have. */ public void setMaxColumns(int maxColumns) { this.maxColumns = maxColumns; } /** * The format of the file to be parsed/written (returns the format's defaults). * * @return The format of the file to be parsed/written */ public F getFormat() { return format; } /** * Defines the format of the file to be parsed/written (returns the format's defaults). * * @param format The format of the file to be parsed/written */ public void setFormat(F format) { if (format == null) { throw new IllegalArgumentException("Format cannot be null"); } this.format = format; } /** * Selects a sequence of fields for reading/writing by their names. * *

When reading, only the values of the selected columns will be parsed, and the content of the other columns ignored. * The resulting rows will be returned with the selected columns only, in the order specified. If you want to * obtain the original row format, with all columns included and nulls in the fields that have not been selected, * set {@link CommonParserSettings#setColumnReorderingEnabled(boolean)} with {@code false}.

* *

When writing, the sequence provided represents the expected format of the input rows. For example, * headers can be "H1,H2,H3", but the input data is coming with values for two columns and in a different order, * such as "V_H3, V_H1". Selecting fields "H3" and "H1" will allow the writer to write values in the expected * locations. Using the given example, the output row will be generated as: "V_H1,null,V_H3"

* * @param fieldNames The field names to read/write * * @return the (modifiable) set of selected fields */ public FieldSet selectFields(String... fieldNames) { return setFieldSet(new FieldNameSelector(), fieldNames); } /** * Selects fields which will not be read/written, by their names * *

When reading, only the values of the selected columns will be parsed, and the content of the other columns ignored. * The resulting rows will be returned with the selected columns only, in the order specified. If you want to * obtain the original row format, with all columns included and nulls in the fields that have not been selected, * set {@link CommonParserSettings#setColumnReorderingEnabled(boolean)} with {@code false}.

* *

When writing, the sequence of non-excluded fields represents the expected format of the input rows. For example, * headers can be "H1,H2,H3", but the input data is coming with values for two columns and in a different order, * such as "V_H3, V_H1". Selecting fields "H3" and "H1" will allow the writer to write values in the expected * locations. Using the given example, the output row will be generated as: "V_H1,null,V_H3"

* * @param fieldNames The field names to exclude from the parsing/writing process * * @return the (modifiable) set of ignored fields */ public FieldSet excludeFields(String... fieldNames) { return setFieldSet(new ExcludeFieldNameSelector(), fieldNames); } /** * Selects a sequence of fields for reading/writing by their positions. * *

When reading, only the values of the selected columns will be parsed, and the content of the other columns ignored. * The resulting rows will be returned with the selected columns only, in the order specified. If you want to * obtain the original row format, with all columns included and nulls in the fields that have not been selected, * set {@link CommonParserSettings#setColumnReorderingEnabled(boolean)} with {@code false}.

* *

When writing, the sequence provided represents the expected format of the input rows. For example, * headers can be "H1,H2,H3", but the input data is coming with values for two columns and in a different order, * such as "V_H3, V_H1". Selecting indexes "2" and "0" will allow the writer to write values in the expected * locations. Using the given example, the output row will be generated as: "V_H1,null,V_H3"

* * @param fieldIndexes The indexes to read/write * * @return the (modifiable) set of selected fields */ public FieldSet selectIndexes(Integer... fieldIndexes) { return setFieldSet(new FieldIndexSelector(), fieldIndexes); } /** * Selects columns which will not be read/written, by their positions * *

When reading, only the values of the selected columns will be parsed, and the content of the other columns ignored. * The resulting rows will be returned with the selected columns only, in the order specified. If you want to * obtain the original row format, with all columns included and nulls in the fields that have not been selected, * set {@link CommonParserSettings#setColumnReorderingEnabled(boolean)} with {@code false}.

* *

When writing, the sequence of non-excluded fields represents the expected format of the input rows. For example, * headers can be "H1,H2,H3", but the input data is coming with values for two columns and in a different order, * such as "V_H3, V_H1". Selecting fields by index, such as "2" and "0" will allow the writer to write values in the expected * locations. Using the given example, the output row will be generated as: "V_H1,null,V_H3"

* * @param fieldIndexes indexes of columns to exclude from the parsing/writing process * * @return the (modifiable) set of ignored fields */ public FieldSet excludeIndexes(Integer... fieldIndexes) { return setFieldSet(new ExcludeFieldIndexSelector(), fieldIndexes); } /** * Selects a sequence of fields for reading/writing by their names * * *

When reading, only the values of the selected columns will be parsed, and the content of the other columns ignored. * The resulting rows will be returned with the selected columns only, in the order specified. If you want to * obtain the original row format, with all columns included and nulls in the fields that have not been selected, * set {@link CommonParserSettings#setColumnReorderingEnabled(boolean)} with {@code false}.

* *

When writing, the sequence provided represents the expected format of the input rows. For example, * headers can be "H1,H2,H3", but the input data is coming with values for two columns and in a different order, * such as "V_H3, V_H1". Selecting fields "H3" and "H1" will allow the writer to write values in the expected * locations. Using the given example, the output row will be generated as: "V_H1,null,V_H3"

* * @param columns The columns to read/write * * @return the (modifiable) set of selected fields */ @SuppressWarnings("rawtypes") public FieldSet selectFields(Enum... columns) { return setFieldSet(new FieldEnumSelector(), columns); } /** * Selects columns which will not be read/written, by their names * *

When reading, only the values of the selected columns will be parsed, and the content of the other columns ignored. * The resulting rows will be returned with the selected columns only, in the order specified. If you want to * obtain the original row format, with all columns included and nulls in the fields that have not been selected, * set {@link CommonParserSettings#setColumnReorderingEnabled(boolean)} with {@code false}.

* *

When writing, the sequence of non-excluded fields represents the expected format of the input rows. For example, * headers can be "H1,H2,H3", but the input data is coming with values for two columns and in a different order, * such as "V_H3, V_H1". Selecting fields "H3" and "H1" will allow the writer to write values in the expected * locations. Using the given example, the output row will be generated as: "V_H1,null,V_H3"

* * @param columns The columns to exclude from the parsing/writing process * * @return the (modifiable) set of ignored fields */ @SuppressWarnings("rawtypes") public FieldSet excludeFields(Enum... columns) { return setFieldSet(new ExcludeFieldEnumSelector(), columns); } /** * Replaces the current field selection * * @param fieldSet the new set of selected fields * @param values the values to include to the selection * * @return the set of selected fields given in as a parameter. */ private FieldSet setFieldSet(FieldSet fieldSet, T... values) { this.fieldSelector = (FieldSelector) fieldSet; fieldSet.add(values); return fieldSet; } /** * Returns the set of selected fields, if any * * @return the set of selected fields. Null if no field was selected/excluded */ FieldSet getFieldSet() { return (FieldSet) fieldSelector; } /** * Returns the FieldSelector object, which handles selected fields. * * @return the FieldSelector object, which handles selected fields. Null if no field was selected/excluded */ FieldSelector getFieldSelector() { return this.fieldSelector; } /** * Indicates whether this settings object can automatically derive configuration options. This is used, for example, to define the headers when the user * provides a {@link BeanWriterProcessor} where the bean class contains a {@link Headers} annotation, or to enable header extraction when the bean class of a * {@link BeanProcessor} has attributes mapping to header names. * *

Defaults to {@code true}

* * @return {@code true} if the automatic configuration feature is enabled, false otherwise */ public final boolean isAutoConfigurationEnabled() { return autoConfigurationEnabled; } /** * Indicates whether this settings object can automatically derive configuration options. This is used, for example, to define the headers when the user * provides a {@link BeanWriterProcessor} where the bean class contains a {@link Headers} annotation, or to enable header extraction when the bean class of a * {@link BeanProcessor} has attributes mapping to header names. * * @param autoConfigurationEnabled a flag to turn the automatic configuration feature on/off. */ public final void setAutoConfigurationEnabled(boolean autoConfigurationEnabled) { this.autoConfigurationEnabled = autoConfigurationEnabled; } /** * Returns the custom error handler to be used to capture and handle errors that might happen while processing records with a {@link RowProcessor} * or a {@link RowWriterProcessor} (i.e. non-fatal {@link DataProcessingException}s). * *

The parsing/writing process won't stop (unless the error handler rethrows the {@link DataProcessingException} or manually stops the process).

* * @return the callback error handler with custom code to manage occurrences of {@link DataProcessingException}. * * @deprecated Use the {@link #getProcessorErrorHandler()} method as it allows format-specific error handlers to be built to work with different implementations of {@link Context}. * Implementations based on {@link RowProcessorErrorHandler} allow only parsers who provide a {@link ParsingContext} to be used. */ @Deprecated public RowProcessorErrorHandler getRowProcessorErrorHandler() { return errorHandler == null ? NoopRowProcessorErrorHandler.instance : (RowProcessorErrorHandler) errorHandler; } /** * Defines a custom error handler to capture and handle errors that might happen while processing records with a {@link RowProcessor} * or a {@link RowWriterProcessor} (i.e. non-fatal {@link DataProcessingException}s). * *

The parsing parsing/writing won't stop (unless the error handler rethrows the {@link DataProcessingException} or manually stops the process).

* * @param rowProcessorErrorHandler the callback error handler with custom code to manage occurrences of {@link DataProcessingException}. * * @deprecated Use the {@link #setProcessorErrorHandler(ProcessorErrorHandler)} method as it allows format-specific error handlers to be built to work with different implementations of {@link Context}. * Implementations based on {@link RowProcessorErrorHandler} allow only parsers who provide a {@link ParsingContext} to be used. */ @Deprecated public void setRowProcessorErrorHandler(RowProcessorErrorHandler rowProcessorErrorHandler) { this.errorHandler = rowProcessorErrorHandler; } /** * Returns the custom error handler to be used to capture and handle errors that might happen while processing records with a {@link com.univocity.parsers.common.processor.core.Processor} * or a {@link RowWriterProcessor} (i.e. non-fatal {@link DataProcessingException}s). * *

The parsing/writing process won't stop (unless the error handler rethrows the {@link DataProcessingException} or manually stops the process).

* * @param the {@code Context} type provided by the parser implementation. * * @return the callback error handler with custom code to manage occurrences of {@link DataProcessingException}. */ public ProcessorErrorHandler getProcessorErrorHandler() { return errorHandler == null ? NoopProcessorErrorHandler.instance : (ProcessorErrorHandler) errorHandler; } /** * Defines a custom error handler to capture and handle errors that might happen while processing records with a {@link com.univocity.parsers.common.processor.core.Processor} * or a {@link RowWriterProcessor} (i.e. non-fatal {@link DataProcessingException}s). * *

The parsing parsing/writing won't stop (unless the error handler rethrows the {@link DataProcessingException} or manually stops the process).

* * @param processorErrorHandler the callback error handler with custom code to manage occurrences of {@link DataProcessingException}. */ public void setProcessorErrorHandler(ProcessorErrorHandler processorErrorHandler) { this.errorHandler = processorErrorHandler; } /** * Returns a flag indicating whether or not a {@link ProcessorErrorHandler} has been defined through the use of method {@link #setProcessorErrorHandler(ProcessorErrorHandler)} * * @return {@code true} if the parser/writer is configured to use a {@link ProcessorErrorHandler} */ public boolean isProcessorErrorHandlerDefined() { return errorHandler != null; } /** * Extending classes must implement this method to return the default format settings for their parser/writer * * @return Default format configuration for the given parser/writer settings. */ protected abstract F createDefaultFormat(); final void autoConfigure() { if (!this.autoConfigurationEnabled) { return; } runAutomaticConfiguration(); } /** * Configures the parser/writer to trim or keep leading and trailing whitespaces around values * This has the same effect as invoking both {@link #setIgnoreLeadingWhitespaces(boolean)} and {@link #setIgnoreTrailingWhitespaces(boolean)} * with the same value. * * @param trim a flag indicating whether the whitespaces should remove whitespaces around values parsed/written. */ public final void trimValues(boolean trim) { this.setIgnoreLeadingWhitespaces(trim); this.setIgnoreTrailingWhitespaces(trim); } /** * Configures the parser/writer to limit the length of displayed contents being parsed/written in the exception message when an error occurs * *

If set to {@code 0}, then no exceptions will include the content being manipulated in their attributes, * and the {@code ""} string will appear in error messages as the parsed/written content.

* *

defaults to {@code -1} (no limit)

. * * @return the maximum length of contents displayed in exception messages in case of errors while parsing/writing. */ public int getErrorContentLength() { return errorContentLength; } /** * Configures the parser/writer to limit the length of displayed contents being parsed/written in the exception message when an error occurs. * *

If set to {@code 0}, then no exceptions will include the content being manipulated in their attributes, * and the {@code ""} string will appear in error messages as the parsed/written content.

* *

defaults to {@code -1} (no limit)

. * * @param errorContentLength maximum length of contents displayed in exception messages in case of errors while parsing/writing. */ public void setErrorContentLength(int errorContentLength) { this.errorContentLength = errorContentLength; } void runAutomaticConfiguration() { } /** * Returns a flag indicating whether the parser/writer should skip bit values as whitespace. * * By default the parser/writer * removes control characters and considers a whitespace any character where {@code character <= ' '} evaluates to * {@code true}. This includes bit values, i.e. {@code 0} (the \0 character) and {@code 1} which might * be produced by database dumps. Disabling this flag will prevent the parser/writer from discarding these characters * when {@link #getIgnoreLeadingWhitespaces()} or {@link #getIgnoreTrailingWhitespaces()} evaluate to {@code true}. * *

defaults to {@code true}

* * @return a flag indicating whether bit values (0 or 1) should be considered whitespace. */ public final boolean getSkipBitsAsWhitespace() { return skipBitsAsWhitespace; } /** * Configures the parser to skip bit values as whitespace. * * By default the parser/writer removes control characters and considers a whitespace any character where {@code character <= ' '} evaluates to * {@code true}. This includes bit values, i.e. {@code 0} (the \0 character) and {@code 1} which might * be produced by database dumps. Disabling this flag will prevent the parser/writer from discarding these characters * when {@link #getIgnoreLeadingWhitespaces()} or {@link #getIgnoreTrailingWhitespaces()} evaluate to {@code true}. * *

defaults to {@code true}

* * @param skipBitsAsWhitespace a flag indicating whether bit values (0 or 1) should be considered whitespace. */ public final void setSkipBitsAsWhitespace(boolean skipBitsAsWhitespace) { this.skipBitsAsWhitespace = skipBitsAsWhitespace; } /** * Returns the starting decimal range for {@code characters <= ' '} that should be skipped as whitespace, as * determined by {@link #getSkipBitsAsWhitespace()} * * @return the starting range after which characters will be considered whitespace */ protected final int getWhitespaceRangeStart() { return skipBitsAsWhitespace ? -1 : 1; } @Override public final String toString() { StringBuilder out = new StringBuilder(); out.append(getClass().getSimpleName()).append(':'); TreeMap config = new TreeMap(); addConfiguration(config); for (Entry e : config.entrySet()) { out.append("\n\t"); out.append(e.getKey()).append('=').append(e.getValue()); } out.append("Format configuration:\n\t").append(getFormat().toString()); return out.toString(); } protected void addConfiguration(Map out) { out.put("Null value", nullValue); out.put("Maximum number of characters per column", maxCharsPerColumn); out.put("Maximum number of columns", maxColumns); out.put("Skip empty lines", skipEmptyLines); out.put("Ignore trailing whitespaces", ignoreTrailingWhitespaces); out.put("Ignore leading whitespaces", ignoreLeadingWhitespaces); out.put("Selected fields", fieldSelector == null ? "none" : fieldSelector.describe()); out.put("Headers", Arrays.toString(headers)); out.put("Auto configuration enabled", autoConfigurationEnabled); out.put("RowProcessor error handler", errorHandler); out.put("Length of content displayed on error", errorContentLength); out.put("Restricting data in exceptions", errorContentLength == 0); out.put("Skip bits as whitespace", skipBitsAsWhitespace); } /** * Clones this configuration object to reuse user-provided settings. * * Properties that are specific to a given input (such as header names and selection of fields) can be reset to their defaults * if the {@code clearInputSpecificSettings} flag is set to {@code true} * * @param clearInputSpecificSettings flag indicating whether to clear settings that are likely to be associated with a given input. * * @return a copy of the configurations applied to the current instance. */ protected CommonSettings clone(boolean clearInputSpecificSettings) { try { CommonSettings out = (CommonSettings) super.clone(); if (out.format != null) { out.format = out.format.clone(); } if (clearInputSpecificSettings) { out.clearInputSpecificSettings(); } return out; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } /** * Clones this configuration object. Use alternative {@link #clone(boolean)} method to reset properties that are * specific to a given input, such as header names and selection of fields. * * @return a copy of all configurations applied to the current instance. */ @Override protected CommonSettings clone() { return clone(false); } /** * Clears settings that are likely to be specific to a given input. */ protected void clearInputSpecificSettings() { fieldSelector = null; headers = null; } } CommonWriterSettings.java000066400000000000000000000231341475274123300344320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.processor.*; import java.util.*; /** * This is the parent class for all configuration classes used by writers ({@link AbstractWriter}) * *

By default, all writers work with, at least, the following configuration options in addition to the ones provided by {@link CommonSettings}: * *

    *
  • rowWriterProcessor: a implementation of the interface {@link RowWriterProcessor} which processes input objects into a manageable format for writing.
  • *
* * @param the format supported by this writer. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.processor.RowWriterProcessor * @see com.univocity.parsers.csv.CsvWriterSettings * @see com.univocity.parsers.fixed.FixedWidthWriterSettings */ public abstract class CommonWriterSettings extends CommonSettings { private RowWriterProcessor rowWriterProcessor; private Boolean headerWritingEnabled = null; private String emptyValue = ""; private boolean expandIncompleteRows = false; private boolean columnReorderingEnabled = false; /** * Returns the String representation of an empty value (defaults to null) * *

When writing, if the writer has an empty String to write to the output, the emptyValue is used instead of an empty string * * @return the String representation of an empty value */ public String getEmptyValue() { return emptyValue; } /** * Sets the String representation of an empty value (defaults to null) * *

If the writer has an empty String to write to the output, the emptyValue is used instead of an empty string * * @param emptyValue the String representation of an empty value */ public void setEmptyValue(String emptyValue) { this.emptyValue = emptyValue; } /** * Returns the implementation of the interface {@link RowWriterProcessor} which processes input objects into a manageable format for writing. * * @return the implementation of the interface {@link RowWriterProcessor} which processes input objects into a manageable format for writing. * * @see com.univocity.parsers.common.processor.ObjectRowWriterProcessor * @see com.univocity.parsers.common.processor.BeanWriterProcessor */ public RowWriterProcessor getRowWriterProcessor() { return rowWriterProcessor; } /** * Defines a processor for input objects that converts them into a manageable format for writing. * * @param rowWriterProcessor the implementation of the interface {@link RowWriterProcessor} which processes input objects into a manageable format for writing. * * @see com.univocity.parsers.common.processor.ObjectRowWriterProcessor * @see com.univocity.parsers.common.processor.BeanWriterProcessor */ public void setRowWriterProcessor(RowWriterProcessor rowWriterProcessor) { this.rowWriterProcessor = rowWriterProcessor; } /** * Returns a flag indicating whether automatic writing of headers is enabled. If enabled, and headers are defined (or derived automatically if {@link #isAutoConfigurationEnabled} evaluates to {@code true}), * the writer will invoke the {@link AbstractWriter#writeHeaders()} method automatically. In this case, attempting to explicitly write the headers will result in a {@link TextWritingException}. * *

Defaults to {@code false}

* * @return returns {@code true} if automatic header writing is enabled, otherwise false. */ public final boolean isHeaderWritingEnabled() { return headerWritingEnabled == null ? false : headerWritingEnabled; } /** * Enables automatic writing of headers when they are available. If enabled, and headers are defined (or derived automatically if {@link #isAutoConfigurationEnabled} evaluates to {@code true}), * the writer will invoke the {@link AbstractWriter#writeHeaders()} method automatically. In this case, attempting to explicitly write the headers will result in a {@link TextWritingException}. * *

Defaults to {@code false}

* * @param headerWritingEnabled a flag to enable or disable automatic header writing. */ public final void setHeaderWritingEnabled(boolean headerWritingEnabled) { this.headerWritingEnabled = headerWritingEnabled; } /** * Indicates whether the writer should expand records with less columns than the number of headers. For example, if * the writer is using "A,B,C" as the headers, and the user provides a row with "V1,V2", then {@code null} will be * introduced in column C, generating the output "V1,V2,null". * *

Defaults to {@code false}

* * @return a flag indicating whether records with less columns than the number of headers are to be expanded with nulls. */ public final boolean getExpandIncompleteRows() { return expandIncompleteRows; } /** * Defines whether the writer should expand records with less columns than the number of headers. * For example, if the writer is using "A,B,C" as the headers, and the user provides a row with "V1,V2", then {@code null} will be * introduced in column C, generating the output "V1,V2,null". * *

Defaults to {@code false}

* * @param expandIncompleteRows a flag indicating whether records with less columns than the number of headers are to be expanded with nulls. */ public final void setExpandIncompleteRows(boolean expandIncompleteRows) { this.expandIncompleteRows = expandIncompleteRows; } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); out.put("Empty value", emptyValue); out.put("Header writing enabled", headerWritingEnabled); out.put("Row processor", rowWriterProcessor == null ? "none" : rowWriterProcessor.getClass().getName()); } @Override final void runAutomaticConfiguration() { if (rowWriterProcessor instanceof BeanWriterProcessor) { Class beanClass = ((BeanWriterProcessor) rowWriterProcessor).getBeanClass(); configureFromAnnotations(beanClass); } } /** * Configures the writer based on the annotations provided in a given class * * @param beanClass the classes whose annotations will be processed to derive configurations for writing. */ protected void configureFromAnnotations(Class beanClass) { if(!deriveHeadersFrom(beanClass)){ return; } Headers headerAnnotation = AnnotationHelper.findHeadersAnnotation(beanClass); String[] headersFromBean = AnnotationHelper.deriveHeaderNamesFromFields(beanClass, MethodFilter.ONLY_GETTERS); boolean writeHeaders = false; if (headerAnnotation != null) { if (headerAnnotation.sequence().length > 0) { headersFromBean = headerAnnotation.sequence(); } writeHeaders = headerAnnotation.write(); } if (headerWritingEnabled == null) { headerWritingEnabled = writeHeaders; } if (getHeaders() == null && headersFromBean.length > 0) { setHeadersDerivedFromClass(beanClass, headersFromBean); } } @Override protected CommonWriterSettings clone(boolean clearInputSpecificSettings) { return (CommonWriterSettings) super.clone(clearInputSpecificSettings); } @Override protected CommonWriterSettings clone() { return (CommonWriterSettings) super.clone(); } @Override protected void clearInputSpecificSettings() { super.clearInputSpecificSettings(); rowWriterProcessor = null; } /** * Indicates whether fields selected using the field selection methods (defined by the parent class {@link CommonSettings}) should be reordered (defaults to false). *

When disabled, each written record will contain values for all columns, in the order they are sent to the writer. Fields which were not selected will not be written but and the record will contain empty values. *

When enabled, each written record will contain values only for the selected columns. The values will be ordered according to the selection. * * @return true if the selected fields should be reordered when writing with field selection enabled, false otherwise */ public boolean isColumnReorderingEnabled() { return columnReorderingEnabled; } /** * Defines whether fields selected using the field selection methods (defined by the parent class {@link CommonSettings}) should be reordered (defaults to false). *

When disabled, each written record will contain values for all columns, in the order they are sent to the writer. Fields which were not selected will not be written but and the record will contain empty values. *

When enabled, each written record will contain values only for the selected columns. The values will be ordered according to the selection. * * @param columnReorderingEnabled the flag indicating whether or not selected fields should be reordered and written by the writer */ public void setColumnReorderingEnabled(boolean columnReorderingEnabled) { this.columnReorderingEnabled = columnReorderingEnabled; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/Context.java000066400000000000000000000114211475274123300317630ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.record.*; /** * Basic context information used internally by instances of {@link com.univocity.parsers.common.processor.core.Processor} and {@link com.univocity.parsers.common.record.Record}. * * @author Univocity Software Pty Ltd - dev@univocity.com * @see DefaultContext * @see ParsingContext * @see DefaultParsingContext */ public interface Context { /** * Returns the file headers that identify each parsed record. * * @return the headers used to identify each record parsed from the input. */ String[] headers(); /** * Returns the sequence of headers that have been selected. If no selection has been made, all available headers * will be returned, producing the same output as a call to method {@link #headers()}. * * @return the sequence of selected headers, or all headers if no selection has been made. */ String[] selectedHeaders(); /** * Returns the indexes of each field extracted from the input when fields are selected. * *

The indexes are relative to their original position in the input. *

For example, if the input has the fields "A, B, C, D", and the selected fields are "A, D", then the extracted field indexes will return [0, 3] * *

If no fields were selected, then this method will return null. This means all fields are being parsed. * * @return The indexes of each selected field; null if no fields were selected. * * @see com.univocity.parsers.common.CommonSettings */ int[] extractedFieldIndexes(); /** * Indicates whether selected fields are being reordered. * *

If columns are reordered, each parsed record will contain values only for the selected fields, as specified by {@link #extractedFieldIndexes()} * * @return true if the parsed records are being reordered by the parser, false otherwise * * @see com.univocity.parsers.common.CommonParserSettings * @see com.univocity.parsers.common.CommonSettings */ boolean columnsReordered(); /** * Returns the position of a header (0 based). * * @param header the header whose position will be returned * * @return the position of the given header, or -1 if it could not be found. */ int indexOf(String header); /** * Returns the position of a header (0 based). * * @param header the header whose position will be returned * * @return the position of the given header, or -1 if it could not be found. */ int indexOf(Enum header); /** * Returns the column index of the record being processed. * * @return the column index of the record being processed. */ int currentColumn(); /** * Returns the index of the last valid record parsed from the input * * @return the index of the last valid record parsed from the input */ long currentRecord(); /** * Stops the parsing process. Any open resources in use by the parser are closed * automatically unless {@link CommonParserSettings#isAutoClosingEnabled()} evaluates to {@code false}. */ void stop(); /** * Identifies whether the parser is running. * * @return true if the parser is stopped, false otherwise. */ boolean isStopped(); /** * Returns the length limit of parsed contents appearing in exception messages when an error occurs * *

If {@code 0}, then no exceptions will include the content being manipulated in their attributes, * and the {@code ""} string will appear in error messages as the parsed content.

* *

defaults to {@code -1} (no limit)

. * * @return the maximum length of the data content to display in exception messages */ int errorContentLength(); /** * Converts the given parsed row to a {@link Record} * * @param row the row to be converted into a {@link Record} * * @return a {@link Record} representing the given row. */ Record toRecord(String[] row); /** * Returns the metadata information associated with records produced by the current parsing process. * * @return the record metadata. */ RecordMetaData recordMetaData(); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ContextSnapshot.java000066400000000000000000000033721475274123300335110ustar00rootroot00000000000000/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; /** * A snapshot of a {@link Context} which retains copies of variable attributes of a given {@link Context} to * store the state of the parsing process at a given point in time. All runtime operations such as {@link #stop()} * will still work and affect the current parsing process. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public abstract class ContextSnapshot extends ContextWrapper { private final int currentColumn; private final long currentRecord; /** * Creates a snapshot of a given {@link Context} * @param context the context object whose variable attributes will be copied over. */ public ContextSnapshot(T context) { super(context); currentColumn = context.currentColumn(); currentRecord = context.currentRecord(); } @Override public int currentColumn() { return currentColumn; } @Override public long currentRecord() { return currentRecord; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ContextWrapper.java000066400000000000000000000044621475274123300333330ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.record.*; /** * A simple a wrapper for a {@link Context}. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public abstract class ContextWrapper implements Context { protected final T context; /** * Wraps a {@link Context}. * * @param context the context object to be wrapped. */ public ContextWrapper(T context) { this.context = context; } @Override public String[] headers() { return context.headers(); } @Override public int[] extractedFieldIndexes() { return context.extractedFieldIndexes(); } @Override public boolean columnsReordered() { return context.columnsReordered(); } @Override public int indexOf(String header) { return context.indexOf(header); } @Override public int indexOf(Enum header) { return context.indexOf(header); } @Override public int currentColumn() { return context.currentColumn(); } @Override public long currentRecord() { return context.currentRecord(); } @Override public void stop() { context.stop(); } @Override public boolean isStopped() { return context.isStopped(); } @Override public String[] selectedHeaders() { return context.selectedHeaders(); } @Override public int errorContentLength() { return context.errorContentLength(); } @Override public Record toRecord(String[] row) { return context.toRecord(row); } @Override public RecordMetaData recordMetaData() { return context.recordMetaData(); } } ConversionProcessor.java000066400000000000000000000054701475274123300343140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.conversions.*; /** * A basic interface for classes that associate {@link Conversion} implementations with fields of a given input/output. */ public interface ConversionProcessor { /** * Applies a set of {@link Conversion} objects over indexes of a record. * *

The idiom to define which indexes should have these conversions applies is as follows: *


	 *
	 * processor.convertIndexes(Conversions.trim(), Conversions.toUpperCase()).add(2, 5); // applies trim and uppercase conversions to fields in indexes 2 and 5
	 * 

* * @param conversions The sequence of conversions to be executed in a set of field indexes. * * @return A {@link FieldSet} for indexes. */ @SuppressWarnings({"unchecked", "rawtypes"}) FieldSet convertIndexes(Conversion... conversions); /** * Applies a set of {@link Conversion} objects over all elements of a record * * @param conversions The sequence of conversions to be executed in all elements of a record */ @SuppressWarnings({"rawtypes", "unchecked"}) void convertAll(Conversion... conversions); /** * Applies a set of {@link Conversion} objects over fields of a record by name. * *

The idiom to define which fields should have these conversions applied is as follows: *


	 *
	 * processor.convertFields(Conversions.trim(), Conversions.toUpperCase()).add("name", "position"); // applies trim and uppercase conversions to fields with headers "name" and "position"
	 * 

* * @param conversions The sequence of conversions to be executed in a set of field indexes. * * @return A {@link FieldSet} for field names. */ @SuppressWarnings({"unchecked", "rawtypes"}) FieldSet convertFields(Conversion... conversions); /** * Applies a sequence of conversions over values of a given type. Used for writing. * @param type the type over which a sequence of conversions should be applied * @param conversions the sequence of conversions to apply over values of the given type. */ void convertType(Class type, Conversion... conversions); } DataProcessingException.java000066400000000000000000000231321475274123300350470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.processor.*; import java.util.*; /** * A {@code DataProcessingException} is an error thrown during the processing of a record successfully parsed. * This type of error usually indicates that the input text has been parsed correctly, but the subsequent * transformations applied over the input (generally via a {@link RowProcessor}} failed. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class DataProcessingException extends TextParsingException { private static final long serialVersionUID = 1410975527141918215L; private String columnName; private int columnIndex; private Object[] row; private Object value; private Map values = new HashMap(); private boolean fatal = true; private boolean handled = false; private String details = null; /** * Creates a new exception with an error message only. * * @param message the error message */ public DataProcessingException(String message) { this(message, -1, null, null); } /** * Creates a new exception with an error message and error cause * * @param message the error message * @param cause the cause of the error */ public DataProcessingException(String message, Throwable cause) { this(message, -1, null, cause); } /** * Creates a new exception with an error message and the row that could not be processed. * * @param message the error message * @param row the row that could not be processed. */ public DataProcessingException(String message, Object[] row) { this(message, -1, row, null); } /** * Creates a new exception with an error message, the row that could not be processed, and the error cause. * * @param message the error message * @param row the row that could not be processed. * @param cause the cause of the error */ public DataProcessingException(String message, Object[] row, Throwable cause) { this(message, -1, row, cause); } /** * Creates a new exception with an error message and the column that could not be processed. * * @param message the error message * @param columnIndex index of the column that could not be processed. */ public DataProcessingException(String message, int columnIndex) { this(message, columnIndex, null, null); } /** * Creates a new exception with an error message, the column that could not be processed * the row that could not be processed, and the error cause. * * @param message the error message * @param columnIndex index of the column that could not be processed. * @param row the row that could not be processed. * @param cause the cause of the error */ public DataProcessingException(String message, int columnIndex, Object[] row, Throwable cause) { super(null, message, cause); setColumnIndex(columnIndex); this.row = row; } @Override protected String getErrorDescription() { return "Error processing parsed input"; } @Override protected String getDetails() { String details = (this.details == null ? "" : this.details + '\n') + super.getDetails(); Object[] row = getRow(); if (row != null) { row = row.clone(); for (int i = 0; i < row.length; i++) { row[i] = restrictContent(row[i]); } } details = printIfNotEmpty(details, "row", row); details = printIfNotEmpty(details, "value", restrictContent(getValue())); details = printIfNotEmpty(details, "columnName", getColumnName()); details = printIfNotEmpty(details, "columnIndex", getColumnIndex()); return details; } /** * Returns the name of the column from where the error occurred, if available. * * @return the name of the column from where the error occurred. */ public String getColumnName() { if (columnName != null) { return columnName; } String[] headers = getHeaders(); if (headers != null && getExtractedColumnIndex() != -1 && getExtractedColumnIndex() < headers.length) { return headers[getExtractedColumnIndex()]; } return null; } /** * Returns the index of the column from where the error occurred, if available. * * @return the index of the column from where the error occurred. */ public final int getColumnIndex() { return columnIndex; } /** * Returns the record being processed when the error occurred, if available. * * @return the record being processed when error occurred, if available. */ public final Object[] getRow() { return restrictContent(row); } /** * Defines the value being processed when the error occurred. * * @param value the value being processed when error occurred. */ public final void setValue(Object value) { if (errorContentLength == 0) { value = null; } if (value == null) { value = "null"; } this.value = value; } /** * Associates a label in the exception message (idenfied in curly braces) with a value being processed when the error occurred. * Used for formatting the exception message * * @param label a label in the exception message - any string enclosed by curly braces. * @param value the value being processed when error occurred, that should be replaced by the label in the exception message. */ public final void setValue(String label, Object value) { if (errorContentLength == 0) { value = null; } this.values.put(label, value); } /** * Returns the value being processed when the error occurred, if available. * * @return the value being processed when the error occurred, if available. */ public final Object getValue() { if (errorContentLength == 0) { return null; } if (value != null) { return value; } if (row != null && columnIndex != -1 && columnIndex < row.length) { return row[columnIndex]; } return null; } /** * Defines the column index being processed when the error occurred. * * @param columnIndex the column index being processed when error occurred. */ public final void setColumnIndex(int columnIndex) { this.columnIndex = columnIndex; } private int getExtractedColumnIndex() { if (this.extractedIndexes != null && columnIndex < extractedIndexes.length && columnIndex > -1) { return extractedIndexes[columnIndex]; } return columnIndex; } /** * Defines the name of the column being processed when the error occurred. * * @param columnName the name of the column being processed when error occurred. */ public final void setColumnName(String columnName) { this.columnName = columnName; } /** * Updates the exception with the record being processed when the error occurred. * * @param row the record data processed when the error occurred. */ public final void setRow(Object[] row) { if (errorContentLength == 0) { row = null; } this.row = row; } /** * Returns a flag indicating whether this error is fatal and the process must stop as it is impossible to proceed. * * @return a flag indicating whether this error is fatal and the process must stop as it is impossible to proceed. */ final boolean isFatal() { return fatal; } /** * Marks the error as non fatal and the parsing process might proceed. */ public final void markAsNonFatal() { this.fatal = false; } /** * Marks the error as handled so it doesn't trigger a {@link ProcessorErrorHandler} again. * @param handler the {@link ProcessorErrorHandler} used to handle this exception. */ public final void markAsHandled(ProcessorErrorHandler handler) { this.handled = handler != null && !(handler instanceof NoopProcessorErrorHandler) && !(handler instanceof NoopRowProcessorErrorHandler); } /** * Returns a flag indicating this exception has been handled by a user-provided {@link ProcessorErrorHandler} * * @return {@code true} if this exception has been handled to a user-provided {@link ProcessorErrorHandler}, * otherwise {@code false} */ public boolean isHandled() { return handled; } public void setDetails(String details) { this.details = details == null || details.trim().isEmpty() ? null : details; } @Override protected final String updateMessage(String msg) { if (errorContentLength == 0 || msg == null) { return msg; //doesn't replace labels enclosed within { and }. } StringBuilder out = new StringBuilder(msg.length()); int previous = 0; int start = 0; while (true) { start = msg.indexOf('{', start); if (start == -1) { break; } int end = msg.indexOf('}', start); if (end == -1) { break; } String label = msg.substring(start + 1, end); Object value = null; if ("value".equals(label)) { value = this.value; } else if (values.containsKey(label)) { value = values.get(label); } if (value != null) { String content = restrictContent(value); out.append(msg, previous, start); out.append(content); previous = end; } start = end; } out.append(msg, previous == 0 ? 0 : previous + 1, msg.length()); return out.toString(); } } DataValidationException.java000066400000000000000000000053331475274123300350300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; /** * A {@code DataValidationException} is an error thrown during the processing of a record successfully parsed, * but whose data failed to pass a validation defined by annotation {@link com.univocity.parsers.annotations.Validate} * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class DataValidationException extends DataProcessingException { private static final long serialVersionUID = 3110975527111918123L; /** * Creates a new validation exception with an error message only. * * @param message the error message */ public DataValidationException(String message) { super(message, -1, null, null); } /** * Creates a new validation exception with an error message and error cause * * @param message the error message * @param cause the cause of the error */ public DataValidationException(String message, Throwable cause) { super(message, -1, null, cause); } /** * Creates a new validation exception with an error message and the row that could not be validated. * * @param message the error message * @param row the row that could not be processed. */ public DataValidationException(String message, Object[] row) { super(message, -1, row, null); } /** * Creates a new validation exception with an error message, the row that could not be validated, and the error cause. * * @param message the error message * @param row the row that could not be processed. * @param cause the cause of the error */ public DataValidationException(String message, Object[] row, Throwable cause) { super(message, -1, row, cause); } /** * Creates a new validation exception with an error message and the column that could not be validated. * * @param message the error message * @param columnIndex index of the column that could not be validated. */ public DataValidationException(String message, int columnIndex) { super(message, columnIndex, null, null); } @Override protected String getErrorDescription() { return "Error validating parsed input"; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/DefaultContext.java000066400000000000000000000066571475274123300333070ustar00rootroot00000000000000/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; import com.univocity.parsers.common.record.*; /** * Default implementation of the {@link Context} interface with essential information about the output being produced. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public class DefaultContext implements Context { protected boolean stopped = false; final ParserOutput output; final ColumnMap columnMap; final int errorContentLength; protected RecordFactory recordFactory; private String[] headers; public DefaultContext(int errorContentLength) { this(null, errorContentLength); } public DefaultContext(ParserOutput output, int errorContentLength) { this.output = output; this.errorContentLength = errorContentLength; this.columnMap = new ColumnMap(this, output); } @Override public String[] headers() { if(headers == null) { if (output == null) { headers = ArgumentUtils.EMPTY_STRING_ARRAY; } headers = output.getHeaderAsStringArray(); } return headers; } public String[] selectedHeaders() { if(headers == null) { headers(); } int[] extractedFieldIndexes = extractedFieldIndexes(); if (extractedFieldIndexes != null) { String[] extractedFields = new String[extractedFieldIndexes.length]; String[] headers = headers(); for (int i = 0; i < extractedFieldIndexes.length; i++) { extractedFields[i] = headers[extractedFieldIndexes[i]]; } return extractedFields; } return headers(); } @Override public int[] extractedFieldIndexes() { if (output == null) { return null; } return output.getSelectedIndexes(); } @Override public boolean columnsReordered() { if (output == null) { return false; } return output.isColumnReorderingEnabled(); } @Override public int indexOf(String header) { return columnMap.indexOf(header); } @Override public int indexOf(Enum header) { return columnMap.indexOf(header); } void reset() { if (output != null) { output.reset(); } recordFactory = null; columnMap.reset(); } @Override public int currentColumn() { if (output == null) { return -1; } return output.getCurrentColumn(); } @Override public long currentRecord() { if (output == null) { return -1; } return output.getCurrentRecord(); } @Override public void stop() { stopped = true; } @Override public boolean isStopped() { return stopped; } @Override public int errorContentLength() { return errorContentLength; } @Override public Record toRecord(String[] row) { if (recordFactory == null) { recordFactory = new RecordFactory(this); } return recordFactory.newRecord(row); } @Override public RecordMetaData recordMetaData(){ if(recordFactory == null){ recordFactory = new RecordFactory(this); } return recordFactory.getRecordMetaData(); } } DefaultConversionProcessor.java000066400000000000000000000305231475274123300356160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.util.*; /** * The base class for {@link RowProcessor} and {@link RowWriterProcessor} implementations that support value conversions provided by {@link Conversion} instances. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public abstract class DefaultConversionProcessor implements ConversionProcessor { private Map, Conversion[]> conversionsByType; protected FieldConversionMapping conversions; private boolean conversionsInitialized; private int[] fieldIndexes; private int[] reverseFieldIndexes; private boolean fieldsReordered; ProcessorErrorHandler errorHandler = NoopProcessorErrorHandler.instance; Context context; @Override @SuppressWarnings({"unchecked", "rawtypes"}) public final FieldSet convertIndexes(Conversion... conversions) { return getConversions().applyConversionsOnFieldIndexes(conversions); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public final void convertAll(Conversion... conversions) { getConversions().applyConversionsOnAllFields(conversions); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public final FieldSet convertFields(Conversion... conversions) { return getConversions().applyConversionsOnFieldNames(conversions); } private FieldConversionMapping getConversions() { if (conversions == null) { conversions = new FieldConversionMapping(); } return conversions; } protected void initializeConversions(String[] row, Context context) { conversionsInitialized = true; this.fieldIndexes = null; this.fieldsReordered = false; String[] contextHeaders = context == null ? null : context.headers(); if (contextHeaders != null && contextHeaders.length > 0) { getConversions().prepareExecution(false, contextHeaders); } else { getConversions().prepareExecution(false, row); } if (context != null) { this.fieldIndexes = context.extractedFieldIndexes(); this.fieldsReordered = context.columnsReordered(); } } /** * Executes the sequences of conversions defined using {@link DefaultConversionProcessor#convertFields(Conversion...)}, {@link DefaultConversionProcessor#convertIndexes(Conversion...)} and {@link DefaultConversionProcessor#convertAll(Conversion...)}, for every field in the given row. * *

Each field will be transformed using the {@link Conversion#execute(Object)} method. *

In general the conversions will process a String and convert it to some object value (such as booleans, dates, etc). * * @param row the parsed record with its individual records as extracted from the original input. * @param context the current state of the parsing process. * * @return an row of Object instances containing the values obtained after the execution of all conversions. *

Fields that do not have any conversion defined will just be copied to the object array into their original positions. */ public final Object[] applyConversions(String[] row, Context context) { boolean keepRow = true; Object[] objectRow = new Object[row.length]; boolean[] convertedFlags = conversionsByType != null ? new boolean[row.length] : null; System.arraycopy(row, 0, objectRow, 0, row.length); if (conversions != null) { if (!conversionsInitialized) { initializeConversions(row, context); } final int length = !fieldsReordered && fieldIndexes == null ? objectRow.length : fieldIndexes.length; for (int i = 0; i < length; i++) { try { if (!fieldsReordered) { if (fieldIndexes == null) { objectRow[i] = conversions.applyConversions(i, row[i], convertedFlags); } else { int index = fieldIndexes[i]; objectRow[index] = conversions.applyConversions(index, row[index], convertedFlags); } } else { objectRow[i] = conversions.applyConversions(fieldIndexes[i], row[i], convertedFlags); } } catch (Throwable ex) { keepRow = handleConversionError(ex, objectRow, i); } } } if (keepRow && convertedFlags != null) { keepRow = applyConversionsByType(false, objectRow, convertedFlags); } if (keepRow && validateAllValues(objectRow)) { return objectRow; } return null; } private void populateReverseFieldIndexes() { int max = 0; for (int i = 0; i < fieldIndexes.length; i++) { if (fieldIndexes[i] > max) { max = fieldIndexes[i]; } } reverseFieldIndexes = new int[max + 1]; Arrays.fill(reverseFieldIndexes, -1); for (int i = 0; i < fieldIndexes.length; i++) { reverseFieldIndexes[fieldIndexes[i]] = i; } } private boolean validateAllValues(Object[] objectRow) { if (conversions != null && conversions.validatedIndexes != null) { boolean keepRow = true; for (int i = 0; keepRow && i < conversions.validatedIndexes.length; i++) { final int index = conversions.validatedIndexes[i]; int valueIndex = index; if (fieldsReordered) { if (reverseFieldIndexes == null) { populateReverseFieldIndexes(); } valueIndex = reverseFieldIndexes[index]; } try { Object value = index < objectRow.length ? objectRow[valueIndex] : null; conversions.executeValidations(index, value); } catch (Throwable ex) { keepRow = handleConversionError(ex, objectRow, index); } } return keepRow; } return true; } /** * Executes the sequences of reverse conversions defined using {@link DefaultConversionProcessor#convertFields(Conversion...)}, {@link DefaultConversionProcessor#convertIndexes(Conversion...)} and {@link DefaultConversionProcessor#convertAll(Conversion...)}, for every field in the given row. * *

Each field will be transformed using the {@link Conversion#revert(Object)} method. *

In general the conversions will process an Object (such as a Boolean, Date, etc), and convert it to a String representation. * * @param executeInReverseOrder flag to indicate whether the conversion sequence should be executed in the reverse order of its declaration. * @param row the row of objects that will be converted * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * * @return {@code true} if the the row should be discarded */ public final boolean reverseConversions(boolean executeInReverseOrder, Object[] row, NormalizedString[] headers, int[] indexesToWrite) { boolean keepRow = true; boolean[] convertedFlags = conversionsByType != null ? new boolean[row.length] : null; if (conversions != null) { if (!conversionsInitialized) { conversionsInitialized = true; conversions.prepareExecution(true, headers != null ? NormalizedString.toArray(headers) : new String[row.length]); this.fieldIndexes = indexesToWrite; } if (executeInReverseOrder) { keepRow = validateAllValues(row); } final int last = fieldIndexes == null ? row.length : fieldIndexes.length; for (int i = 0; i < last; i++) { try { if (fieldIndexes == null || fieldIndexes[i] == -1) { row[i] = conversions.reverseConversions(executeInReverseOrder, i, row[i], convertedFlags); } else { int index = fieldIndexes[i]; row[index] = conversions.reverseConversions(executeInReverseOrder, index, row[index], convertedFlags); } } catch (Throwable ex) { keepRow = handleConversionError(ex, row, i); } } } if (keepRow && convertedFlags != null) { keepRow = applyConversionsByType(true, row, convertedFlags); } if (executeInReverseOrder) { return keepRow; } return keepRow && validateAllValues(row); } private boolean applyConversionsByType(boolean reverse, Object[] row, boolean[] convertedFlags) { boolean keepRow = true; for (int i = 0; i < row.length; i++) { if (convertedFlags[i]) { continue; //conversions already applied. Prevent default type conversion. } try { row[i] = applyTypeConversion(reverse, row[i]); } catch (Throwable ex) { keepRow = handleConversionError(ex, row, i); } } return keepRow; } /** * Handles an error that occurred when applying conversions over a value. If the user defined a * {@link ProcessorErrorHandler} the user will receive the exception and is able to determine whether or not * processing should continue, discarding the record. If the error handler is an instance of * {@link RetryableErrorHandler}, the user can provide a default value to use in place of the one that could not * be converted, and decide whether or not the record should be kept with the use of the * {@link RetryableErrorHandler#keepRecord()} method. * * @param ex the exception that occurred when applying a conversion * @param row the record being processed at the time the exception happened. * @param column the column if the given row, whose value could not be converted. If negative, it's not possible to * keep the record. * * @return {@code true} if the error has been handled by the user and the record can still be processed, otherwise * {@code false} if the record should be discarded. */ protected final boolean handleConversionError(Throwable ex, Object[] row, int column) { if (row != null && row.length < column) { //expand row so column index won't make error handlers blow up. row = Arrays.copyOf(row, column + 1); } DataProcessingException error = toDataProcessingException(ex, row, column); if (column > -1 && errorHandler instanceof RetryableErrorHandler) { ((RetryableErrorHandler) errorHandler).prepareToRun(); } error.markAsHandled(errorHandler); errorHandler.handleError(error, row, context); if (column > -1 && errorHandler instanceof RetryableErrorHandler) { RetryableErrorHandler retry = ((RetryableErrorHandler) errorHandler); Object defaultValue = retry.getDefaultValue(); row[column] = defaultValue; return !retry.isRecordSkipped(); } return false; } protected DataProcessingException toDataProcessingException(Throwable ex, Object[] row, int column) { DataProcessingException error; if (ex instanceof DataProcessingException) { error = (DataProcessingException) ex; error.setRow(row); error.setColumnIndex(column); } else { error = new DataProcessingException("Error processing data conversions", column, row, ex); } error.markAsNonFatal(); error.setContext(context); return error; } @Override public final void convertType(Class type, Conversion... conversions) { ArgumentUtils.noNulls("Type to convert", type); ArgumentUtils.noNulls("Sequence of conversions to apply over data of type " + type.getSimpleName(), conversions); if (conversionsByType == null) { conversionsByType = new HashMap, Conversion[]>(); } conversionsByType.put(type, conversions); } private Object applyTypeConversion(boolean revert, Object input) { if (conversionsByType == null || input == null) { return input; } Conversion[] conversionSequence = conversionsByType.get(input.getClass()); if (conversionSequence == null) { return input; } if (revert) { for (int i = 0; i < conversionSequence.length; i++) { input = conversionSequence[i].revert(input); } } else { for (int i = 0; i < conversionSequence.length; i++) { input = conversionSequence[i].execute(input); } } return input; } } DefaultParsingContext.java000066400000000000000000000052361475274123300345440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; import com.univocity.parsers.common.input.*; import java.util.*; /** * The default {@link ParsingContext} implementation used internally by {@link AbstractParser} to expose information about a parsing process in execution. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.ParsingContext * @see com.univocity.parsers.common.AbstractParser * @see com.univocity.parsers.common.processor.RowProcessor */ public class DefaultParsingContext extends DefaultContext implements ParsingContext { private final CharInputReader input; private final AbstractParser parser; public DefaultParsingContext(AbstractParser parser, int errorContentLength) { super(parser == null ? null : parser.output, errorContentLength); this.parser = parser; this.input = parser == null ? null : parser.input; } @Override public long currentLine() { return input.lineCount(); } @Override public long currentChar() { return input.charCount(); } @Override public void skipLines(long lines) { input.skipLines(lines); } @Override public String fieldContentOnError() { char[] chars = output.appender.getChars(); if (chars != null) { int length = output.appender.length(); if (length > chars.length) { length = chars.length; } if (length > 0) { return new String(chars, 0, length); } } return null; } @Override public String currentParsedContent() { if (input != null) { return input.currentParsedContent(); } return null; } @Override public int currentParsedContentLength() { if (input != null) { return input.currentParsedContentLength(); } return 0; } @Override public Map comments() { return parser.getComments(); } @Override public String lastComment() { return parser.getLastComment(); } @Override public String[] parsedHeaders() { return parser.getParsedHeaders(); } @Override public char[] lineSeparator() { return input.getLineSeparator(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/DummyFormat.java000066400000000000000000000025461475274123300326130ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.util.*; /** * A concrete (dummy) implementation of {@code Format}. Used by {@link AbstractWriter} to manage its internal configuration of field selections * * @see AbstractWriter * @see CommonSettings * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ final class DummyFormat extends Format { static final DummyFormat instance = new DummyFormat(); private DummyFormat() { } @Override protected final TreeMap getConfiguration() { return new TreeMap(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/Format.java000066400000000000000000000206551475274123300316000ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.util.Map.*; import java.util.*; /** * This is the parent class for all configuration classes that define a text format. * *

By default, all parsers and writers have to handle, at least, the following format definitions: * *

    *
  • lineSeparator: the 1-2 character sequence that indicates the end of a line. Newline sequences are different across operating systems. Typically: *
      *
    • Windows uses carriage return and line feed: \r\n
    • *
    • Linux/Unix uses line feed only: \n
    • *
    • MacOS uses carriage return only: \r
    • *
    * {@link Format#lineSeparator} defaults to the system line separator *
  • *
  • normalizedNewline: a single character used to represent the end of a line uniformly in any parsed content. It has the following implications: *
      *
    • When reading a text-based input, the sequence of characters defined in {@link Format#lineSeparator} will be replaced by this character.
    • *
    • When writing to a text-based output, this character will be replaced by the sequence of characters defined in {@link Format#lineSeparator}.
    • *
    *

    {@link Format#normalizedNewline} defaults to '\n'. *

  • *
  • comment:a character that, if found in the beginning of a line of text, represents comment in any text-based input supported by univocity-parsers. *

    {@link Format#comment} defaults to '#'.

  • *
* * @see com.univocity.parsers.csv.CsvFormat * @see com.univocity.parsers.fixed.FixedWidthFormat * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public abstract class Format implements Cloneable{ private static final String systemLineSeparatorString; private static final char[] systemLineSeparator; static { String lineSeparator = System.getProperty("line.separator"); if (lineSeparator == null) { systemLineSeparatorString = "\n"; } else { systemLineSeparatorString = lineSeparator; } systemLineSeparator = systemLineSeparatorString.toCharArray(); } private String lineSeparatorString; private char[] lineSeparator; private char normalizedNewline = '\n'; private char comment = '#'; protected Format() { this.lineSeparator = systemLineSeparator.clone(); this.lineSeparatorString = systemLineSeparatorString; } /** * Returns the current line separator character sequence, which can contain 1 to 2 characters. Defaults to the system's line separator sequence (usually '\r\n' in Windows, '\r' in MacOS, and '\n' in Linux/Unix). * @return the sequence of 1 to 2 characters that identifies the end of a line */ public char[] getLineSeparator() { return lineSeparator.clone(); } /** * Returns the system's line separator sequence, which can contain 1 to 2 characters. * @return a sequence of 1 to 2 characters used as the system's line ending. */ public static char[] getSystemLineSeparator(){ return systemLineSeparator.clone(); } /** * Returns the current line separator sequence as a String of 1 to 2 characters. Defaults to the system's line separator sequence (usually "\r\n" in Windows, "\r" in MacOS, and "\n" in Linux/Unix). * @return the sequence of 1 to 2 characters that identifies the end of a line */ public String getLineSeparatorString() { return lineSeparatorString; } /** * Defines the line separator sequence that should be used for parsing and writing. * @param lineSeparator a sequence of 1 to 2 characters that identifies the end of a line */ public void setLineSeparator(String lineSeparator) { if (lineSeparator == null || lineSeparator.isEmpty()) { throw new IllegalArgumentException("Line separator cannot be empty"); } setLineSeparator(lineSeparator.toCharArray()); } /** * Defines the line separator sequence that should be used for parsing and writing. * @param lineSeparator a sequence of 1 to 2 characters that identifies the end of a line */ public void setLineSeparator(char[] lineSeparator) { if (lineSeparator == null || lineSeparator.length == 0) { throw new IllegalArgumentException("Invalid line separator. Expected 1 to 2 characters"); } if (lineSeparator.length > 2) { throw new IllegalArgumentException("Invalid line separator. Up to 2 characters are expected. Got " + lineSeparator.length + " characters."); } this.lineSeparator = lineSeparator; this.lineSeparatorString = new String(lineSeparator); if(lineSeparator.length == 1){ setNormalizedNewline(lineSeparator[0]); } } /** * Returns the normalized newline character, which is automatically replaced by {@link Format#lineSeparator} when reading/writing. Defaults to '\n'. * @return the normalized newline character */ public char getNormalizedNewline() { return normalizedNewline; } /** * Sets the normalized newline character, which is automatically replaced by {@link Format#lineSeparator} when reading/writing * @param normalizedNewline a single character used to represent a line separator. */ public void setNormalizedNewline(char normalizedNewline) { this.normalizedNewline = normalizedNewline; } /** * Compares the given character against the {@link Format#normalizedNewline} character. * @param ch the character to be verified * @return true if the given character is the normalized newline character, false otherwise */ public boolean isNewLine(char ch) { return this.normalizedNewline == ch; } /** * Returns the character that represents a line comment. Defaults to '#' *

Set it to '\0' to disable comment skipping. * @return the comment character */ public char getComment() { return comment; } /** * Defines the character that represents a line comment when found in the beginning of a line of text. Defaults to '#' *

Use '\0' to disable comment skipping. * @param comment the comment character */ public void setComment(char comment) { this.comment = comment; } /** * Identifies whether or not a given character represents a comment * @param ch the character to be verified * @return true if the given character is the comment character, false otherwise */ public boolean isComment(char ch) { return this.comment == ch; } private static String getFormattedValue(Object value) { if (value instanceof Character) { char ch = (Character) value; switch (ch) { case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; case '\0': return "\\0"; default: return value.toString(); } } if (value instanceof String) { String s = (String) value; StringBuilder tmp = new StringBuilder(); for (int i = 0; i < s.length(); i++) { tmp.append(getFormattedValue(s.charAt(i))); } value = tmp.toString(); } if (String.valueOf(value).trim().isEmpty()) { return "'" + value + '\''; } return String.valueOf(value); } @Override public final String toString() { StringBuilder out = new StringBuilder(); out.append(getClass().getSimpleName()).append(':'); TreeMap config = getConfiguration(); config.put("Comment character", comment); config.put("Line separator sequence", lineSeparatorString); config.put("Line separator (normalized)", normalizedNewline); for (Entry e : config.entrySet()) { out.append("\n\t\t"); out.append(e.getKey()).append('=').append(getFormattedValue(e.getValue())); } return out.toString(); } protected abstract TreeMap getConfiguration(); @Override protected Format clone() { try { return (Format) super.clone(); } catch(CloneNotSupportedException e){ throw new IllegalStateException("Error cloning format object", e); } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/Internal.java000066400000000000000000000050751475274123300321230ustar00rootroot00000000000000/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * Internal class to keep common internal functions that are used in multiple places. * * @author Univocity Software Pty Ltd - dev@univocity.com */ class Internal { public static final void process(String[] row, Processor processor, C context, ProcessorErrorHandler errorHandler) { try { processor.rowProcessed(row, context); } catch (DataProcessingException ex) { ex.setContext(context); if (!ex.isFatal() && !ex.isHandled() && ex.getColumnIndex() > -1 && errorHandler instanceof RetryableErrorHandler) { RetryableErrorHandler retry = ((RetryableErrorHandler) errorHandler); ex.markAsHandled(errorHandler); retry.handleError(ex, row, context); if (!retry.isRecordSkipped()) { try { processor.rowProcessed(row, context); return; } catch (DataProcessingException e) { ex = e; } catch (Throwable t) { throwDataProcessingException(processor, t, row, context.errorContentLength()); } } } ex.setErrorContentLength(context.errorContentLength()); if (ex.isFatal()) { throw ex; } ex.markAsHandled(errorHandler); errorHandler.handleError(ex, row, context); } catch (Throwable t) { throwDataProcessingException(processor, t, row, context.errorContentLength()); } } private static final void throwDataProcessingException(Processor processor, Throwable t, String[] row, int errorContentLength) throws DataProcessingException { DataProcessingException ex = new DataProcessingException("Unexpected error processing input row " + AbstractException.restrictContent(errorContentLength, Arrays.toString(row)) + " using Processor " + processor.getClass().getName() + '.' , AbstractException.restrictContent(errorContentLength, row) , t); ex.restrictContent(errorContentLength); throw ex; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/IterableResult.java000066400000000000000000000024521475274123300332710ustar00rootroot00000000000000/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; /** * An {@link Iterable} result that provides the current parsing context * through the {@link #getContext()} method * * @author Univocity Software Pty Ltd - dev@univocity.com */ public interface IterableResult extends Iterable { /** * Returns the current parsing {@link Context}, if available * @return the contextual object with information about an ongoing parsing process */ C getContext(); @Override ResultIterator iterator(); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/LineReader.java000066400000000000000000000034131475274123300323530ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.io.*; /** * A simple Reader implementation to enable parsers to process lines on demand, via {@link AbstractParser#parseLine(String)} * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ class LineReader extends Reader { private String line; private int length; private int next = 0; public LineReader() { } public void setLine(String line) { this.line = line; this.length = line.length(); this.next = 0; } @Override public int read(char cbuf[], int off, int len) { if (len == 0) { return 0; } if (next >= length) { return -1; } int read = Math.min(length - next, len); line.getChars(next, next + read, cbuf, off); next += read; return read; } @Override public long skip(long ns) { return 0; } @Override public boolean ready() { return line != null; } @Override public boolean markSupported() { return false; } @Override public void close() { line = null; } } NoopParsingContext.java000066400000000000000000000054141475274123300340710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.record.*; import java.util.*; /** * A {@link ParsingContext} implementation that does nothing. * * @author Univocity Software Pty Ltd - dev@univocity.com */ class NoopParsingContext implements ParsingContext { static final NoopParsingContext instance = new NoopParsingContext(); private RecordMetaData recordMetaData; private NoopParsingContext() { } @Override public void stop() { } @Override public boolean isStopped() { return false; } @Override public long currentLine() { return 0; } @Override public long currentChar() { return 0; } @Override public int currentColumn() { return 0; } @Override public long currentRecord() { return 0; } @Override public void skipLines(long lines) { } @Override public String[] parsedHeaders() { return null; } @Override public String currentParsedContent() { return null; } public int currentParsedContentLength() { return 0; } @Override public Map comments() { return Collections.emptyMap(); } @Override public String lastComment() { return null; } @Override public char[] lineSeparator() { return Format.getSystemLineSeparator(); } @Override public String[] headers() { return null; } @Override public String[] selectedHeaders() { return null; } @Override public int[] extractedFieldIndexes() { return null; } @Override public boolean columnsReordered() { return true; } @Override public int indexOf(String header) { return -1; } @Override public int indexOf(Enum header) { return -1; } @Override public String fieldContentOnError() { return null; } @Override public int errorContentLength() { return -1; } @Override public Record toRecord(String[] row) { return null; } @Override public RecordMetaData recordMetaData() { if(recordMetaData == null){ recordMetaData = new RecordFactory(this).getRecordMetaData(); } return recordMetaData; } } NoopProcessorErrorHandler.java000066400000000000000000000034641475274123300354130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; /** * An (singleton) implementation of {@link ProcessorErrorHandler} that simply rethrows any {@link DataProcessingException} * that comes into its {@link #handleError(DataProcessingException, Object[], Context)}} method * * @see ProcessorErrorHandler * * @author Univocity Software Pty Ltd - parsers@univocity.com * @param the {@code Context} type provided by the parser implementation. * */ public final class NoopProcessorErrorHandler implements ProcessorErrorHandler { public static final ProcessorErrorHandler instance = new NoopProcessorErrorHandler(); private NoopProcessorErrorHandler() { } /** * Rethrows the {@link DataProcessingException} * * @param error the exception thrown during the processing an input record. Will be rethrown to abort the parsing process. * @param inputRow ignored * @param context ignored */ @Override public void handleError(DataProcessingException error, Object[] inputRow, T context) { throw error; } } NoopRowProcessorErrorHandler.java000066400000000000000000000030721475274123300360760ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; /** * An (singleton) implementation of {@link RowProcessorErrorHandler} that simply rethrows any {@link DataProcessingException} * that comes into its {@link #handleError(DataProcessingException, Object[], ParsingContext)} method * * @see RowProcessorErrorHandler * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ final class NoopRowProcessorErrorHandler implements RowProcessorErrorHandler { public static final RowProcessorErrorHandler instance = new NoopRowProcessorErrorHandler(); private NoopRowProcessorErrorHandler() { } /** * Rethrows the {@link DataProcessingException} */ @Override public void handleError(DataProcessingException error, Object[] inputRow, ParsingContext context) { throw error; } } NormalizedString.java000066400000000000000000000535571475274123300335730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.io.*; import java.util.*; import static com.univocity.parsers.common.ArgumentUtils.*; /** * A {@code NormalizedString} allows representing text in a normalized fashion. Strings * with different character case or surrounding whitespace are considered the same. * * Used to represent groups of fields, where users may refer to their names using * different character cases or whitespaces. * * Where the character case or the surrounding space is relevant, the {@code NormalizedString} * will have its {@link #isLiteral()} method return {@code true}, meaning the exact * character case and surrounding whitespaces are required for matching it. * * Invoking {@link #valueOf(String)} with a {@code String} surrounded by single quotes * will create a literal {@code NormalizedString}. Use {@link #literalValueOf(String)} * to obtain the same {@code NormalizedString} without having to introduce single quotes. * */ public final class NormalizedString implements Serializable, Comparable, CharSequence { private static final long serialVersionUID = -3904288692735859811L; private static final StringCache stringCache = new StringCache() { @Override protected NormalizedString process(String input) { if (input == null) { return null; } return new NormalizedString(input); } }; private final String original; private final String normalized; private final boolean literal; private final int hashCode; private NormalizedString(String string) { String trimmed = string.trim(); if (trimmed.length() > 2 && trimmed.charAt(0) == '\'' && trimmed.charAt(trimmed.length() - 1) == '\'') { this.original = string.substring(1, string.length() - 1); this.normalized = original; this.hashCode = normalize(original).hashCode(); this.literal = true; } else { this.original = string; this.normalized = normalize(original); this.hashCode = normalized.hashCode(); this.literal = false; } } private String normalize(Object value) { String str = String.valueOf(value); str = str.trim().toLowerCase(); return str; } public boolean isLiteral() { return literal; } @Override public boolean equals(Object anObject) { if (anObject == this) { return true; } if (anObject == null) { return false; } if (anObject instanceof NormalizedString) { NormalizedString other = (NormalizedString) anObject; if (this.literal || other.literal) { return original.equals(other.original); } return this.normalized.equals(other.normalized); } if (literal) { return original.equals(String.valueOf(anObject)); } else { return normalized.equals(normalize(anObject)); } } @Override public int hashCode() { return hashCode; } @Override public int length() { return original.length(); } @Override public char charAt(int index) { return original.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return original.subSequence(start, end); } @Override public int compareTo(NormalizedString o) { if (o == this) { return 0; } if (this.literal || o.literal) { return original.compareTo(o.original); } return this.normalized.compareTo(o.normalized); } /** * Compares a {@code NormalizedString} against a {@code String} lexicographically. * @param o a plain {@code String} * @return the result of {@link String#compareTo(String)}. If this {@code NormalizedString} * is a literal, the original argument string will be compared. If this {@code NormalizedString} * is not a literal, the result will be from the comparison of the normalized content of both strings * (i.e. surrounding whitespaces and character case differences will be ignored). */ public int compareTo(String o) { return compareTo(valueOf(o)); } @Override public String toString() { return original; } /** * Creates a literal {@code NormalizedString}, meaning it will only match with * other {@code String} or {@code NormalizedString} if they have the exact same content * including character case and surrounding whitespaces. * * @param string the input {@code String} * @return the literal {@code NormalizedString} version of the given string. */ public static NormalizedString literalValueOf(String string) { if (string == null) { return null; } return stringCache.get('\'' + string + "\'"); } /** * Creates a non-literal {@code NormalizedString}, meaning it will match with * other {@code String} or {@code NormalizedString} regardless of different * including character case and surrounding whitespaces. * * If the input value is enclosed with single quotes, a literal {@code NormalizedString} * will be returned, as described in {@link #literalValueOf(String)} * * @param o the input object whose {@code String} representation will be used * @return the {@code NormalizedString} of the given object. */ public static NormalizedString valueOf(Object o) { if (o == null) { return null; } return stringCache.get(o.toString()); } /** * Creates a non-literal {@code NormalizedString}, meaning it will match with * other {@code String} or {@code NormalizedString} regardless of different * including character case and surrounding whitespaces. * * If the input string is enclosed with single quotes, a literal {@code NormalizedString} * will be returned, as described in {@link #literalValueOf(String)} * * @param string the input string * @return the {@code NormalizedString} of the given string. */ public static NormalizedString valueOf(String string) { if (string == null) { return null; } return stringCache.get(string); } /** * Converts a {@code NormalizedString} back to its original {@code String} representation * @param string the normalized string * @return the original string used to create the given normalized representation. */ public static String valueOf(NormalizedString string) { if (string == null) { return null; } return string.original; } /** * Converts a collection of plain strings into an array of {@code NormalizedString} * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static NormalizedString[] toArray(Collection args) { if (args == null) { throw new IllegalArgumentException("String collection cannot be null"); } NormalizedString[] out = new NormalizedString[args.size()]; Iterator it = args.iterator(); for (int i = 0; i < out.length; i++) { out[i] = valueOf(it.next()); } return out; } /** * Converts a collection of normalized strings into an array of {@code String} * @param args the normalized strings to convert back to to {@code String} * @return the {@code String} representations of all normalized strings. */ public static String[] toStringArray(Collection args) { if (args == null) { throw new IllegalArgumentException("String collection cannot be null"); } String[] out = new String[args.size()]; Iterator it = args.iterator(); for (int i = 0; i < out.length; i++) { out[i] = valueOf(it.next()); } return out; } /** * Converts multiple plain strings into an array of {@code NormalizedString}, ensuring * no duplicate {@code NormalizedString} elements exist, even if their original {@code String}s * are different. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static NormalizedString[] toUniqueArray(String... args) { notEmpty("Element array", args); NormalizedString[] out = toArray(args); NormalizedString[] duplicates = findDuplicates(out); if (duplicates.length > 0) { throw new IllegalArgumentException("Duplicate elements found: " + Arrays.toString(duplicates)); } return out; } /** * Converts multiple plain strings into an array of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static NormalizedString[] toArray(String... args) { if (args == null) { return null; } else if (args.length == 0) { return EMPTY_NORMALIZED_STRING_ARRAY; } NormalizedString[] out = new NormalizedString[args.length]; for (int i = 0; i < args.length; i++) { out[i] = valueOf(args[i]); } return out; } /** * Converts multiple normalized strings into an array of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the {@code String} representations of all input strings. */ public static String[] toArray(NormalizedString... args) { if (args == null) { return null; } else if (args.length == 0) { return EMPTY_STRING_ARRAY; } String[] out = new String[args.length]; for (int i = 0; i < args.length; i++) { out[i] = valueOf(args[i]); } return out; } private static > T getCollection(T out, String... args) { Collections.addAll(out, toArray(args)); return out; } private static > T getCollection(T out, Collection args) { Collections.addAll(out, toArray(args)); return out; } private static > T getCollection(T out, NormalizedString... args) { Collections.addAll(out, toArray(args)); return out; } private static > T getStringCollection(T out, Collection args) { Collections.addAll(out, toStringArray(args)); return out; } /** * Converts multiple plain strings into an {@code ArrayList} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static ArrayList toArrayList(String... args) { return getCollection(new ArrayList(), args); } /** * Converts multiple plain strings into an {@code ArrayList} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static ArrayList toArrayList(Collection args) { return getCollection(new ArrayList(), args); } /** * Converts multiple normalized strings into a {@code HashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static ArrayList toArrayListOfStrings(NormalizedString... args) { return getCollection(new ArrayList(), args); } /** * Converts multiple normalized strings into a {@code HashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static ArrayList toArrayListOfStrings(Collection args) { return getStringCollection(new ArrayList(), args); } /** * Converts multiple plain strings into a {@code TreeSet} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static TreeSet toTreeSet(String... args) { return getCollection(new TreeSet(), args); } /** * Converts multiple plain strings into a {@code TreeSet} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static TreeSet toTreeSet(Collection args) { return getCollection(new TreeSet(), args); } /** * Converts multiple normalized strings into a {@code HashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static TreeSet toTreeSetOfStrings(NormalizedString... args) { return getCollection(new TreeSet(), args); } /** * Converts multiple normalized strings into a {@code HashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static TreeSet toTreeSetOfStrings(Collection args) { return getStringCollection(new TreeSet(), args); } /** * Converts multiple plain strings into a {@code HashSet} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static HashSet toHashSet(String... args) { return getCollection(new HashSet(), args); } /** * Converts multiple plain strings into a {@code HashSet} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static HashSet toHashSet(Collection args) { return getCollection(new HashSet(), args); } /** * Converts multiple normalized strings into a {@code HashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static HashSet toHashSetOfStrings(NormalizedString... args) { return getCollection(new HashSet(), args); } /** * Converts multiple normalized strings into a {@code HashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static HashSet toHashSetOfStrings(Collection args) { return getStringCollection(new HashSet(), args); } /** * Converts multiple plain strings into a {@code LinkedHashSet} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static LinkedHashSet toLinkedHashSet(String... args) { return getCollection(new LinkedHashSet(), args); } /** * Converts multiple plain strings into a {@code LinkedHashSet} of {@code NormalizedString}. * * @param args the strings to convert to {@code NormalizedString} * @return the {@code NormalizedString} representations of all input strings. */ public static LinkedHashSet toLinkedHashSet(Collection args) { return getCollection(new LinkedHashSet(), args); } /** * Converts multiple normalized strings into a {@code LinkedHashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static LinkedHashSet toLinkedHashSetOfStrings(NormalizedString... args) { return getCollection(new LinkedHashSet(), args); } /** * Converts multiple normalized strings into a {@code LinkedHashSet} of {@code String}. * * @param args the normalized strings to convert to {@code String} * @return the original {@code String}s of all input normalized strings. */ public static LinkedHashSet toLinkedHashSetOfStrings(Collection args) { return getStringCollection(new LinkedHashSet(), args); } /** * Returns the literal representation of this {@code NormalizedString}, meaning it will only match with * other {@code String} or {@code NormalizedString} if they have the exact same content * including character case and surrounding whitespaces. * * @return the literal representation of the current {@code NormalizedString} */ public NormalizedString toLiteral() { if (literal) { return this; } return literalValueOf(this.original); } /** * Analyzes a group of NormalizedString to identify any instances whose normalized content will generate * clashes. Any clashing entries will be converted to their literal counterparts (using {@link #toLiteral()}), * making it possible to identify one from the other. * * @param strings a group of identifiers that may contain ambiguous entries if their character case or surrounding whitespaces is not considered. * This array will be modified. * * @return the input string array, with {@code NormalizedString} literals in the positions where clashes would originally occur. */ public static NormalizedString[] toIdentifierGroupArray(NormalizedString[] strings) { identifyLiterals(strings); return strings; } /** * Analyzes a group of String to identify any instances whose normalized content will generate * clashes. Any clashing entries will be converted to their literal counterparts (using {@link #toLiteral()}), * making it possible to identify one from the other. * * @param strings a group of identifiers that may contain ambiguous entries if their character case or surrounding whitespaces is not considered. * * * @return a {@code NormalizedString} array with literals in the positions where clashes would originally occur. */ public static NormalizedString[] toIdentifierGroupArray(String[] strings) { NormalizedString[] out = toArray(strings); identifyLiterals(out, false, false); return out; } /** * Analyzes a group of NormalizedString to identify any instances whose normalized content will generate * clashes. Any clashing entries will be converted to their literal counterparts (using {@link #toLiteral()}), * making it possible to identify one from the other. * * @param strings a group of identifiers that may contain ambiguous entries if their character case or surrounding whitespaces is not considered. * This array will be modified. * * @return {@code true} if any entry has been modified to be a literal, otherwise {@code false} * */ public static boolean identifyLiterals(NormalizedString[] strings) { return identifyLiterals(strings, false, false); } /** * Analyzes a group of NormalizedString to identify any instances whose normalized content will generate * clashes. Any clashing entries will be converted to their literal counterparts (using {@link #toLiteral()}), * making it possible to identify one from the other. * * @param strings a group of identifiers that may contain ambiguous entries if their character case or surrounding whitespaces is not considered. * This array will be modified. * * @param lowercaseIdentifiers flag indicating that identifiers are stored in lower case (for compatibility with databases). * If a string has a uppercase character, it means it must become a literal. * @param uppercaseIdentifiers flag indicating that identifiers are stored in upper case (for compatibility with databases). * If a string has a lowercase character, it means it must become a literal. * * @return {@code true} if any entry has been modified to be a literal, otherwise {@code false} * */ public static boolean identifyLiterals(NormalizedString[] strings, boolean lowercaseIdentifiers, boolean uppercaseIdentifiers) { if (strings == null) { return false; } TreeMap normalizedMap = new TreeMap(); boolean modified = false; for (int i = 0; i < strings.length; i++) { NormalizedString string = strings[i]; if (string == null || string.isLiteral()) { continue; } if (shouldBeLiteral(string.original, lowercaseIdentifiers, uppercaseIdentifiers)) { strings[i] = NormalizedString.literalValueOf(string.original); continue; } Object[] clashing = normalizedMap.get(string); if (clashing != null && !string.original.equals(((NormalizedString) clashing[0]).original)) { strings[i] = NormalizedString.literalValueOf(string.original); strings[(Integer) clashing[1]] = ((NormalizedString) clashing[0]).toLiteral(); modified = true; } else { normalizedMap.put(string, new Object[]{string, i}); } } return modified; } private static boolean shouldBeLiteral(String string, boolean lowercaseIdentifiers, boolean uppercaseIdentifiers) { if (lowercaseIdentifiers || uppercaseIdentifiers) { for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); if ((uppercaseIdentifiers && !Character.isUpperCase(ch)) || (lowercaseIdentifiers && !Character.isLowerCase(ch))) { return true; } } } return false; } /** * Returns the internal string cache to allow users to tweak its size limit or clear it when appropriate * @return the string cache used to store {@code NormalizedString} instances associated with their original {@code String}. */ public static StringCache getCache(){ return stringCache; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ParserOutput.java000066400000000000000000000325511475274123300330230ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.input.*; import java.util.*; /** * The ParserOutput is the component that manages records parsed by {@link AbstractParser} and their values. * * It is solely responsible for deciding when: *

    *
  • parsed records should be reordered according to the fields selected in {@link CommonSettings}
  • *
  • characters and values parsed in {@link AbstractParser#parseRecord()} should be retained or discarded
  • *
  • input headers should be loaded from the records parsed in {@link AbstractParser#parseRecord()} or from {@link CommonSettings#getHeaders()}
  • *
* * Implementations of this class are made available to concrete parser implementations of {@link AbstractParser}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see CommonSettings */ public class ParserOutput { /** * Keeps track of the current column being parsed in the input. * Calls to {@link ParserOutput#valueParsed} and {@link ParserOutput#emptyParsed} will increase the column count. * This value is reset to zero after a row is parsed. */ protected int column = 0; /** * Stores the values parsed for a record. */ protected final String[] parsedValues; /** *

Stores (shared) references to {@link CharAppender} for each potential column (as given by {@link CommonSettings#getMaxColumns()}). *

Fields that are not selected will receive an instance of {@link NoopCharAppender} so all parser calls in {@link AbstractParser#parseRecord()} to {@link ParserOutput#appender} will do nothing. *

Selected fields (given by {@link CommonParserSettings}) will receive a functional {@link CharAppender}. */ private final CharAppender[] appenders; protected final CommonParserSettings settings; private final boolean skipEmptyLines; private final String nullValue; /** *

The appender available to parsers for accumulating characters read from the input. *

This attribute is assigned to different instances of CharAppender during parsing process, namely, * a (potentially) different CharAppender for each parsed column, taken from * {@link ParserOutput#appenders}[{@link ParserOutput#column}] */ public CharAppender appender; private final CharAppender appenderInstance; private boolean columnsToExtractInitialized; private boolean columnsReordered; private boolean columnReorderingEnabledSetting; private String[] headerStrings; private NormalizedString[] headers; private int[] selectedIndexes; private long currentRecord; public boolean trim = false; public final Deque pendingRecords = new LinkedList(); /** * Headers parsed from the input when {@link CommonParserSettings#headerExtractionEnabled} is {@code true}, * irrespective of any user-provided headers in {@link CommonParserSettings#getHeaders()} */ String[] parsedHeaders; private final AbstractParser parser; /** * Initializes the ParserOutput with the configuration specified in {@link CommonParserSettings} * * @param settings the parser configuration */ public ParserOutput(CommonParserSettings settings) { this(null, settings); } /** * Initializes the ParserOutput with the configuration specified in {@link CommonParserSettings} * * @param parser the parser whose output will be managed by this class. * @param settings the parser configuration */ public ParserOutput(AbstractParser parser, CommonParserSettings settings) { this.parser = parser; this.appenderInstance = settings.newCharAppender(); this.appender = appenderInstance; this.parsedValues = new String[settings.getMaxColumns()]; this.appenders = new CharAppender[settings.getMaxColumns() + 1]; Arrays.fill(appenders, appender); this.settings = settings; this.skipEmptyLines = settings.getSkipEmptyLines(); this.nullValue = settings.getNullValue(); this.columnsToExtractInitialized = false; this.currentRecord = 0; if (settings.isHeaderExtractionEnabled() && parser != null) { parser.ignoreTrailingWhitespace = false; parser.ignoreLeadingWhitespace = false; } if (settings.getHeaders() != null) { initializeHeaders(); } this.columnReorderingEnabledSetting = settings.isColumnReorderingEnabled(); } protected void initializeHeaders() { columnsReordered = false; selectedIndexes = null; this.appender = appenderInstance; Arrays.fill(appenders, appender); if (column > 0) { //we only initialize headers from a parsed row if it is not empty parsedHeaders = new String[column]; System.arraycopy(parsedValues, 0, parsedHeaders, 0, column); } boolean usingParsedHeaders = false; this.headers = NormalizedString.toIdentifierGroupArray(settings.getHeaders()); if (headers != null) { headers = headers.clone(); } else if (column > 0) { //we only initialize headers from a parsed row if it is not empty headers = NormalizedString.toIdentifierGroupArray(parsedHeaders.clone()); usingParsedHeaders = true; } if (parser != null) { parser.ignoreTrailingWhitespace = settings.getIgnoreTrailingWhitespaces(); parser.ignoreLeadingWhitespace = settings.getIgnoreLeadingWhitespaces(); if (usingParsedHeaders) { parser.initialize(); } } if (usingParsedHeaders) { for (int i = 0; i < headers.length; i++) { NormalizedString header = headers[i]; if (header != null && !header.isLiteral()) { if (settings.getIgnoreLeadingWhitespaces()) { if (settings.getIgnoreTrailingWhitespaces()) { headers[i] = NormalizedString.valueOf(headers[i].toString().trim()); } else { headers[i] = NormalizedString.valueOf(ArgumentUtils.trim(headers[i].toString(), true, false)); } } else if (settings.getIgnoreTrailingWhitespaces()) { headers[i] = NormalizedString.valueOf(ArgumentUtils.trim(headers[i].toString(), false, true)); } } } } columnsToExtractInitialized = true; initializeColumnsToExtract(headers); } /** * Gets all values parsed in the {@link ParserOutput#parsedValues} array * * @return the sequence of parsed values in a record. */ public String[] rowParsed() { if (!pendingRecords.isEmpty()) { return pendingRecords.poll(); } // some values were parsed. Let's return them if (column > 0) { // identifies selected columns and headers (in the first non-empty row) if (!columnsToExtractInitialized) { initializeHeaders(); //skips the header row. We want to use the headers defined in the settings. if (settings.isHeaderExtractionEnabled()) { Arrays.fill(parsedValues, null); column = 0; this.appender = appenders[0]; return null; } else if (!columnsReordered && selectedIndexes != null) { String[] out = new String[column]; for (int i = 0; i < selectedIndexes.length; i++) { int index = selectedIndexes[i]; if (index < column) { out[index] = parsedValues[index]; } } column = 0; return out; } } currentRecord++; if (columnsReordered) { if (selectedIndexes.length == 0) { column = 0; return ArgumentUtils.EMPTY_STRING_ARRAY; } String[] reorderedValues = new String[selectedIndexes.length]; for (int i = 0; i < selectedIndexes.length; i++) { int index = selectedIndexes[i]; if (index >= column || index == -1) { reorderedValues[i] = nullValue; } else { reorderedValues[i] = parsedValues[index]; } } column = 0; this.appender = appenders[0]; return reorderedValues; } else { int last = columnReorderingEnabledSetting ? column : column < headers.length ? headers.length : column; String[] out = new String[last]; System.arraycopy(parsedValues, 0, out, 0, column); column = 0; this.appender = appenders[0]; return out; } } else if (!skipEmptyLines) { //no values were parsed, but we are not skipping empty lines if (!columnsToExtractInitialized) { initializeHeaders(); } currentRecord++; if (columnsReordered) { if (selectedIndexes.length == 0) { return ArgumentUtils.EMPTY_STRING_ARRAY; } String[] out = new String[selectedIndexes.length]; Arrays.fill(out, nullValue); return out; } return new String[]{nullValue}; } // no values were parsed and we do not care about empty lines. return null; } FieldSelector getFieldSelector() { return settings.getFieldSelector(); } /** * Initializes the sequence of selected fields, if any. * * @param values a sequence of values that represent the headers of the input. This can be either a parsed record or the headers as defined in {@link CommonSettings#getHeaders()} */ private void initializeColumnsToExtract(NormalizedString[] values) { FieldSelector selector = settings.getFieldSelector(); if (selector != null) { selectedIndexes = selector.getFieldIndexes(values); if (selectedIndexes != null) { Arrays.fill(appenders, NoopCharAppender.getInstance()); for (int i = 0; i < selectedIndexes.length; i++) { int index = selectedIndexes[i]; if (index != -1) { appenders[index] = appender; } } columnsReordered = settings.isColumnReorderingEnabled(); int length = values == null ? selectedIndexes.length : values.length; if (!columnsReordered && length < appenders.length && !(selector instanceof FieldIndexSelector)) { Arrays.fill(appenders, length, appenders.length, appender); } appender = appenders[0]; } } } public String[] getHeaderAsStringArray() { if (headerStrings == null) { headerStrings = NormalizedString.toArray(getHeaders()); } return headerStrings; } /** * Returns the sequence of values that represent the headers each field in the input. This can be either a parsed record or the headers as defined in {@link CommonSettings#getHeaders()} * * @return the headers each field in the input */ public NormalizedString[] getHeaders() { if (parser != null) { parser.extractHeadersIfRequired(); } if (this.headers == null) { this.headers = NormalizedString.toIdentifierGroupArray(settings.getHeaders()); } return this.headers; } /** * Returns the selected indexes of all fields as defined in {@link CommonSettings}. Null if no fields were selected. * * @return the selected indexes of all fields as defined in {@link CommonSettings}. Null if no fields were selected. */ public int[] getSelectedIndexes() { return this.selectedIndexes; } /** * Indicates whether fields selected using the field selection methods (in {@link CommonSettings}) are being reordered. * * @return

false if no fields were selected or column reordering has been disabled in {@link CommonParserSettings#isColumnReorderingEnabled()} *

true if fields were selected and column reordering has been enabled in {@link CommonParserSettings#isColumnReorderingEnabled()} */ public boolean isColumnReorderingEnabled() { return columnsReordered; } /** * Returns the position of the current parsed value * * @return the position of the current parsed value */ public int getCurrentColumn() { return column; } /** * Adds a nullValue (as specified in {@link CommonSettings#getNullValue()}) to the output and prepares the next position in the record to receive more values. */ public void emptyParsed() { this.parsedValues[column++] = nullValue; this.appender = appenders[column]; } /** * Adds the accumulated value in the appender object to the output and prepares the next position in the record to receive more values. */ public void valueParsed() { if (trim) { appender.updateWhitespace(); } this.parsedValues[column++] = appender.getAndReset(); this.appender = appenders[column]; } /** * Adds a value processed externally to the output and prepares the next position in the record to receive more values * * @param value the value to be added to the current record position. */ public void valueParsed(String value) { this.parsedValues[column++] = value; this.appender = appenders[column]; } /** * Returns the current record index. The number returned here reflects the number of actually parsed and valid records sent to the output of {@link ParserOutput#rowParsed}. * * @return the current record index. */ public long getCurrentRecord() { return currentRecord; } /** * Discards the values parsed so far */ public final void discardValues() { column = 0; this.appender = appenders[0]; } /** * Resets the parser output and prepares for a new parsing process. */ final void reset() { this.columnsToExtractInitialized = false; this.currentRecord = 0; this.column = 0; this.headers = null; this.headerStrings = null; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ParsingContext.java000077500000000000000000000134621475274123300333210ustar00rootroot00000000000000/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; import com.univocity.parsers.common.processor.*; import java.util.*; /** * Parsing context information available to instances of {@link RowProcessor}. * *

The ParsingContext can be used to control and to obtain information about the parsing process. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see RowProcessor * @see DefaultParsingContext */ public interface ParsingContext extends Context { /** * Returns the file headers that identify each parsed record. * *

If the headers are extracted from the input (i.e. {@link CommonParserSettings#isHeaderExtractionEnabled()} == true), then these values will be returned. *

If no headers are extracted from the input, then the configured headers in {@link CommonSettings#getHeaders()} will be returned. * Note that the user-provided headers will override the header list parsed from the input, if any. To obtain the * original list of headers found in the input use {@link ParsingContext#parsedHeaders()} * * @return the headers used to identify each record parsed from the input. * * @see com.univocity.parsers.common.CommonParserSettings * @see com.univocity.parsers.common.CommonSettings */ String[] headers(); /** * Returns the indexes of each field extracted from the input when fields are selected in the parser settings (i.e. using {@link CommonSettings#selectFields} and friends). * *

The indexes are relative to their original position in the input. *

For example, if the input has the fields "A, B, C, D", and the selected fields are "A, D", then the extracted field indexes will return [0, 3] * *

If no fields were selected, then this method will return null. This means all fields are being parsed. * * @return The indexes of each selected field; null if no fields were selected. * * @see com.univocity.parsers.common.CommonSettings */ int[] extractedFieldIndexes(); /** * Indicates whether selected fields (using {@link CommonSettings#selectFields} and friends) are being reordered. * *

If columns are reordered, each parsed record will contain values only for the selected fields, as specified by {@link CommonParserSettings#isColumnReorderingEnabled} * * @return true if the parsed records are being reordered by the parser, false otherwise * * @see com.univocity.parsers.common.CommonParserSettings * @see com.univocity.parsers.common.CommonSettings */ boolean columnsReordered(); /** * Returns the current line of text being processed by the parser * * @return current line of text being processed by the parser */ long currentLine(); /** * Returns the index of the last char read from the input so far. * * @return the index of the last char read from the input so far. */ long currentChar(); /** * Skips a given number of lines from the current position. * * @param lines the number of lines to be skipped. */ void skipLines(long lines); /** * Returns the headers parsed from the input, if and only if {@link CommonParserSettings#headerExtractionEnabled} is {@code true}. * The result of this method won't return the list of headers manually set by the user in {@link CommonParserSettings#getHeaders()}. * Use the {@link #headers()} method instead to obtain the headers actually used by the parser. * * @return the headers parsed from the input, when {@link CommonParserSettings#headerExtractionEnabled} is {@code true}. */ String[] parsedHeaders(); /** * Returns a String with the input character sequence parsed to produce the current record. * * @return the text content parsed for the current input record. */ String currentParsedContent(); /** * Returns the length of the character sequence parsed to produce the current record. * @return the length of the text content parsed for the current input record */ int currentParsedContentLength(); /** * Returns a String with the input character sequence accumulated on a field before {@link TextParsingException} occurred. * * @return the text content parsed for the current field of the current input record at the time of the error. */ String fieldContentOnError(); /** * Returns all comments collected by the parser so far. * An empty map will be returned if {@link CommonParserSettings#isCommentCollectionEnabled()} evaluates to {@code false}. * * @return a map containing the line numbers and comments found in each. */ Map comments(); /** * Returns the last comment found in the input. * {@code null} will be returned if {@link CommonParserSettings#isCommentCollectionEnabled()} is evaluated to {@code false}. * * @return the last comment found in the input. */ String lastComment(); /** * Returns the line separator characters used to separate individual records when parsing. This could be the line * separator defined in the {@link Format#getLineSeparator()} configuration, or the line separator sequence * identified automatically when {@link CommonParserSettings#isLineSeparatorDetectionEnabled()} evaluates to {@code true}. * * @return the line separator sequence. Might contain one or two characters. */ char[] lineSeparator(); } ParsingContextSnapshot.java000066400000000000000000000052101475274123300347470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.util.*; /** * A snapshot of a {@link ParsingContext} which retains copies of variable attributes of a given {@link ParsingContext} to * store the state of the parsing process at a given point in time. All runtime operations such as {@link #stop()} * will still work and affect the current parsing process. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class ParsingContextSnapshot extends ParsingContextWrapper { private final long currentLine; private final long currentChar; private final Map comments; private final String lastComment; private final int currentColumn; private final String currentParsedContent; private final long currentRecord; /** * Creates a snapshot of a given {@link Context} * * @param context the context object whose variable attributes will be copied over. */ public ParsingContextSnapshot(ParsingContext context) { super(context); currentLine = context.currentLine(); currentChar = context.currentChar(); comments = context.comments() == Collections.EMPTY_MAP ? Collections.emptyMap() : Collections.unmodifiableMap(context.comments()); lastComment = context.lastComment(); currentColumn = context.currentColumn(); currentParsedContent = context.currentParsedContent(); currentRecord = context.currentRecord(); } @Override public long currentLine() { return currentLine; } @Override public long currentChar() { return currentChar; } @Override public Map comments() { return comments; } @Override public String lastComment() { return lastComment; } @Override public int currentColumn() { return currentColumn; } @Override public String currentParsedContent() { return currentParsedContent; } @Override public long currentRecord() { return currentRecord; } } ParsingContextWrapper.java000066400000000000000000000042551475274123300346000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common; import com.univocity.parsers.common.record.*; import java.util.*; /** * A simple a wrapper for a {@link ParsingContext}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ParsingContextWrapper extends ContextWrapper implements ParsingContext { /** * Wraps a {@link ParsingContext}. * @param context the parsingContext object to be wrapped. */ public ParsingContextWrapper(ParsingContext context) { super(context); } @Override public long currentLine() { return context.currentLine(); } @Override public long currentChar() { return context.currentChar(); } @Override public void skipLines(long lines) { context.skipLines(lines); } @Override public String currentParsedContent() { return context.currentParsedContent(); } @Override public int currentParsedContentLength() { return context.currentParsedContentLength(); } @Override public Map comments() { return context.comments(); } @Override public String lastComment() { return context.lastComment(); } @Override public String[] parsedHeaders() { return context.parsedHeaders(); } @Override public char[] lineSeparator() { return context.lineSeparator(); } @Override public String fieldContentOnError() { return context.fieldContentOnError(); } @Override public String[] selectedHeaders() { return context.selectedHeaders(); } @Override public Record toRecord(String[] row) { return context.toRecord(row); } } ProcessorErrorHandler.java000066400000000000000000000062751475274123300345620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.common.processor.core.*; /** * The {@code ProcessorErrorHandler} is a callback used by the parser/writer to handle non-fatal {@link DataProcessingException}s that may occur when * processing rows using a {@link Processor} or {@link RowWriterProcessor}. This leaves the responsibility of error handling to the user. If the user does not * rethrow the {@code DataProcessingException}, the parsing/writing process won't stop and will proceed normally. * *

This error handler WILL NOT handle {@code TextParsingException}s or other errors that prevent the parser to reliably extract rows from a given input, * or the writer to proceed writing data.

* *

When parsing, the {@link #handleError(DataProcessingException, Object[], Context)} method will be called only when a valid record has been parsed, but the * subsequent processing executed by a {@link Processor} fails.

* *

When writing, the {@link #handleError(DataProcessingException, Object[], Context)} method will be called only when a using * the {@link AbstractWriter#processRecord(Object)} methods, and {@link RowWriterProcessor} fails to execute.

* * @see RowProcessor * @see RowWriterProcessor * @see DataProcessingException * @see TextParsingException * @see AbstractParser * @see AbstractWriter * @see CommonSettings * @see Context * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface ProcessorErrorHandler { /** * Handles non-fatal instances of {@code DataProcessingException} that are thrown by a {@link Processor} while processing a record parsed from the input, * or from a {@link RowWriterProcessor} when processing records for writing. * * @param error the exception thrown during the processing an input record. Rethrow the error to abort the parsing process. * When parsing, you can also invoke {@link ParsingContext#stop()} to stop the parser silently. * @param inputRow the record that could not be processed. When writing, the original input object (i.e. {@code null}, java bean or object array) will be sent by the writer. * @param context the parsing context with information about the state of the parser at the time the error occurred. Will be null when writing. */ void handleError(DataProcessingException error, Object[] inputRow, T context); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/ResultIterator.java000066400000000000000000000024171475274123300333340ustar00rootroot00000000000000/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.util.*; /** * An {@link Iterator} that provides the current parsing context * through the {@link #getContext()} method * * @author Univocity Software Pty Ltd - dev@univocity.com */ public interface ResultIterator extends Iterator { /** * Returns the current parsing {@link Context}, if available * * @return the contextual object with information about an ongoing parsing process */ C getContext(); } RetryableErrorHandler.java000066400000000000000000000105231475274123300345230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; /** * A {@link ProcessorErrorHandler} implementation that gives the user a chance to provide a default value for * columns that could not be processed due to an exception, through the method {@link #setDefaultValue(Object)}. * This must be called from within the implementation of the * {@link #handleError(DataProcessingException, Object[], Context)} method, and will prevent the record from being * discarded. The value provided by the user will be assigned to the problematic input row, at the column defined by * {@link DataProcessingException#getColumnIndex()}. * * NOTE:If the column index is {@code < 0}, then the record can't be * salvaged and it will be discarded regardless of the user calling {@link #setDefaultValue(Object)} or not. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see DataProcessingException * @see TextParsingException * @see AbstractParser * @see AbstractWriter * @see CommonSettings * @see Context */ public abstract class RetryableErrorHandler implements ProcessorErrorHandler { private Object defaultValue; private boolean skipRecord = true; /** * Assigns a default value to be assigned to the problematic column that raised the current {@link DataProcessingException}. * * The current column is available from the exception itself, i.e. {@link DataProcessingException#getColumnIndex()}. * * NOTE:If the column index is {@code < 0}, then the record can't be * salvaged and it will be discarded regardless of the user calling {@link #setDefaultValue(Object)} or not. * * @param defaultValue the value to be used for the current column. It will be discarded after handling the current * {@link DataProcessingException}. */ public final void setDefaultValue(Object defaultValue) { this.defaultValue = defaultValue; keepRecord(); } /** * Ignores the {@link DataProcessingException} and instructs the parser/writer to continue processing the record. */ public final void keepRecord(){ skipRecord = false; } /** * Returns the default value to be assigned to the problematic column that raised the current {@link DataProcessingException}. * * The current column is available from the exception itself, i.e. {@link DataProcessingException#getColumnIndex()}. * * NOTE:If the column index is {@code < 0}, then the record can't be * salvaged and it will be discarded regardless of the user calling {@link #setDefaultValue(Object)} or not. * * @return the value to be used for the current column. It will be discarded after handling the current * {@link DataProcessingException}. */ public final Object getDefaultValue() { return defaultValue; } /** * Prepares this error handler to be executed. This is called automatically by the library prior to invoking * method {@link #handleError(DataProcessingException, Object[], Context)} */ final void prepareToRun() { skipRecord = true; defaultValue = null; } /** * Flag indicating whether the current record will be skipped. Returns {@code true} by default unless * the user invokes {@link #setDefaultValue(Object)} from within the {@link #handleError(DataProcessingException, Object[], Context)} * method implementation, in which case the current record will continue to be processed. * * @return {@code true} if the record originating the current {@link DataProcessingException} should be skipped, * otherwise {@code false} */ public final boolean isRecordSkipped() { return skipRecord; } } RowProcessorErrorHandler.java000066400000000000000000000044701475274123300352450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.common.processor.*; /** * The {@code RowProcessorErrorHandler} is a callback used by the parser/writer to handle non-fatal {@link DataProcessingException}s that may occur when * processing rows using a {@link RowProcessor} or {@link RowWriterProcessor}. This leaves the responsibility of error handling to the user. If the user does not * rethrow the {@code DataProcessingException}, the parsing/writing process won't stop and will proceed normally. * *

This error handler WILL NOT handle {@code TextParsingException}s or other errors that prevent the parser to reliably extract rows from a given input, * or the writer to proceed writing data.

* *

When parsing, the {@link #handleError(DataProcessingException, Object[], Context)} method will be called only when a valid record has been parsed, but the * subsequent processing executed by a {@link RowProcessor} fails.

* *

When writing, the {@link #handleError(DataProcessingException, Object[], Context)} method will be called only when a using * the {@link AbstractWriter#processRecord(Object)} methods, and {@link RowWriterProcessor} fails to execute.

* * @see RowProcessor * @see RowWriterProcessor * @see DataProcessingException * @see TextParsingException * @see AbstractParser * @see AbstractWriter * @see CommonSettings * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface RowProcessorErrorHandler extends ProcessorErrorHandler { } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/StringCache.java000066400000000000000000000115221475274123300325330ustar00rootroot00000000000000/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; /** * A simple cache of values associated with strings. It is built to simply prevent generating the same value over * and over again over a short period of time. Once its size limit is reached, the cache will be fully cleared. * Do not use this as a general purpose caching solution. This meant for storing values that can be cheaply produced * and re-generating them every now and then won't incur in any major performance impact. * * @param the type of entry to be stored in the cache */ public abstract class StringCache { private static final int DEFAULT_SIZE_LIMIT = 16384; private static final int DEFAULT_MAX_STRING_LENGTH = 0; private final Map> stringCache = new ConcurrentHashMap>(); private int sizeLimit = DEFAULT_SIZE_LIMIT; private int maxStringLength = DEFAULT_MAX_STRING_LENGTH; /** * Converts a given string to a value * * @param input the input to be converted and stored in the cache * @return the value generated from the given string/ */ protected abstract T process(String input); /** * Tests whether the cache contains the given key * * @param input a string that might have a value associated to it. * @return {@code true} if the cache contains (or contained) a value associated with the given key. */ public boolean containsKey(String input) { return stringCache.containsKey(input); } /** * Returns the size limit of this string cache. Defaults to 16,384. For simplicity, when * this limit is reached, the entire cache is cleared. * * @return the maximum number of entries that can be stored in this string cache. */ public int getSizeLimit() { return sizeLimit; } /** * Defines the size limit of this string cache (16,384 by default). For simplicity, when * this limit is reached, the entire cache is cleared. * * @param sizeLimit the maximum number of entries that can be stored in this string cache. */ public void setSizeLimit(int sizeLimit) { if (sizeLimit <= 0) { sizeLimit = DEFAULT_SIZE_LIMIT; } this.sizeLimit = sizeLimit; } /** * Associates a value to a string * * @param input the string to be associated with a given value * @param value the value associated with the given string */ public void put(String input, T value) { if (input == null || input.length() > maxStringLength) { return; } if (stringCache.size() >= sizeLimit) { stringCache.clear(); } stringCache.put(input, new SoftReference(value)); } /** * Returns the value associated with the given string. If it doesn't exist, * or if it has been evicted, a value will be populated using {@link #process(String)} * * @param input the string whose associated value will be returned * @return the value associated with the given string. */ public T get(String input) { if (input == null || (maxStringLength > 0 && input.length() > maxStringLength)) { return null; } SoftReference ref = stringCache.get(input); T out; if (ref == null || ref.get() == null) { out = process(input); ref = new SoftReference(out); stringCache.put(input, ref); } else { out = ref.get(); } return out; } /** * Removes all entries stored in this cache. */ public void clear() { stringCache.clear(); } /** * Returns the maximum length a {@code String} key can have to be used as a key in this cache. * If the {@code String} length exceeds this limit, the value associated with it won't be cached. * Defaults to 1024 * * @return the maximum length a {@code String} key can have */ public int getMaxStringLength() { return maxStringLength; } /** * Returns the maximum length a {@code String} key can have to be used as a key in this cache. * If the {@code String} length exceeds this limit, the value associated with it won't be cached. * Defaults to 1024 * * @param maxStringLength the maximum length a {@code String} key can have */ public void setMaxStringLength(int maxStringLength) { this.maxStringLength = maxStringLength; } } TextParsingException.java000066400000000000000000000126151475274123300344150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/** * **************************************************************************** * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.univocity.parsers.common; /** * Exception type used provide information about any issue that might happen while parsing from a given input. *

It generally provides location information about where in the input a parsing error occurred. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class TextParsingException extends AbstractException { private static final long serialVersionUID = 1410975527141918214L; private long lineIndex; private long charIndex; private long recordNumber; private int columnIndex; private String content; private String[] headers; protected int[] extractedIndexes; /** * Creates a new exception with information about an error that occurred when parsing some input. * * @param context the context of the parser when an error occurred * @param message message with details about the error * @param cause the cause of the error */ public TextParsingException(Context context, String message, Throwable cause) { super(message, cause); setContext(context); } protected void setContext(Context context) { if (context instanceof ParsingContext) { setParsingContext((ParsingContext) context); } else { setParsingContext(null); } this.columnIndex = context == null ? -1 : context.currentColumn(); this.recordNumber = context == null ? -1L : context.currentRecord(); if (this.headers == null) { this.headers = context == null ? null : context.headers(); } this.extractedIndexes = context == null ? null : context.extractedFieldIndexes(); } private void setParsingContext(ParsingContext parsingContext) { this.lineIndex = parsingContext == null ? -1L : parsingContext.currentLine(); this.charIndex = parsingContext == null ? '\0' : parsingContext.currentChar(); this.content = parsingContext == null ? null : parsingContext.fieldContentOnError(); } /** * Creates a new exception with information about an error that occurred when parsing some input. * * @param context the context of the parser when an error occurred * @param message message with details about the error */ public TextParsingException(ParsingContext context, String message) { this(context, message, null); } /** * Creates a new exception with information about an error that occurred when parsing some input. * * @param context the context of the parser when an error occurred * @param cause the cause of the error */ public TextParsingException(ParsingContext context, Throwable cause) { this(context, cause != null ? cause.getMessage() : null, cause); } /** * Creates a new exception with information about an error that occurred when parsing some input. * * @param context the context of the parser when an error occurred */ public TextParsingException(ParsingContext context) { this(context, null, null); } @Override protected String getErrorDescription() { return "Error parsing input"; } @Override protected String getDetails() { String details = ""; details = printIfNotEmpty(details, "line", lineIndex); details = printIfNotEmpty(details, "column", columnIndex); details = printIfNotEmpty(details, "record", recordNumber); details = charIndex == 0 ? details : printIfNotEmpty(details, "charIndex", charIndex); details = printIfNotEmpty(details, "headers", headers); details = printIfNotEmpty(details, "content parsed", restrictContent(content)); return details; } /** * Returns the record number when the exception occurred. * * @return the record number when the exception occurred. */ public long getRecordNumber() { return recordNumber; } /** * Returns the column index where the exception occurred. * * @return the column index where the exception occurred. */ public int getColumnIndex() { return columnIndex; } /** * Returns the line number where the exception occurred. * * @return the line number where the exception occurred. */ public long getLineIndex() { return lineIndex; } /** * Returns the location of the last character read from before the error occurred. * * @return the location of the last character read from before the error occurred. */ public long getCharIndex() { return charIndex; } /** * Returns the last chunk of content parsed before the error took place * * @return the last chunk of content parsed before the error took place */ public final String getParsedContent() { if (errorContentLength == 0) { return null; } return content; } /** * Returns the headers processed from the input, if any. * * @return the headers processed from the input, if any. */ public final String[] getHeaders() { return headers; } } TextWritingException.java000066400000000000000000000132541475274123300344350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; /** * Exception type used provide information about any issue that might happen while writing to a given output. * *

It generally provides location and data information in case of a writing failure. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class TextWritingException extends AbstractException { private static final long serialVersionUID = 7198462597717255519L; private final long recordCount; private final Object[] recordData; private final String recordCharacters; /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param message message with details about the error * @param recordCount the number of records written until the error occurred * @param row the input row that was being written when the error occurred * @param recordCharacters the characters already written to the output record. * @param cause the cause of the error */ private TextWritingException(String message, long recordCount, Object[] row, String recordCharacters, Throwable cause) { super(message, cause); this.recordCount = recordCount; this.recordData = row; this.recordCharacters = recordCharacters; } /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param message message with details about the error * @param recordCount the number of records written until the error occurred * @param recordCharacters the characters already written to the output record. * @param cause the cause of the error */ public TextWritingException(String message, long recordCount, String recordCharacters, Throwable cause) { this(message, recordCount, null, recordCharacters, cause); } /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param message message with details about the error * @param recordCount the number of records written until the error occurred * @param row the input row that was being written when the error occurred * @param cause the cause of the error */ public TextWritingException(String message, long recordCount, Object[] row, Throwable cause) { this(message, recordCount, row, null, cause); } /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param message message with details about the error */ public TextWritingException(String message) { this(message, 0, null, null, null); } /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param cause the cause of the error */ public TextWritingException(Throwable cause) { this(cause != null ? cause.getMessage() : null, 0, null, null, cause); } /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param message message with details about the error * @param line index of the line being written to the output when the error occurred * @param row the input row that was being written when the error occurred */ public TextWritingException(String message, long line, Object[] row) { this(message, line, row, null); } /** * Creates a new exception with information about an error that occurred when writing data to some output. * * @param message message with details about the error * @param line index of the line being written to the output when the error occurred * @param recordCharacters the characters already written to the output record. */ public TextWritingException(String message, long line, String recordCharacters) { this(message, line, null, recordCharacters, null); } /** * Returns the number of records written before the exception occurred. * * @return the number of records written before the exception occurred. */ public long getRecordCount() { return recordCount; } /** * Returns the data that failed to be written * * @return the data that failed to be written */ public Object[] getRecordData() { return restrictContent(recordData); } /** * Returns the character data that failed to be written * * @return the character data that failed to be written */ public String getRecordCharacters() { if(errorContentLength == 0){ return null; } return recordCharacters; } @Override protected String getDetails() { String details = ""; details = printIfNotEmpty(details, "recordCount", recordCount); details = printIfNotEmpty(details, "recordData", restrictContent(recordData)); details = printIfNotEmpty(details, "recordCharacters", restrictContent(recordCharacters)); return details; } @Override protected String getErrorDescription() { return "Error writing data"; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/beans/000077500000000000000000000000001475274123300305655ustar00rootroot00000000000000BeanHelper.java000066400000000000000000000106451475274123300333640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/beans/* * Copyright (c) 2015. Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.beans; import java.lang.ref.*; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; /** * Helper class used to obtain property descriptors from annotated java beans whose values are set via reflection. * This class was implemented to eliminate direct compile-time dependency with {@link java.beans.Introspector} and * other classes in the {@code java.beans.*} package. This is required to allow Android developers to use univocity-parsers. * Android developers should add have openbeans-1.0.jar * in their classpath to be able to use univocity-parsers. * * When available, the classes from package {@code com.googlecode.openbeans.*} will be used, otherwise the * bean introspection classes classes from {@code java.beans.*} package will be loaded. * * If everything fails, then the parser will try to manipulate fields in annotated java beans directly, instead * of using their getters and setters. */ public final class BeanHelper { private static final PropertyWrapper[] EMPTY = new PropertyWrapper[0]; private static final Class introspectorClass = findIntrospectorImplementationClass(); private static final Method beanInfoMethod = getBeanInfoMethod(); private static final Method propertyDescriptorMethod = getMethod("getPropertyDescriptors", beanInfoMethod, false); static Method PROPERTY_WRITE_METHOD = getMethod("getWriteMethod", propertyDescriptorMethod, true); static Method PROPERTY_READ_METHOD = getMethod("getReadMethod", propertyDescriptorMethod, true); static Method PROPERTY_NAME_METHOD = getMethod("getName", propertyDescriptorMethod, true); private static final Map, WeakReference> descriptors = new ConcurrentHashMap, WeakReference>(); private BeanHelper() { } /** * Returns the property descriptors of all properties available from a class * @param beanClass the class whose property descriptors should be returned * @return an array of all property descriptors of the given class. Might be empty. */ public static PropertyWrapper[] getPropertyDescriptors(Class beanClass) { if (propertyDescriptorMethod == null) { return EMPTY; } PropertyWrapper[] out = null; WeakReference reference = descriptors.get(beanClass); if (reference != null) { out = reference.get(); } if (out == null) { try { Object beanInfo = beanInfoMethod.invoke(null, beanClass, Object.class); Object[] propertyDescriptors = (Object[]) propertyDescriptorMethod.invoke(beanInfo); out = new PropertyWrapper[propertyDescriptors.length]; for (int i = 0; i < propertyDescriptors.length; i++) { out[i] = new PropertyWrapper(propertyDescriptors[i]); } } catch (Exception ex) { out = EMPTY; } descriptors.put(beanClass, new WeakReference(out)); } return out; } private static Class findIntrospectorImplementationClass() { try { return Class.forName("com.googlecode.openbeans.Introspector"); } catch (Throwable e1) { try { return Class.forName("java.beans.Introspector"); } catch (Throwable e2) { return null; } } } private static Method getBeanInfoMethod() { if (introspectorClass == null) { return null; } try { return introspectorClass.getMethod("getBeanInfo", Class.class, Class.class); } catch (Throwable e) { return null; } } private static Method getMethod(String methodName, Method method, boolean fromComponentType) { if (method == null) { return null; } try { Class returnType = method.getReturnType(); if (fromComponentType) { returnType = returnType.getComponentType(); } return returnType.getMethod(methodName); } catch (Exception ex) { return null; } } } PropertyWrapper.java000066400000000000000000000055261475274123300345460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/beans/* * Copyright (c) 2015. Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.beans; import java.lang.reflect.*; /** * Wrapper for a implementation of PropertyDescriptor from either {@code java.beans.PropertyDescriptor} * or {@code com.googlecode.openbeans.PropertyDescriptor}. * * Used to eliminate compile-time dependencies with package {@code java.beans.*} which is not * available to Android developers. */ public final class PropertyWrapper { private static final Method NO_METHOD = getNullMethod(); private static final String NO_NAME = "!!NO_NAME!!"; private final Object propertyDescriptor; private Method writeMethod; private Method readMethod; private String name; PropertyWrapper(Object propertyDescriptor) { this.propertyDescriptor = propertyDescriptor; } /** * Returns the method that should be used to write a value to a property of a Java bean. * Might be {@code null}. * * @return The method that should be used to write the property value, if available. **/ public final Method getWriteMethod() { if (writeMethod == null) { writeMethod = (Method) invoke(propertyDescriptor, BeanHelper.PROPERTY_WRITE_METHOD); } return writeMethod == NO_METHOD ? null : writeMethod; } /** * Returns the method that should be used to read the value of a property of a Java bean. * Might be {@code null}. * * @return The method that should be used to read the property value, if available. */ public final Method getReadMethod() { if (readMethod == null) { readMethod = (Method) invoke(propertyDescriptor, BeanHelper.PROPERTY_READ_METHOD); } return readMethod == NO_METHOD ? null : readMethod; } /** * Returns the name of a property of a Java bean. * Might be {@code null}. * * @return The property name. */ public final String getName() { if (name == null) { name = (String) invoke(propertyDescriptor, BeanHelper.PROPERTY_NAME_METHOD); } return name == NO_NAME ? null : name; } private static Object invoke(Object propertyDescriptor, Method method) { try { return method.invoke(propertyDescriptor); } catch (Exception ex) { return null; } } private static Method getNullMethod() { try { return Object.class.getMethod("hashCode"); } catch (NoSuchMethodException e) { // should never happen. return null; } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/000077500000000000000000000000001475274123300307435ustar00rootroot00000000000000AbstractColumnMapping.java000066400000000000000000000161231475274123300357670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.annotations.helpers.*; import java.util.*; /** * Basic support operations for mapping attributes/methods to columns in a {@link ColumnMapper} * @param the type of key (attribute/method names or specific method definition with parameter and return types) */ abstract class AbstractColumnMapping implements Cloneable { final String prefix; Map mapping; /** * Creates a mapping with a prefix. * * @param prefix a dot separated sequence of names that represents the nesting of complex attributes inside a class (e.g customer.contact.phone). * @param parent the parent mapping of columns, relevant only when nested objects' attributes or methods are being mapped. */ AbstractColumnMapping(String prefix, AbstractColumnMapping parent) { if (parent != null) { mapping = parent.mapping; this.prefix = parent.prefix.isEmpty() ? prefix : parent.prefix + '.' + prefix; } else { mapping = new LinkedHashMap(); this.prefix = prefix; } } /** * Maps a attribute or method to a column name * @param key attribute/method name or specific method definition with parameter and return type * @param columnName name of column associated with the given key */ void mapToColumnName(K key, String columnName) { mapping.put(key, columnName); } /** * Maps a attribute or method to a column name * @param key attribute/method name or specific method definition with parameter and return type * @param column enumeration representing the column associated with the given key */ void mapToColumn(K key, Enum column) { mapping.put(key, column); } /** * Maps a attribute or method to a column name * @param key attribute/method name or specific method definition with parameter and return type * @param columnIndex number representing the position of the column associated with the given key */ void mapToColumnIndex(K key, int columnIndex) { mapping.put(key, columnIndex); } /** * Maps multiple attributes or methods to multiple column names * @param mappings the mappings to be added */ void mapToColumnNames(Map mappings) { mapping.putAll(mappings); } /** * Maps multiple attributes or methods to multiple column names * @param mappings the mappings to be added */ void mapToColumns(Map> mappings) { mapping.putAll(mappings); } /** * Maps multiple attributes or methods to multiple column names * @param mappings the mappings to be added */ void mapToColumnIndexes(Map mappings) { mapping.putAll(mappings); } /** * Tests whether a given attribute or method is mapped to a column * @param key the attribute or method name/descriptor * @return {@code true} if the key is mapped. */ boolean isMapped(K key) { return getMappedColumn(key) != null; } /** * Transforms the key so it can work with the given prefix. * * @param prefix the current object nesting level, denoted by a dot-separated string of nested attribute names. * @param key the key to transform. * @return the transformed key or {@code null} if the key can't be used with the given prefix */ abstract K prefixKey(String prefix, K key); private Object getMappedColumn(K key) { if (key == null) { return null; } key = prefixKey(prefix, key); Object out = mapping.get(key); return out; } /** * Updates the mapping of a attribute/method so a mapped class member can target * a user provided column. * * @param fieldMapping a class member that has should be mapped to a column * @param key the attribute name or method specification that matches with the given field. * * @return {@code true} if the mapping has been successfully updated. */ boolean updateFieldMapping(FieldMapping fieldMapping, K key) { Object mappedColumn = getMappedColumn(key); if (mappedColumn != null) { if (mappedColumn instanceof Enum) { mappedColumn = ((Enum) mappedColumn).name(); } if (mappedColumn instanceof String) { fieldMapping.setFieldName((String) mappedColumn); fieldMapping.setIndex(-1); return true; } else if (mappedColumn instanceof Integer) { fieldMapping.setIndex((Integer) mappedColumn); return true; } throw new IllegalStateException("Unexpected mapping of '" + key + "' to " + mappedColumn); } return false; } /** * Returns all prefixes used by the keys in this mapping. These represent names of * nested objects that will be navigated through to access their attributes/methods. * @param out the set of prefixes to populate. */ void extractPrefixes(Set out) { for (K key : mapping.keySet()) { String keyPrefix = getKeyPrefix(prefix, key); if (keyPrefix != null) { out.add(keyPrefix); } } } /** * Returns the prefix of a given key, i.e. the current nested object that is * being targeted. * * @param prefix the current prefix - a dot separated string with nested attribute names * @param key the attribute name or method definition. If its own prefix starts with the given prefix, the next element after the dot will be returned (if any) * @return the name of the next nested object relative to the current prefix. */ abstract String getKeyPrefix(String prefix, K key); /** * Creates a deep copy of this mapping that is independent from the original. * @return the duplicate of this object. */ public AbstractColumnMapping clone() { try { AbstractColumnMapping out = (AbstractColumnMapping) super.clone(); out.mapping = new LinkedHashMap(mapping); return out; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } /** * Locates a given key based on an attribute or method name. * * @param nameWithPrefix name of the attribute or method, prefixed with nested object names that identify the path to the target class member. * @return the key formed with the given attribute name or method definition */ abstract K findKey(String nameWithPrefix); /** * Removes any mappings containing keys that have a given attribute or method name. * * @param nameWithPrefix name of the attribute or method, prefixed with nested object names that identify the path to the target class member. */ void remove(String nameWithPrefix) { K key; while ((key = findKey(nameWithPrefix)) != null) { if (mapping.remove(key) == null) { return; } } } } AllIndexesSelector.java000066400000000000000000000032501475274123300352600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; /** * A FieldSelector that selects all indexes of a record. * * @see FieldSelector * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class AllIndexesSelector implements FieldSelector { @Override public int[] getFieldIndexes(NormalizedString[] headers) { if(headers == null){ return null; } int[] out = new int[headers.length]; for (int i = 0; i < out.length; i++) { out[i] = i; } return out; } @Override public String describe() { return "all fields"; } @Override public Object clone() { try { return super.clone(); }catch (CloneNotSupportedException e){ throw new IllegalStateException(e); } } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } ColumnMapper.java000066400000000000000000000344141475274123300341370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.annotations.*; import java.util.*; /** * A utility that allows users to manually define mappings from * attributes/methods of a given class to columns to be parsed or written. * * This removes the requirement of having classes annotated with {@link Parsed} or * {@link Nested}. * * Mappings defined manually take precedence over annotations. * * @see ColumnMapping */ public interface ColumnMapper extends Cloneable { /** * Maps an attribute to a column name. * * @param attributeName the name of the attribute. * Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the attribute "mobile" * from a Contact attribute inside a Customer class. * @param columnName the name of the column that: * (a) when parsing, will be read from to populate the given attribute of an object; * (b) when writing, will receive the value of the given attribute of an object; */ void attributeToColumnName(String attributeName, String columnName); /** * Maps an attribute to a column. * * @param attributeName the name of the attribute. * Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the attribute "mobile" * from a Contact attribute inside a Customer class. * @param column an enumeration representing the column that: * (a) when parsing, will be read from to populate the given attribute of an object; * (b) when writing, will receive the value of the given attribute of an object; */ void attributeToColumn(String attributeName, Enum column); /** * Maps an attribute to a column position. * * @param attributeName the name of the attribute. * Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the attribute "mobile" * from a Contact attribute inside a Customer class. * @param columnIndex the position of the column that: * (a) when parsing, will be read from to populate the given attribute of an object; * (b) when writing, will receive the value of the given attribute of an object; */ void attributeToIndex(String attributeName, int columnIndex); /** * Maps multiple attributes to multiple column names. * * @param mappings a map of attribute names associated with a corresponding column name, where: * *

    *
  • Each key is the name of the attribute. Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the attribute "mobile" * from a Contact attribute inside a Customer class. *
  • *
  • Each value is the name of the column that: * (a) when parsing, will be read from to populate the given attribute of an object; * (b) when writing, will receive the value of the given attribute of an object; *
  • *
*/ void attributesToColumnNames(Map mappings); /** * Maps multiple attributes to multiple columns. * * @param mappings a map of attribute names associated with a corresponding column, where: * *
    *
  • Each key is the name of the attribute. Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the attribute "mobile" * from a Contact attribute inside a Customer class. *
  • *
  • Each value is an enumeration representing the column that: * (a) when parsing, will be read from to populate the given attribute of an object; * (b) when writing, will receive the value of the given attribute of an object; *
  • *
*/ void attributesToColumns(Map> mappings); /** * Maps multiple attributes to multiple column positions. * * @param mappings a map of attribute names associated with a corresponding column, where: * *
    *
  • Each key is the name of the attribute. Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the attribute "mobile" * from a Contact attribute inside a Customer class. *
  • *
  • Each value is an integer representing the position of the column that: * (a) when parsing, will be read from to populate the given attribute of an object; * (b) when writing, will receive the value of the given attribute of an object; *
  • *
*/ void attributesToIndexes(Map mappings); /** * Maps a setter method to a column name. Use when {@link #methodToColumnName(String, String)} * is not enough to uniquely identify the method you need (e.g. when there are * overloaded methods with different parameter types) * * Used only for parsing. Will be ignored when writing. * * @param setterName the name of the setter method. * Use the dot character to access methods of nested objects, * e.g. {@code contact.mobile} will target the setter method "mobile(String)" * from a Contact attribute inside a Customer class. * @param parameterType the type of the parameter used in the given setter name. * @param columnName the name of the column that when parsing, will be read from to invoke given setter method of an object * */ void methodToColumnName(String setterName, Class parameterType, String columnName); /** * Maps a setter method to a column. Use when {@link #methodToColumnName(String, String)} * is not enough to uniquely identify the method you need (e.g. when there are * overloaded methods with different parameter types) * * Used only for parsing. Will be ignored when writing. * * @param setterName the name of the setter method. * Use the dot character to access methods of nested objects, * e.g. {@code contact.mobile} will target the setter method "mobile(String)" * from a Contact attribute inside a Customer class. * @param parameterType the type of the parameter used in the given setter name. * @param column an enumeration representing the column that when parsing, will be read from to invoke given setter method of an object */ void methodToColumn(String setterName, Class parameterType, Enum column); /** * Maps a setter method to a column position. Use when {@link #methodToColumnName(String, String)} * is not enough to uniquely identify the method you need (e.g. when there are * overloaded methods with different parameter types) * * Used only for parsing. Will be ignored when writing. * * @param setterName the name of the setter method. * Use the dot character to access methods of nested objects, * e.g. {@code contact.mobile} will target the setter method "mobile(String)" * from a Contact attribute inside a Customer class. * @param parameterType the type of the parameter used in the given setter name. * @param columnIndex the position of the column that when parsing, will be read from to invoke given setter method of an object */ void methodToIndex(String setterName, Class parameterType, int columnIndex); /** * Maps a method to a column name. * * When parsing, only "setter" methods will be used i.e. the given method accepts one parameter. * If the method is overridden, use {@link #methodToColumnName(String, Class, String)} * to specify the exact parameter type to match the appropriate setter method. * * When writing, only "getter" methods will be used i.e. the given method * doesn't accept any parameters and returns a value. * * @param methodName the name of the method. * Use the dot character to access methods of nested objects, * e.g. {@code contact.mobile} will target the method "mobile(String)" when parsing, or "String mobile()" when writing, * from a Contact attribute inside a Customer class. * @param columnName the name of the column that: * (a) when parsing, will be read from to invoke given setter method of an object; * (b) when writing, will receive the value returned by the given getter method of an object; * */ void methodToColumnName(String methodName, String columnName); /** * Maps a method to a column. * * When parsing, only "setter" methods will be used i.e. the given method accepts one parameter. * If the method is overridden, use {@link #methodToColumnName(String, Class, String)} * to specify the exact parameter type to match the appropriate setter method. * * When writing, only "getter" methods will be used i.e. the given method * doesn't accept any parameters and returns a value. * * @param methodName the name of the method. * Use the dot character to access methods of nested objects, * * e.g. {@code contact.mobile} will target the method "mobile(String)" when parsing, or "String mobile()" when writing, * * from a Contact attribute inside a Customer class. * @param column an enumeration representing the column that: * (a) when parsing, will be read from to invoke given setter method of an object; * (b) when writing, will receive the value returned by the given getter method of an object; * */ void methodToColumn(String methodName, Enum column); /** * Maps a method to a column position. * * When parsing, only "setter" methods will be used i.e. the given method accepts one parameter. * If the method is overridden, use {@link #methodToColumnName(String, Class, String)} * to specify the exact parameter type to match the appropriate setter method. * * When writing, only "getter" methods will be used i.e. the given method * doesn't accept any parameters and returns a value. * * @param methodName the name of the method. * Use the dot character to access methods of nested objects, * * e.g. {@code contact.mobile} will target the method "mobile(String)" when parsing, or "String mobile()" when writing, * * from a Contact attribute inside a Customer class. * @param columnIndex the position of the column that: * (a) when parsing, will be read from to invoke given setter method of an object; * (b) when writing, will receive the value returned by the given getter method of an object; * */ void methodToIndex(String methodName, int columnIndex); /** * Maps multiple methods to multiple column names. * * @param mappings a map of methods names associated with a corresponding column name, where: * *
    *
  • Each key is the name of a method. Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the method "mobile(String)" when parsing, or "String mobile()" when writing, * from a Contact attribute inside a Customer class. *
  • *
  • Each value is the name of the column that: * (a) when parsing, will be read from to invoke given setter method of an object; * (b) when writing, will receive the value returned by the given getter method of an object; *
  • *
*/ void methodsToColumnNames(Map mappings); /** * Maps multiple methods to multiple columns. * * @param mappings a map of methods names associated with a corresponding column, where: * *
    *
  • Each key is the name of a method. Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the method "mobile(String)" when parsing, or "String mobile()" when writing, * from a Contact attribute inside a Customer class. *
  • *
  • Each value is an enumeration representing the column that: * (a) when parsing, will be read from to invoke given setter method of an object; * (b) when writing, will receive the value returned by the given getter method of an object; *
  • *
*/ void methodsToColumns(Map> mappings); /** * Maps multiple methods to multiple column positions. * * @param mappings a map of methods names associated with a corresponding column position, where: * *
    *
  • Each key is the name of a method. Use the dot character to access attributes of nested objects, * e.g. {@code contact.mobile} will target the method "mobile(String)" when parsing, or "String mobile()" when writing, * from a Contact attribute inside a Customer class. *
  • *
  • Each value is an integer representing the position of the column that: * (a) when parsing, will be read from to invoke given setter method of an object; * (b) when writing, will receive the value returned by the given getter method of an object; *
  • *
*/ void methodsToIndexes(Map mappings); /** * Creates a deep copy of this object with all its mappings. Changes to the clone won't affect the original instance. * @return a clone of the current mappings. */ ColumnMapper clone(); /** * Removes any mappings that target a given method or attribute name. * @param methodOrAttributeName the name of the method or attribute to be removed. */ void remove(String methodOrAttributeName); } ColumnMapping.java000066400000000000000000000212151475274123300343010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.annotations.helpers.*; import java.util.*; import static com.univocity.parsers.annotations.helpers.MethodDescriptor.*; /** * Implementation the {@link ColumnMapper} interface which allows * users to manually define mappings from attributes/methods of a given class * to columns to be parsed or written. * * @see ColumnMapper */ public final class ColumnMapping implements ColumnMapper { private class NameMapping extends AbstractColumnMapping { public NameMapping(String prefix, NameMapping parent) { super(prefix, parent); } @Override String prefixKey(String prefix, String key) { if (prefix.isEmpty()) { return key; } else { return prefix + '.' + key; } } @Override String getKeyPrefix(String prefix, String key) { return getCurrentAttributePrefix(prefix, key); } @Override String findKey(String nameWithPrefix) { return nameWithPrefix; } } private class MethodMapping extends AbstractColumnMapping { public MethodMapping(String prefix, MethodMapping parent) { super(prefix, parent); } @Override MethodDescriptor prefixKey(String prefix, MethodDescriptor key) { if (key.getPrefix().equals(prefix)) { return key; } return null; } @Override String getKeyPrefix(String prefix, MethodDescriptor key) { return getCurrentAttributePrefix(prefix, key.getPrefixedName()); } @Override MethodDescriptor findKey(String nameWithPrefix) { for (MethodDescriptor k : this.mapping.keySet()) { if (k.getPrefixedName().equals(nameWithPrefix)) { return k; } } return null; } } private static String getCurrentAttributePrefix(String prefix, String name) { if (!name.startsWith(prefix)) { return null; } int off = prefix.isEmpty() ? 0 : 1; int dot = name.indexOf('.', prefix.length() + off); if (dot != -1) { String attributePrefix = name.substring(prefix.length() + off, dot); return attributePrefix; } return null; } private NameMapping attributeMapping; private NameMapping methodNameMapping; private MethodMapping methodMapping; /** * Creates a new column mapping instance */ public ColumnMapping() { this("", null); } /** * Creates a nested column mapping instance for handling nested attributes. For internal use. * * @param prefix the current nesting path, denoted by a dot separated string of attribute names * @param parent the mappings of the parent object in the nested structure. */ public ColumnMapping(String prefix, ColumnMapping parent) { attributeMapping = new NameMapping(prefix, parent == null ? null : parent.attributeMapping); methodNameMapping = new NameMapping(prefix, parent == null ? null : parent.methodNameMapping); methodMapping = new MethodMapping(prefix, parent == null ? null : parent.methodMapping); } @Override public void attributeToColumnName(String attributeName, String columnName) { attributeMapping.mapToColumnName(attributeName, columnName); } @Override public void attributeToColumn(String attributeName, Enum column) { attributeMapping.mapToColumn(attributeName, column); } @Override public void attributeToIndex(String attributeName, int columnIndex) { attributeMapping.mapToColumnIndex(attributeName, columnIndex); } @Override public void attributesToColumnNames(Map mappings) { attributeMapping.mapToColumnNames(mappings); } @Override public void attributesToColumns(Map> mappings) { attributeMapping.mapToColumns(mappings); } @Override public void attributesToIndexes(Map mappings) { attributeMapping.mapToColumnIndexes(mappings); } private void methodToColumnName(MethodDescriptor method, String columnName) { methodMapping.mapToColumnName(method, columnName); } private void methodToColumn(MethodDescriptor method, Enum column) { methodMapping.mapToColumn(method, column); } private void methodToIndex(MethodDescriptor method, int columnIndex) { methodMapping.mapToColumnIndex(method, columnIndex); } /** * Tests whether a method or attribute has been mapped to a column. * @param method a descriptor of getter/setter methods (can be {@code null}) * @param targetName name of a method or attribute * @return {@code true} if the given method or attribute has been mapped to a column */ public boolean isMapped(MethodDescriptor method, String targetName) { return methodMapping.isMapped(method) || attributeMapping.isMapped(targetName) || methodNameMapping.isMapped(targetName); } /** * Updates the mapping of a attribute/method so a mapped class member can target * a user provided column. * * @param fieldMapping a class member that has should be mapped to a column * @param targetName name of a method or attribute * @param method a descriptor of getter/setter methods (can be {@code null}) * * @return {@code true} if the mapping has been successfully updated. */ public boolean updateMapping(FieldMapping fieldMapping, String targetName, MethodDescriptor method) { if (methodMapping.isMapped(method)) { return methodMapping.updateFieldMapping(fieldMapping, method); } else if (attributeMapping.isMapped(targetName)) { return attributeMapping.updateFieldMapping(fieldMapping, targetName); } else if (methodNameMapping.isMapped(targetName)) { return methodNameMapping.updateFieldMapping(fieldMapping, targetName); } return false; } /** * Returns object the nesting path associated with the current mapping. * @return a dot separated string of nested attribute names */ public String getPrefix() { return methodMapping.prefix; } @Override public void methodToColumnName(String methodName, String columnName) { methodNameMapping.mapToColumnName(methodName, columnName); } @Override public void methodToColumn(String methodName, Enum column) { methodNameMapping.mapToColumn(methodName, column); } @Override public void methodToIndex(String methodName, int columnIndex) { methodNameMapping.mapToColumnIndex(methodName, columnIndex); } @Override public void methodsToColumnNames(Map mappings) { methodNameMapping.mapToColumnNames(mappings); } @Override public void methodsToColumns(Map> mappings) { methodNameMapping.mapToColumns(mappings); } @Override public void methodsToIndexes(Map mappings) { methodNameMapping.mapToColumnIndexes(mappings); } public void remove(String methodOrAttributeName) { attributeMapping.remove(methodOrAttributeName); methodNameMapping.remove(methodOrAttributeName); methodMapping.remove(methodOrAttributeName); } @Override public void methodToColumnName(String setterName, Class parameterType, String columnName) { methodToColumnName(setter(setterName, parameterType), columnName); } @Override public void methodToColumn(String setterName, Class parameterType, Enum column) { methodToColumn(setter(setterName, parameterType), column); } @Override public void methodToIndex(String setterName, Class parameterType, int columnIndex) { methodToIndex(setter(setterName, parameterType), columnIndex); } /** * Returns the first-level names of all nested members whose attributes or methods have been mapped * @return the names of nested objects to visit from the current object */ public Set getNestedAttributeNames() { Set out = new HashSet(); attributeMapping.extractPrefixes(out); methodNameMapping.extractPrefixes(out); methodMapping.extractPrefixes(out); return out; } @Override public ColumnMapper clone() { try { ColumnMapping out = (ColumnMapping) super.clone(); out.attributeMapping = (NameMapping) this.attributeMapping.clone(); out.methodNameMapping = (NameMapping) this.methodNameMapping.clone(); out.methodMapping = (MethodMapping) this.methodMapping.clone(); return out; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } } ExcludeFieldEnumSelector.java000066400000000000000000000044431475274123300364170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; /** * A FieldSelector capable of deselecting fields in a record. *

This selector stores undesired fields, represented by values of an enumeration, * and will return the indexes of those fields that are not part of the selection. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see FieldSelector * @see FieldSet */ @SuppressWarnings("rawtypes") public class ExcludeFieldEnumSelector extends FieldSet implements FieldSelector { private ExcludeFieldNameSelector names = new ExcludeFieldNameSelector(); /** * Returns the indexes of any that are part of a sequence of headers but not part of the selection. * * @param headers the sequence of headers that might have some elements selected by this FieldSelector * @return the positions of all elements which were not selected. */ @Override public int[] getFieldIndexes(NormalizedString[] headers) { if(headers == null){ return null; } names.set(ArgumentUtils.toArray(this.get())); return names.getFieldIndexes(headers); } @Override public String describe() { return "undesired " + super.describe(); } public ExcludeFieldEnumSelector clone(){ ExcludeFieldEnumSelector out = (ExcludeFieldEnumSelector) super.clone(); out.names = (ExcludeFieldNameSelector) names.clone(); return out; } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } ExcludeFieldIndexSelector.java000066400000000000000000000045561475274123300365670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; import java.util.*; /** * A FieldSelector capable of deselecting fields by their position in a record. * *

This selector stores undesired fields and will return the indexes of those fields that are not part of the selection. * * @see FieldSelector * @see FieldSet * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ExcludeFieldIndexSelector extends FieldSet implements FieldSelector { /** * Returns the indexes of any that are part of a sequence of headers but not part of the selection. * @param columns the sequence of headers that might have some elements selected by this FieldSelector * @return the positions of all elements which were not selected. */ @Override public int[] getFieldIndexes(NormalizedString[] columns) { if(columns == null){ return null; } Set chosenFields = new HashSet(this.get()); Iterator it = chosenFields.iterator(); while(it.hasNext()){ Integer chosenIndex = it.next(); if (chosenIndex >= columns.length || chosenIndex < 0) { it.remove(); } } int[] out = new int[columns.length - chosenFields.size()]; int j = 0; for (int i = 0; i < columns.length; i++) { if (!chosenFields.contains(i)) { out[j++] = i; } } return out; } @Override public String describe() { return "undesired " + super.describe(); } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } ExcludeFieldNameSelector.java000066400000000000000000000046611475274123300363750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; import java.util.*; /** * A FieldSelector capable of deselecting fields by their name in a record. * *

This selector stores undesired fields and will return the indexes of those fields that are not part of the selection. * * @see FieldSelector * @see FieldSet * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ExcludeFieldNameSelector extends FieldSet implements FieldSelector, Cloneable { /** * Returns the indexes of any that are part of a sequence of headers but not part of the selection. * @param headers the sequence of headers that might have some elements selected by this FieldSelector * @return the positions of all elements which were not selected. */ @Override public int[] getFieldIndexes(NormalizedString[] headers) { if(headers == null){ return null; } NormalizedString[] normalizedHeaders = headers; // removes duplicates if any Set chosenFields = NormalizedString.toHashSet(this.get()); Object[] unknownFields = ArgumentUtils.findMissingElements(normalizedHeaders, chosenFields); int[] out = new int[normalizedHeaders.length - (chosenFields.size() - unknownFields.length)]; int j = 0; for (int i = 0; i < normalizedHeaders.length; i++) { if (!chosenFields.contains(normalizedHeaders[i])) { out[j++] = i; } } return out; } @Override public String describe() { return "undesired " + super.describe(); } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } FieldConversionMapping.java000066400000000000000000000465401475274123300361450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import java.util.*; /** * A class for mapping field selections to sequences of {@link Conversion} objects * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class FieldConversionMapping implements Cloneable { @SuppressWarnings("rawtypes") private static final Conversion[] EMPTY_CONVERSION_ARRAY = new Conversion[0]; public int[] validatedIndexes; /** * This list contains the sequence of conversions applied to sets of fields over multiple calls. *

It is shared by {@link FieldConversionMapping#fieldNameConversionMapping}, {@link FieldConversionMapping#fieldIndexConversionMapping} and {@link FieldConversionMapping#convertAllMapping}. *

Every time the user associates a sequence of conversions to a field, conversionSequence list will receive the FieldSelector. */ private List conversionSequence = new ArrayList(); private AbstractConversionMapping fieldNameConversionMapping = new AbstractConversionMapping(conversionSequence) { @Override protected FieldSelector newFieldSelector() { return new FieldNameSelector(); } }; private AbstractConversionMapping fieldIndexConversionMapping = new AbstractConversionMapping(conversionSequence) { @Override protected FieldSelector newFieldSelector() { return new FieldIndexSelector(); } }; @SuppressWarnings("rawtypes") private AbstractConversionMapping fieldEnumConversionMapping = new AbstractConversionMapping(conversionSequence) { @Override protected FieldSelector newFieldSelector() { return new FieldEnumSelector(); } }; private AbstractConversionMapping convertAllMapping = new AbstractConversionMapping(conversionSequence) { @Override protected FieldSelector newFieldSelector() { return new AllIndexesSelector(); } }; /** * This is the final sequence of conversions applied to each index in a record. It is populated when {@link FieldConversionMapping#prepareExecution(boolean, String[])} is invoked. */ private Map>> conversionsByIndex = Collections.emptyMap(); private Map> validationsByIndex = Collections.emptyMap(); /** * Prepares the conversions registered in this object to be executed against a given sequence of fields * * @param writing flag indicating whether a writing process is being initialized. * @param values The field sequence that identifies how records will be organized. *

This is generally the sequence of headers in a record, but it might be just the first parsed row from a given input (as field selection by index is allowed). */ public void prepareExecution(boolean writing, String[] values) { if (fieldNameConversionMapping.isEmpty() && fieldEnumConversionMapping.isEmpty() && fieldIndexConversionMapping.isEmpty() && convertAllMapping.isEmpty()) { return; } if (!conversionsByIndex.isEmpty()) { return; } //Note this property is shared across all conversion mappings. This is required so //the correct conversion sequence is registered for all fields. conversionsByIndex = new HashMap>>(); // adds the conversions in the sequence they were created. for (FieldSelector next : conversionSequence) { fieldNameConversionMapping.prepareExecution(writing, next, conversionsByIndex, values); fieldIndexConversionMapping.prepareExecution(writing, next, conversionsByIndex, values); fieldEnumConversionMapping.prepareExecution(writing, next, conversionsByIndex, values); convertAllMapping.prepareExecution(writing, next, conversionsByIndex, values); } Iterator>>> entryIterator = conversionsByIndex.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry>> e = entryIterator.next(); Iterator> it = e.getValue().iterator(); while (it.hasNext()) { Conversion conversion = it.next(); if (conversion instanceof ValidatedConversion) { if (validationsByIndex.isEmpty()) { validationsByIndex = new TreeMap>(); } it.remove(); List validations = validationsByIndex.get(e.getKey()); if (validations == null) { validations = new ArrayList(1); validationsByIndex.put(e.getKey(), validations); } validations.add((ValidatedConversion) conversion); } } if (e.getValue().isEmpty()) { entryIterator.remove(); } } validatedIndexes = ArgumentUtils.toIntArray(validationsByIndex.keySet()); } /** * Applies a sequence of conversions on all fields. * * @param conversions the sequence of conversions to be applied */ public void applyConversionsOnAllFields(Conversion... conversions) { convertAllMapping.registerConversions(conversions); } /** * Applies a sequence of conversions on a selection of field indexes * * @param conversions the sequence of conversions to be applied * * @return a selector of column indexes. */ public FieldSet applyConversionsOnFieldIndexes(Conversion... conversions) { return fieldIndexConversionMapping.registerConversions(conversions); } /** * Applies a sequence of conversions on a selection of field name * * @param conversions the sequence of conversions to be applied * * @return a selector of column names. */ public FieldSet applyConversionsOnFieldNames(Conversion... conversions) { return fieldNameConversionMapping.registerConversions(conversions); } /** * Applies a sequence of conversions on a selection of enumerations that represent fields * * @param conversions the sequence of conversions to be applied * * @return a selector of enumerations. */ @SuppressWarnings("rawtypes") public FieldSet applyConversionsOnFieldEnums(Conversion... conversions) { return fieldEnumConversionMapping.registerConversions(conversions); } /** * Applies any validations associated with a field at a given index in a record * @param index The index of parsed value in a record * @param value The value of the record at the given index */ public void executeValidations(int index, Object value) { List validations = validationsByIndex.get(index); if (validations != null) { for (int i = 0; i < validations.size(); i++) { validations.get(i).execute(value); } } } /** * Applies a sequence of conversions associated with an Object value at a given index in a record. * * @param executeInReverseOrder flag to indicate whether or not the conversion sequence must be executed in reverse order * @param index The index of parsed value in a record * @param value The value in a record * @param convertedFlags an array of flags that indicate whether a conversion occurred. Used to determine whether * or not a default conversion by type (specified with {@link ConversionProcessor#convertType(Class, Conversion[])}) should be applied. * * @return the Object resulting from a sequence of conversions against the original value. */ @SuppressWarnings({"unchecked", "rawtypes"}) public Object reverseConversions(boolean executeInReverseOrder, int index, Object value, boolean[] convertedFlags) { List> conversions = conversionsByIndex.get(index); if (conversions != null) { if (convertedFlags != null) { convertedFlags[index] = true; } Conversion conversion = null; try { if (executeInReverseOrder) { for (int i = conversions.size() - 1; i >= 0; i--) { conversion = conversions.get(i); value = conversion.revert(value); } } else { for (Conversion c : conversions) { conversion = c; value = conversion.revert(value); } } } catch (DataProcessingException ex) { ex.setValue(value); ex.setColumnIndex(index); ex.markAsNonFatal(); throw ex; } catch (Throwable ex) { DataProcessingException exception; if (conversion != null) { exception = new DataProcessingException("Error converting value '{value}' using conversion " + conversion.getClass().getName(), ex); } else { exception = new DataProcessingException("Error converting value '{value}'", ex); } exception.setValue(value); exception.setColumnIndex(index); exception.markAsNonFatal(); throw exception; } } return value; } /** * Applies a sequence of conversions associated with a String value parsed from a given index. * * @param index The index of parsed value in a record * @param stringValue The parsed value in a record * @param convertedFlags an array of flags that indicate whether a conversion occurred. Used to determine whether * or not a default conversion by type (specified with {@link ConversionProcessor#convertType(Class, Conversion[])}) should be applied. * * @return the Object produced by a sequence of conversions against the original String value. */ @SuppressWarnings({"rawtypes", "unchecked"}) public Object applyConversions(int index, String stringValue, boolean[] convertedFlags) { List> conversions = conversionsByIndex.get(index); if (conversions != null) { if (convertedFlags != null) { convertedFlags[index] = true; } Object result = stringValue; for (Conversion conversion : conversions) { try { result = conversion.execute(result); } catch (DataProcessingException ex) { ex.setColumnIndex(index); ex.markAsNonFatal(); throw ex; } catch (Throwable ex) { DataProcessingException exception = new DataProcessingException("Error converting value '{value}' using conversion " + conversion.getClass().getName(), ex); exception.setValue(result); exception.setColumnIndex(index); exception.markAsNonFatal(); throw exception; } } return result; } return stringValue; } /** * Returns the sequence of conversions to be applied at a given column index * * @param index the index of the column where the conversions should be executed * @param expectedType the type resulting from the conversion sequence. * * @return the sequence of conversions to be applied at a given column index */ @SuppressWarnings("rawtypes") public Conversion[] getConversions(int index, Class expectedType) { List> conversions = conversionsByIndex.get(index); Conversion[] out; if (conversions != null) { out = new Conversion[conversions.size()]; int i = 0; for (Conversion conversion : conversions) { out[i++] = conversion; } } else if (expectedType == String.class) { return EMPTY_CONVERSION_ARRAY; } else { out = new Conversion[1]; out[0] = AnnotationHelper.getDefaultConversion(expectedType, null, null); if (out[0] == null) { return EMPTY_CONVERSION_ARRAY; } } return out; } @Override public FieldConversionMapping clone() { try { FieldConversionMapping out = (FieldConversionMapping) super.clone(); out.validatedIndexes = validatedIndexes == null ? null : this.validatedIndexes.clone(); out.conversionSequence = new ArrayList(); Map clonedSelectors = new HashMap(); for (FieldSelector selector : this.conversionSequence) { FieldSelector clone = (FieldSelector) selector.clone(); out.conversionSequence.add(clone); clonedSelectors.put(selector, clone); } out.fieldNameConversionMapping = fieldNameConversionMapping.clone(clonedSelectors, out.conversionSequence); out.fieldIndexConversionMapping = fieldIndexConversionMapping.clone(clonedSelectors, out.conversionSequence); out.fieldEnumConversionMapping = fieldEnumConversionMapping.clone(clonedSelectors, out.conversionSequence); out.convertAllMapping = convertAllMapping.clone(clonedSelectors, out.conversionSequence); out.conversionsByIndex = new HashMap>>(conversionsByIndex); out.validationsByIndex = new TreeMap>(validationsByIndex); return out; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } } /** * Class responsible for managing field selections and any conversion sequence associated with each. * * @param the FieldSelector type information used to uniquely identify a field (e.g. references to field indexes would use Integer, while references to field names would use String). * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see FieldNameSelector * @see FieldIndexSelector */ abstract class AbstractConversionMapping implements Cloneable { private Map[]> conversionsMap; private List conversionSequence; AbstractConversionMapping(List conversionSequence) { this.conversionSequence = conversionSequence; } /** * Registers a sequence of conversions to a set of fields. *

The selector instance that is used to store which fields should be converted is added to the {@link AbstractConversionMapping#conversionSequence} list in order to keep track of the correct conversion order. *

This is required further conversion sequences might be added to the same fields in separate calls. * * @param conversions the conversion sequence to be applied to a set of fields. * * @return a FieldSet which provides methods to select the fields that must be converted or null if the FieldSelector returned by #newFieldSelector is not an instance of FieldSet (which is the case of {@link AllIndexesSelector}). */ @SuppressWarnings("unchecked") public FieldSet registerConversions(Conversion... conversions) { ArgumentUtils.noNulls("Conversions", conversions); FieldSelector selector = newFieldSelector(); if (conversionsMap == null) { conversionsMap = new LinkedHashMap[]>(); } conversionsMap.put(selector, conversions); conversionSequence.add(selector); if (selector instanceof FieldSet) { return (FieldSet) selector; } return null; } /** * Creates a FieldSelector instance of the desired type. Used in @link FieldConversionMapping}. * * @return a new FieldSelector instance. */ protected abstract FieldSelector newFieldSelector(); /** * Get all indexes in the given selector and adds the conversions defined at that index to the map of conversionsByIndex. *

This method is called in the same sequence each selector was created (in {@link FieldConversionMapping#prepareExecution(boolean, String[])}) *

At the end of the process, the map of conversionsByIndex will have each index with its list of conversions in the order they were declared. * * @param writing flag indicating whether a writing process is being initialized. * @param selector the selected fields for a given conversion sequence. * @param conversionsByIndex map of all conversions registered to every field index, in the order they were declared * @param values The field sequence that identifies how records will be organized. *

This is generally the sequence of headers in a record, but it might be just the first parsed row from a given input (as field selection by index is allowed). */ public void prepareExecution(boolean writing, FieldSelector selector, Map>> conversionsByIndex, String[] values) { if (conversionsMap == null) { return; } //conversionsMap contains maps the conversions applied to a field selection //we will match the indexes where these conversions where applied and add them to the corresponding list in conversionsByIndex Conversion[] conversions = conversionsMap.get(selector); if (conversions == null) { return; } int[] fieldIndexes = selector.getFieldIndexes(NormalizedString.toIdentifierGroupArray(values)); if (fieldIndexes == null) { fieldIndexes = ArgumentUtils.toIntArray(conversionsByIndex.keySet()); } for (int fieldIndex : fieldIndexes) { List> conversionsAtIndex = conversionsByIndex.get(fieldIndex); if (conversionsAtIndex == null) { conversionsAtIndex = new ArrayList>(); conversionsByIndex.put(fieldIndex, conversionsAtIndex); } validateDuplicates(selector, conversionsAtIndex, conversions); conversionsAtIndex.addAll(Arrays.asList(conversions)); } } /** * Ensures an individual field does not have the same conversion object applied to it more than once. * * @param selector the selection of fields * @param conversionsAtIndex the sequence of conversions applied to a given index * @param conversionsToAdd the sequence of conversions to add to conversionsAtIndex */ private static void validateDuplicates(FieldSelector selector, List> conversionsAtIndex, Conversion[] conversionsToAdd) { for (Conversion toAdd : conversionsToAdd) { for (Conversion existing : conversionsAtIndex) { if (toAdd == existing) { throw new DataProcessingException("Duplicate conversion " + toAdd.getClass().getName() + " being applied to " + selector.describe()); } } } } /** * Queries if any conversions were associated with any field * * @return true if no conversions were associated with any field; false otherwise */ public boolean isEmpty() { return conversionsMap == null || conversionsMap.isEmpty(); } public AbstractConversionMapping clone() { try { return (AbstractConversionMapping) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } public AbstractConversionMapping clone(Map clonedSelectors, List clonedConversionSequence) { AbstractConversionMapping out = clone(); out.conversionSequence = clonedConversionSequence; if (conversionsMap != null) { out.conversionsMap = new HashMap[]>(); for (FieldSelector selector : this.conversionSequence) { FieldSelector clone = clonedSelectors.get(selector); if (clone == null) { throw new IllegalStateException("Internal error cloning conversion mappings"); } Conversion[] conversions = conversionsMap.get(selector); out.conversionsMap.put(clone, conversions); } } return out; } } FieldEnumSelector.java000066400000000000000000000037471475274123300351130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; /** * A FieldSelector capable of selecting fields represented by values of an enumeration type. * The {@code toString()} output of the enumeration value will be used to match name of the fields. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see FieldSelector * @see FieldSet */ @SuppressWarnings("rawtypes") public class FieldEnumSelector extends FieldSet implements FieldSelector { private FieldNameSelector names = new FieldNameSelector(); /** * Returns the position of a given column represented by an enumeration value. * * @param column the column whose position will be returned * @return the position of the given column. */ public int getFieldIndex(Enum column) { return names.getFieldIndex(column.toString()); } @Override public int[] getFieldIndexes(NormalizedString[] headers) { if(headers == null){ return null; } names.set(ArgumentUtils.toArray(this.get())); return names.getFieldIndexes(headers); } public FieldEnumSelector clone() { FieldEnumSelector out = (FieldEnumSelector) super.clone(); out.names = (FieldNameSelector) names.clone(); return out; } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } FieldIndexSelector.java000066400000000000000000000030711475274123300352440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; import java.util.*; /** * A FieldSelector capable of selecting fields by their position in a record. * * @see FieldSelector * @see FieldSet * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class FieldIndexSelector extends FieldSet implements FieldSelector { @Override public int[] getFieldIndexes(NormalizedString[] columns) { List chosenIndexes = this.get(); int[] out = new int[chosenIndexes.size()]; int i = 0; for (Integer index : chosenIndexes) { out[i++] = index; } return out; } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } FieldNameSelector.java000066400000000000000000000054531475274123300350630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; import java.util.*; /** * A FieldSelector capable of selecting fields by their name. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see FieldSelector * @see FieldSet */ public class FieldNameSelector extends FieldSet implements FieldSelector, Cloneable { /** * Returns the position of a given header * * @param header the header whose position will be returned * @return the position of the given header. */ public int getFieldIndex(String header) { return getFieldIndexes(new NormalizedString[]{NormalizedString.valueOf(header)})[0]; } @Override public int[] getFieldIndexes(NormalizedString[] headers) { if (headers == null) { return null; } NormalizedString[] normalizedHeader = headers; List selection = NormalizedString.toArrayList(this.get()); NormalizedString[] chosenFields = selection.toArray(new NormalizedString[0]); Object[] unknownFields = ArgumentUtils.findMissingElements(normalizedHeader, chosenFields); //if we get a subset of the expected columns, we can parse normally, considering missing column values as null. if (unknownFields.length > 0 && !selection.containsAll(Arrays.asList(normalizedHeader))) { //nothing matched, just return an empty array and proceed. if (unknownFields.length == chosenFields.length) { return new int[0]; } } int[] out = new int[selection.size()]; Arrays.fill(out, -1); int i = 0; for (NormalizedString chosenField : selection) { int[] indexes = ArgumentUtils.indexesOf(normalizedHeader, chosenField); if (indexes.length > 1) { out = Arrays.copyOf(out, out.length + indexes.length - 1); } if (indexes.length != 0) { for (int j = 0; j < indexes.length; j++) { out[i++] = indexes[j]; } } else { i++; } } return out; } @Override public int[] getFieldIndexes(String[] headers) { return getFieldIndexes(NormalizedString.toIdentifierGroupArray(headers)); } } FieldSelector.java000066400000000000000000000041411475274123300342530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; /** * * Interface used to identify classes capable of selecting fields and returning their positions in a given sequence. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface FieldSelector extends Cloneable { /** * Returns the indexes of any selected fields that are part of a sequence of headers. * @param headers the sequence of headers that might have some elements selected by this FieldSelector * @return the positions of all selected elements in the given headers sequence. */ int[] getFieldIndexes(String[] headers); /** * Returns the indexes of any selected fields that are part of a sequence of headers. * @param headers the sequence of headers that might have some elements selected by this FieldSelector * @return the positions of all selected elements in the given headers sequence. */ int[] getFieldIndexes(NormalizedString[] headers); /** * Returns a string that represents the current field selection * @return a string that represents the current field selection */ String describe(); /** * Clones this field selector. Changes to the selection on the clone won't be reflected on the original * @return a copy of the current field selector. */ Object clone(); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/fields/FieldSet.java000066400000000000000000000125361475274123300333140ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import com.univocity.parsers.common.*; import java.util.*; /** * A set of selected fields. * *

Used by {@link CommonSettings} to select fields for reading/writing *

Also used by {@code com.univocity.parsers.common.processor.ConversionProcessor} to select fields that have to be converted. * * @see FieldNameSelector * @see FieldIndexSelector * * @see CommonSettings * * @param the type of the reference information used to uniquely identify a field (e.g. references to field indexes would use Integer, while references to field names would use String). * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class FieldSet implements Cloneable { private List fields = new ArrayList(); private List> wrappedFieldSets; /** * Creates am empty field set. For internal use only. */ public FieldSet() { this.wrappedFieldSets = Collections.emptyList(); } /** * Creates a field set that wraps a collection of other field sets. For internal use only. * @param wrappedFieldSets the field sets to be wrapped. */ public FieldSet(List> wrappedFieldSets) { this.wrappedFieldSets = wrappedFieldSets; if (this.wrappedFieldSets.contains(this)) { this.wrappedFieldSets.remove(this); } } /** * Returns a copy of the fields in this set * @return a copy of the fields in this set */ public List get() { return new ArrayList(fields); } /** * Validates and sets multiple field references. Any existing reference will be discarded. * @param fields information that uniquely identifies each field * @return the set of currently selected fields */ public FieldSet set(T... fields) { this.fields.clear(); add(fields); for (FieldSet wrapped : wrappedFieldSets) { wrapped.set(fields); } return this; } /** * Validates and adds multiple field references * @param fields information that uniquely identifies each field * @return the set of currently selected fields */ public FieldSet add(T... fields) { for (T field : fields) { addElement(field); } for (FieldSet wrapped : wrappedFieldSets) { wrapped.add(fields); } return this; } /** * Validates and adds a reference to a field. * @param field information that uniquely identifies a field */ private void addElement(T field) { fields.add(field); } /** * Validates and sets multiple field references. Any existing reference will be discarded. * @param fields information that uniquely identifies each field * @return the set of currently selected fields */ public FieldSet set(Collection fields) { this.fields.clear(); add(fields); for (FieldSet wrapped : wrappedFieldSets) { wrapped.set(fields); } return this; } /** * Validates and adds multiple field references * @param fields information that uniquely identifies each field * @return the set of currently selected fields */ public FieldSet add(Collection fields) { for (T field : fields) { addElement(field); } for (FieldSet wrapped : wrappedFieldSets) { wrapped.add(fields); } return this; } /** * Removes multiple field references in the selection * @param fields information that uniquely identifies each field * @return the set of currently selected fields */ public FieldSet remove(T... fields) { for (T field : fields) { this.fields.remove(field); } for (FieldSet wrapped : wrappedFieldSets) { wrapped.remove(fields); } return this; } /** * Removes multiple field references in the selection * @param fields information that uniquely identifies each field * @return the set of currently selected fields */ public FieldSet remove(Collection fields) { this.fields.removeAll(fields); for (FieldSet wrapped : wrappedFieldSets) { wrapped.remove(fields); } return this; } /** * Returns a string that represents the current field selection * @return a string that represents the current field selection */ public String describe() { return "field selection: " + fields.toString(); } @Override public String toString() { return fields.toString(); } public FieldSet clone() { try { FieldSet out = (FieldSet) super.clone(); out.fields = new ArrayList(fields); if (wrappedFieldSets != null) { out.wrappedFieldSets = new ArrayList>(); for (FieldSet fieldSet : wrappedFieldSets) { out.wrappedFieldSets.add(fieldSet.clone()); } } return out; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/000077500000000000000000000000001475274123300306345ustar00rootroot00000000000000AbstractCharInputReader.java000066400000000000000000000410661475274123300361330ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; import java.io.*; import java.util.*; /** * The base class for implementing different flavours of {@link CharInputReader}. * *

It provides the essential conversion of sequences of newline characters defined by {@link Format#getLineSeparator()} into the normalized newline character provided in {@link Format#getNormalizedNewline()}. *

It also provides a default implementation for most of the methods specified by the {@link CharInputReader} interface. *

Extending classes must essentially read characters from a given {@link java.io.Reader} and assign it to the public {@link AbstractCharInputReader#buffer} when requested (in the {@link AbstractCharInputReader#reloadBuffer()} method). * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.Format * @see com.univocity.parsers.common.input.DefaultCharInputReader * @see com.univocity.parsers.common.input.concurrent.ConcurrentCharInputReader */ public abstract class AbstractCharInputReader implements CharInputReader { private final ExpandingCharAppender tmp; private boolean lineSeparatorDetected; private final boolean detectLineSeparator; private List inputAnalysisProcesses; private char lineSeparator1; private char lineSeparator2; private final char normalizedLineSeparator; private long lineCount; private long charCount; private int recordStart; final int whitespaceRangeStart; private boolean skipping = false; private boolean commentProcessing = false; protected final boolean closeOnStop; /** * Current position in the buffer */ public int i; private char ch; /** * The buffer itself */ public char[] buffer; /** * Number of characters available in the buffer. */ public int length = -1; private boolean incrementLineCount; private boolean normalizeLineEndings = true; /** * Creates a new instance that attempts to detect the newlines used in the input automatically. * * @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) that is used to replace any lineSeparator sequence found in the input. * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param closeOnStop indicates whether to automatically close the input when {@link #stop()} is called */ public AbstractCharInputReader(char normalizedLineSeparator, int whitespaceRangeStart, boolean closeOnStop) { this(null, normalizedLineSeparator, whitespaceRangeStart, closeOnStop); } /** * Creates a new instance with the mandatory characters for handling newlines transparently. * * @param lineSeparator the sequence of characters that represent a newline, as defined in {@link Format#getLineSeparator()} * @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) that is used to replace any lineSeparator sequence found in the input. * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param closeOnStop indicates whether to automatically close the input when {@link #stop()} is called */ public AbstractCharInputReader(char[] lineSeparator, char normalizedLineSeparator, int whitespaceRangeStart, boolean closeOnStop) { this.whitespaceRangeStart = whitespaceRangeStart; this.tmp = new ExpandingCharAppender(4096, null, whitespaceRangeStart); if (lineSeparator == null) { detectLineSeparator = true; submitLineSeparatorDetector(); this.lineSeparator1 = '\0'; this.lineSeparator2 = '\0'; } else { setLineSeparator(lineSeparator); this.detectLineSeparator = false; } this.normalizedLineSeparator = normalizedLineSeparator; this.closeOnStop = closeOnStop; } private void submitLineSeparatorDetector() { if (detectLineSeparator && !lineSeparatorDetected) { addInputAnalysisProcess(new LineSeparatorDetector() { @Override protected void apply(char separator1, char separator2) { if (separator1 != '\0') { lineSeparatorDetected = true; lineSeparator1 = separator1; lineSeparator2 = separator2; } else { setLineSeparator(Format.getSystemLineSeparator()); } } }); } } private void setLineSeparator(char[] lineSeparator) { if (lineSeparator == null || lineSeparator.length == 0) { throw new IllegalArgumentException("Invalid line separator. Expected 1 to 2 characters"); } if (lineSeparator.length > 2) { throw new IllegalArgumentException("Invalid line separator. Up to 2 characters are expected. Got " + lineSeparator.length + " characters."); } this.lineSeparator1 = lineSeparator[0]; this.lineSeparator2 = lineSeparator.length == 2 ? lineSeparator[1] : '\0'; } /** * Passes the {@link java.io.Reader} provided in the {@link AbstractCharInputReader#start(Reader)} method to the extending class so it can begin loading characters from it. * * @param reader the {@link java.io.Reader} provided in {@link AbstractCharInputReader#start(Reader)} */ protected abstract void setReader(Reader reader); /** * Informs the extending class that the buffer has been read entirely and requests for another batch of characters. * Implementors must assign the new character buffer to the public {@link AbstractCharInputReader#buffer} attribute, as well as the number of characters available to the public {@link AbstractCharInputReader#length} attribute. * To notify the input does not have any more characters, {@link AbstractCharInputReader#length} must receive the -1 value */ protected abstract void reloadBuffer(); protected final void unwrapInputStream(BomInput.BytesProcessedNotification notification) { InputStream inputStream = notification.input; String encoding = notification.encoding; if (encoding != null) { try { start(new InputStreamReader(inputStream, encoding)); } catch (Exception e) { throw new IllegalStateException(e); } } else { length = -1; start(new InputStreamReader(inputStream), false); } } private void start(Reader reader, boolean resetTmp){ if(resetTmp) { tmp.reset(); } stop(); setReader(reader); lineCount = 0; lineSeparatorDetected = false; submitLineSeparatorDetector(); updateBuffer(); //if the input has been properly decoded with the correct UTF* character set, but has a BOM marker, we can safely discard it. if (length > 0 && buffer[0] == '\uFEFF') { //regardless of the UTF* encoding used, the BOM bytes always produce the '\uFEFF' character when decoded. i++; } } @Override public final void start(Reader reader) { start(reader, true); } /** * Requests the next batch of characters from the implementing class and updates * the character count. * *

If there are no more characters in the input, the reading will stop by invoking the {@link AbstractCharInputReader#stop()} method. */ private void updateBuffer() { if (!commentProcessing && length - recordStart > 0 && buffer != null && !skipping) { tmp.append(buffer, recordStart, length - recordStart); } recordStart = 0; reloadBuffer(); charCount += i; i = 0; if (length == -1) { stop(); incrementLineCount = true; } if (inputAnalysisProcesses != null) { if (length > 0 && length <= 4) { int tmpLength = length; char[] tmp = Arrays.copyOfRange(buffer, 0, length + 1); // length + 1 to assist CSV detection process: length < buffer.length indicates all data was read into the buffer. //sets processes temporarily to null to prevent them running if method `unwrapInputStream` is called. List processes = inputAnalysisProcesses; inputAnalysisProcesses = null; reloadBuffer(); inputAnalysisProcesses = processes; if (length != -1) { char[] newBuffer = new char[tmpLength + buffer.length]; System.arraycopy(tmp, 0, newBuffer, 0, tmpLength); System.arraycopy(buffer, 0, newBuffer, tmpLength, length); buffer = newBuffer; length += tmpLength; } else { buffer = tmp; length = tmpLength; } } try { for (InputAnalysisProcess process : inputAnalysisProcesses) { process.execute(buffer, length); } } finally { if (length > 4) { inputAnalysisProcesses = null; } } } } /** * Submits a custom {@link InputAnalysisProcess} to analyze the input buffer and potentially discover configuration options such as * column separators is CSV, data formats, etc. The process will be execute only once. * * @param inputAnalysisProcess a custom process to analyze the contents of the input buffer. */ public final void addInputAnalysisProcess(InputAnalysisProcess inputAnalysisProcess) { if (inputAnalysisProcess == null) { return; } if (this.inputAnalysisProcesses == null) { inputAnalysisProcesses = new ArrayList(); } inputAnalysisProcesses.add(inputAnalysisProcess); } private void throwEOFException() { if (incrementLineCount) { lineCount++; } ch = '\0'; throw new EOFException(); } @Override public final char nextChar() { if (length == -1) { throwEOFException(); } ch = buffer[i++]; if (i >= length) { updateBuffer(); } if (lineSeparator1 == ch && (lineSeparator2 == '\0' || length != -1 && lineSeparator2 == buffer[i])) { lineCount++; if (normalizeLineEndings) { ch = normalizedLineSeparator; if (lineSeparator2 == '\0') { return ch; } if (++i >= length) { if (length != -1) { updateBuffer(); } else { throwEOFException(); } } } } return ch; } @Override public final char getChar() { return ch; } @Override public final long lineCount() { return lineCount; } @Override public final void skipLines(long lines) { if (lines < 1) { skipping = false; return; } skipping = true; long expectedLineCount = this.lineCount + lines; try { do { nextChar(); } while (lineCount < expectedLineCount); skipping = false; } catch (EOFException ex) { skipping = false; } } @Override public String readComment() { long expectedLineCount = lineCount + 1; commentProcessing = true; tmp.reset(); try { do { char ch = nextChar(); if (ch <= ' ' && whitespaceRangeStart < ch) { ch = skipWhitespace(ch, normalizedLineSeparator, normalizedLineSeparator); } tmp.appendUntil(ch, this, normalizedLineSeparator, normalizedLineSeparator); if (lineCount < expectedLineCount) { tmp.appendIgnoringWhitespace(nextChar()); } else { tmp.updateWhitespace(); return tmp.getAndReset(); } } while (true); } catch (EOFException ex) { tmp.updateWhitespace(); return tmp.getAndReset(); } finally { commentProcessing = false; } } @Override public final long charCount() { return charCount + i; } @Override public final void enableNormalizeLineEndings(boolean normalizeLineEndings) { this.normalizeLineEndings = normalizeLineEndings; } @Override public char[] getLineSeparator() { if (lineSeparator2 != '\0') { return new char[]{lineSeparator1, lineSeparator2}; } else { return new char[]{lineSeparator1}; } } @Override public final char skipWhitespace(char ch, char stopChar1, char stopChar2) { while (ch <= ' ' && ch != stopChar1 && ch != normalizedLineSeparator && ch != stopChar2 && whitespaceRangeStart < ch) { ch = nextChar(); } return ch; } @Override public final int currentParsedContentLength() { return i - recordStart + tmp.length(); } @Override public final String currentParsedContent() { if (tmp.length() == 0) { if (i > recordStart) { return new String(buffer, recordStart, i - recordStart); } return null; } if (i > recordStart) { tmp.append(buffer, recordStart, i - recordStart); } return tmp.getAndReset(); } @Override public final int lastIndexOf(char ch) { if (tmp.length() == 0) { if (i > recordStart) { for (int x = i - 1, c = 0; x >= recordStart; x--, c++) { if (buffer[x] == ch) { return recordStart + c; } } } return -1; } if(i > recordStart){ for (int x = i - 1, c = 0; x >= recordStart; x--, c++) { if (buffer[x] == ch) { return tmp.length() + recordStart + c; } } } return tmp.lastIndexOf(ch); } @Override public final void markRecordStart() { tmp.reset(); recordStart = i % length; } @Override public final boolean skipString(char ch, char stop) { if (i == 0) { return false; } int i = this.i; for (; ch != stop; ch = buffer[i++]) { if (i >= length) { return false; } if (lineSeparator1 == ch && (lineSeparator2 == '\0' || lineSeparator2 == buffer[i])) { break; } } this.i = i - 1; nextChar(); return true; } @Override public final String getString(char ch, char stop, boolean trim, String nullValue, int maxLength) { if (i == 0) { return null; } int i = this.i; for (; ch != stop; ch = buffer[i++]) { if (i >= length) { return null; } if (lineSeparator1 == ch && (lineSeparator2 == '\0' || lineSeparator2 == buffer[i])) { break; } } int pos = this.i - 1; int len = i - this.i; if (maxLength != -1 && len > maxLength) { //validating before trailing whitespace handling so this behaves as an appender. return null; } this.i = i - 1; if (trim) { i = i - 2; while (buffer[i] <= ' ' && whitespaceRangeStart < buffer[i]) { len--; i--; } } String out; if (len <= 0) { out = nullValue; } else { out = new String(buffer, pos, len); } nextChar(); return out; } @Override public final String getQuotedString(char quote, char escape, char escapeEscape, int maxLength, char stop1, char stop2, boolean keepQuotes, boolean keepEscape, boolean trimLeading, boolean trimTrailing) { if (i == 0) { return null; } int i = this.i; while (true) { if (i >= length) { return null; } ch = buffer[i]; if (ch == quote) { if (buffer[i - 1] == escape) { if (keepEscape) { i++; continue; } return null; } if (i + 1 < length) { char next = buffer[i + 1]; if (next == stop1 || next == stop2) { break; } } return null; } else if (ch == escape && !keepEscape) { if (i + 1 < length) { char next = buffer[i + 1]; if (next == quote || next == escapeEscape) { return null; } } } else if (lineSeparator1 == ch && normalizeLineEndings && (lineSeparator2 == '\0' || i + 1 < length && lineSeparator2 == buffer[i + 1])) { return null; } i++; } int pos = this.i; int len = i - this.i; if (maxLength != -1 && len > maxLength) { //validating before trailing whitespace handling so this behaves as an appender. return null; } if (keepQuotes) { pos--; len += 2; } else { if (trimTrailing) { while (len > 0 && buffer[pos + len - 1] <= ' ') { len--; } } if (trimLeading) { while (len > 0 && buffer[pos] <= ' ') { pos++; len--; } } } this.i = i + 1; String out; if (len <= 0) { out = ""; } else { out = new String(buffer, pos, len); } if (this.i >= length) { updateBuffer(); } return out; } public final boolean skipQuotedString(char quote, char escape, char stop1, char stop2) { if (i == 0) { return false; } int i = this.i; while (true) { if (i >= length) { return false; } ch = buffer[i]; if (ch == quote) { if (buffer[i - 1] == escape) { i++; continue; } if (i + 1 < length) { char next = buffer[i + 1]; if (next == stop1 || next == stop2) { break; } } return false; } else if (lineSeparator1 == ch && normalizeLineEndings && (lineSeparator2 == '\0' || i + 1 < length && lineSeparator2 == buffer[i + 1])) { return false; } i++; } this.i = i + 1; if (this.i >= length) { updateBuffer(); } return true; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/BomInput.java000066400000000000000000000150731475274123300332420ustar00rootroot00000000000000/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import java.io.*; import java.nio.charset.*; import static com.univocity.parsers.common.ArgumentUtils.*; /** * A wrapper for an {@link InputStream} that attempts to detect a Byte Order Mark (BOM) in the input * and derive the character encoding that should be used to decode the incoming content. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public final class BomInput extends InputStream { public static final byte[] UTF_8_BOM = toByteArray(0xEF, 0xBB, 0xBF); public static final byte[] UTF_16BE_BOM = toByteArray(0xFE, 0xFF); public static final byte[] UTF_16LE_BOM = toByteArray(0xFF, 0xFE); public static final byte[] UTF_32BE_BOM = toByteArray(0x00, 0x00, 0xFE, 0xFF); public static final byte[] UTF_32LE_BOM = toByteArray(0xFF, 0xFE, 0x00, 0x00); private int bytesRead; private int bytes[] = new int[4]; private String encoding; private int consumed = 0; private final InputStream input; private IOException exception; /** * Wraps an {@link InputStream} and reads the first bytes found on it to attempt to read a BOM. * * @param input the input whose first bytes should be analyzed. */ public BomInput(InputStream input) { this.input = input; try { //This looks shitty on purpose (all in the name of speed). if ((bytes[0] = next()) == 0xEF) { if ((bytes[1] = next()) == 0xBB) { if ((bytes[2] = next()) == 0xBF) { setEncoding("UTF-8"); } } } else if (bytes[0] == 0xFE) { if ((bytes[1] = next()) == 0xFF) { setEncoding("UTF-16BE"); } } else if (bytes[0] == 0xFF) { if ((bytes[1] = next()) == 0xFE) { if ((bytes[2] = next()) == 0x00) { if ((bytes[3] = next()) == 0x00) { setEncoding("UTF-32LE"); } else { setEncoding("UTF-16LE"); //gotcha! } } else { setEncoding("UTF-16LE"); //gotcha! } } } else if (bytes[0] == 0x00) { if ((bytes[1] = next()) == 0x00) { if ((bytes[2] = next()) == 0xFE) { if ((bytes[3] = next()) == 0xFF) { setEncoding("UTF-32BE"); } } } } } catch (IOException e) { // store the exception for later. We want the wrapper to behave exactly like the original input stream and // might need to return any bytes read before this blew up. exception = e; } } private void setEncoding(String encoding) { this.encoding = encoding; if (encoding.equals("UTF-16LE")) { //gotcha! if (bytesRead == 3) { //third byte not a 0x00 bytesRead = 1; bytes[0] = bytes[2]; try { bytes[1] = next(); //reads next byte to be able to decode to a character } catch (Exception e) { exception = (IOException) e; } return; } else if (bytesRead == 4) { //fourth byte not a 0x00 bytesRead = 2; bytes[0] = bytes[2]; bytes[1] = bytes[3]; return; } } this.bytesRead = 0; } private int next() throws IOException { int out = input.read(); bytesRead++; return out; } @Override public final int read() throws IOException { if (bytesRead > 0 && bytesRead > consumed) { int out = bytes[consumed]; // Ensures that if the original input stream returned a byte, it will be consumed. // In case of exceptions, bytes produced prior to the exception will still be returned. // Once the last byte has been consumed, the original exception will be thrown. if (++consumed == bytesRead && exception != null) { throw exception; } return out; } if (consumed == bytesRead) { consumed++; return -1; } throw new BytesProcessedNotification(input, encoding); } /** * Returns a flag indicating whether or not all bytes read from the wrapped input stream have been consumed. This * allows client code to determine if the original input stream can be used directly and safely, or if this * {@code BomInput} wrapper class should be used instead. * * If there are stored bytes that need to be consumed before the wrapped input stream is consumed again, * this method will return {@code true}. * * @return {@code false} if there are no bytes stored and the original input stream can be used directly. If this wrapper * needs to be used to return stored bytes before, then {@code true} will be returned. */ public final boolean hasBytesStored() { return bytesRead > 0; } /** * Returns the detected {@link Charset} determined by the Byte Order Mark (BOM) available in the * input provided in the constructor of this class. * * If no BOM was detected, this method will return {@code null}. * * @return the detected {@link Charset} or {@code null} if a BOM could not be matched. */ public final Charset getCharset() { if (encoding == null) { return null; } return Charset.forName(encoding); } /** * Returns the detected encoding name determined by the Byte Order Mark (BOM) available in the * input provided in the constructor of this class. * * If no BOM was detected, this method will return {@code null}. * * @return the detected encoding name or {@code null} if a BOM could not be matched. */ public final String getEncoding() { return encoding; } /** * Internal notification exception used to re-wrap the original {@link InputStream} into a {@link Reader}. * This is required for performance reasons as overriding {@link InputStream#read()} incurs a heavy performance * penalty when the implementation is native (as in {@link FileInputStream#read()}. */ public static final class BytesProcessedNotification extends RuntimeException { public final InputStream input; public final String encoding; public BytesProcessedNotification(InputStream input, String encoding) { this.input = input; this.encoding = encoding; } @Override public Throwable fillInStackTrace() { return this; } } @Override public void close() throws IOException { input.close(); } } CharAppender.java000077500000000000000000000303431475274123300337620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; /** * * The general interface for classes responsible for appending characters efficiently while handling whitespaces and padding characters. * *

Calls to {@link CharAppender#appendIgnoringWhitespace(char)}, {@link CharAppender#appendIgnoringPadding(char, char)} and {@link CharAppender#appendIgnoringWhitespaceAndPadding(char, char)} should accumulate the * given character and only discard whitespaces/padding if no non-whitespace is appended: * *

For example: * *


 * append('a');                   // accumulated value is now "a";        whitespaceCount = 0;
 * appendIgnoringWhitespace('b'); // accumulated value is now "ab";       whitespaceCount = 0;
 * appendIgnoringWhitespace(' '); // accumulated value remains "ab";      whitespaceCount = 1;
 * appendIgnoringWhitespace(' '); // accumulated value remains "ab";      whitespaceCount = 2;
 * appendIgnoringWhitespace('c'); // accumulated value is now "ab  c";    whitespaceCount = 0;
 * appendIgnoringWhitespace(' '); // accumulated value remains "ab  c";   whitespaceCount = 1;
 * appendIgnoringWhitespace('d'); // accumulated value is now "ab  c d";  whitespaceCount = 0;
 * append(' ');					  // accumulated value is now "ab  c d "; whitespaceCount = 0;
 *  

* *

Implementation note: White spaces should be identified as any character {@code <= ' '} * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface CharAppender extends CharSequence { /** * Appends the given character and marks it as ignored if it is a whitespace ({@code ch <= ' '}) * @param ch character to append */ void appendIgnoringWhitespace(char ch); /** * Appends the given character and marks it as ignored if it is a padding character (the definition of a padding character is implementation dependent.) * @param ch character to append * @param padding the padding character to ignore */ void appendIgnoringPadding(char ch, char padding); /** * Appends the given character and marks it as ignored if it is a whitespace ({@code ch <= ' '}) or a padding character (the definition of a padding character is implementation dependent.) * @param ch character to append * @param padding the padding character to ignore */ void appendIgnoringWhitespaceAndPadding(char ch, char padding); /** * Appends the given character. * @param ch the character to append */ void append(char ch); /** * Returns first the position of a given character * @param ch the character to look for * @param from the starting index from where the search will begin. * @return the position of the given character in the appended content, {@code -1} if not found */ int indexOf(char ch, int from); /** * Returns first the position of a given character sequence * @param charSequence the character sequence to look for * @param from the starting index from where the search will begin. * @return the position of the given character sequence in the appended content, {@code -1} if not found */ int indexOf(char[] charSequence, int from); /** * Returns first the position of a given character sequence * @param charSequence the character sequence to look for * @param from the starting index from where the search will begin. * @return the position of the given character sequence in the appended content, {@code -1} if not found */ int indexOf(CharSequence charSequence, int from); /** * Returns the first position of any given character * @param chars the characters to look for * @param from the starting index from where the search will begin. * @return the position any one of the given characters in the appended content, {@code -1} if none found */ int indexOfAny(char[] chars, int from); /** * Returns a section of the appended content * @param from the starting position in the buffer * @param length the number of characters to accumulate from the given start position * @return a {@code String} with the section of characters accumulated by this appender. */ String substring(int from, int length); /** * Removes a section from the appended content * @param from the starting position in the buffer (inclusive) * @param length the number of characters to accumulate from the given start position */ void remove(int from, int length); /** * Appends the given codepoint. * @param ch the codepoint to append */ void append(int ch); /** * Appends the {@code String} representation of a given object. * @param obj the object whose {@code String} representation will be appended. */ void append(Object obj); /** * Returns the current accumulated value length (the sum of all appended characters - whitespaceCount). * @return the current accumulated value length (the sum of all appended characters - whitespaceCount). */ int length(); /** * Returns the current number of whitespaces accumulated after the last non-whitespace character. *

This is the number of whitespaces accumulated using {@link CharAppender#appendIgnoringWhitespace(char)}, {@link CharAppender#appendIgnoringPadding(char, char)} or {@link CharAppender#appendIgnoringWhitespaceAndPadding(char, char)} * @return the number of whitespaces accumulated using {@link CharAppender#appendIgnoringWhitespace(char)}, {@link CharAppender#appendIgnoringPadding(char, char)} or {@link CharAppender#appendIgnoringWhitespaceAndPadding(char, char)} */ int whitespaceCount(); /** * Resets the number of whitespaces accumulated after the last non-whitespace character. *

This is the number of whitespaces accumulated using {@link CharAppender#appendIgnoringWhitespace(char)}, {@link CharAppender#appendIgnoringPadding(char, char)} or {@link CharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

A subsequent call to {@link CharAppender#whitespaceCount()} should return 0. */ void resetWhitespaceCount(); /** * Returns the accumulated value as a String, discarding any trailing whitespace characters identified when using {@link CharAppender#appendIgnoringWhitespace(char)}, {@link CharAppender#appendIgnoringPadding(char, char)} or {@link CharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

The internal accumulated value is discarded after invoking this method (as in {@link CharAppender#reset()}) * @return a String containing the accumulated characters without the trailing whitespaces. */ String getAndReset(); /** * Clears the accumulated value and the whitespace count. */ void reset(); /** * Returns the accumulated characters, discarding any trailing whitespace characters identified when using {@link CharAppender#appendIgnoringWhitespace(char)}, {@link CharAppender#appendIgnoringPadding(char, char)} or {@link CharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

The internal accumulated value is discarded after invoking this method (as in {@link CharAppender#reset()}) * @return a character array containing the accumulated characters without the trailing whitespaces. */ char[] getCharsAndReset(); /** * Returns the internal character array. * @return the internal character array. */ char[] getChars(); /** * Adds a sequence of repeated characters to the input. * @param ch the character to append * @param length the number of times the given character should be appended. */ void fill(char ch, int length); /** * Prepends the current accumulated value with a character * @param ch the character to prepend in front of the current accumulated value. */ void prepend(char ch); /** * Prepends the current accumulated value with a couple of characters * @param ch1 the first character to prepend in front of the current accumulated value. * @param ch2 the second character to prepend in front of the current accumulated value. */ void prepend(char ch1, char ch2); /** * Prepends the current accumulated value a sequence of characters * @param chars the character sequence to prepend in front of the current accumulated value. */ void prepend(char[] chars); /** * Updates the internal whitespace count of this appender to trim trailing whitespaces. */ void updateWhitespace(); /** * Appends characters from the input, until a stop character is found * @param ch the first character of the input to be appended. * @param input the input whose the following characters will be appended * @param stop the stop character * @return the stop character found on the input. */ char appendUntil(char ch, CharInput input, char stop); /** * Appends characters from the input, until a stop character is found * @param ch the first character of the input to be appended. * @param input the input whose the following characters will be appended * @param stop1 the first stop character * @param stop2 the second stop character * @return one of the stop characters found on the input. */ char appendUntil(char ch, CharInput input, char stop1, char stop2); /** * Appends characters from the input, until a stop character is found * @param ch the first character of the input to be appended. * @param input the input whose the following characters will be appended * @param stop1 the first stop character * @param stop2 the second stop character * @param stop3 the third stop character * @return one of the stop characters found on the input. */ char appendUntil(char ch, CharInput input, char stop1, char stop2, char stop3); /** * Appends characters from an input array * @param ch the character array * @param from the position of the first character in the array to be appended * @param length the number of characters to be appended from the given posiion. */ void append(char[] ch, int from, int length); /** * Appends characters from an input array * @param ch the character array */ void append(char[] ch); /** * Appends codepoints from an input array * @param ch the codepoint array */ void append(int[] ch); /** * Appends characters from an input {@code String} * @param string the input String */ void append(String string); /** * Appends the contents of a String to this appender * * @param string the string whose characters will be appended. * @param from the index of the first character to append * @param to the index of the last character to append */ void append(String string, int from, int to); /** * Ignores the given number of characters at the end of the appended content, * effectively marking these as whitespace. Invoking {@link #resetWhitespaceCount()} * or {@link #updateWhitespace()} will undo this effect. * * @param count the number of characters to ignore */ void ignore(int count); /** * Deletes a given number of characters from the end of the appended content. * Will reset the internal whitespace count if any. Invoke {@link #updateWhitespace()} * to recalculate the number of trailing whitespaces in the appended content. * @param count the number of characters to delete. */ void delete(int count); /** * Indicates whether this appender represents an empty {@code String}. * @return {@code} true calling {@link #getAndReset()} would return {@code null}, otherwise {@code false}. */ boolean isEmpty(); /** * Returns the last index of a given character in the current appended (characters that have been marked as whitespace will be ignored) * @param ch the character to look for * @return the last position of the given character in the appended content, or {@code -1} if not found. */ int lastIndexOf(char ch); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/CharInput.java000077500000000000000000000027621475274123300334060ustar00rootroot00000000000000/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; /** * A (very) basic character input definition. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see Format */ public interface CharInput { /** * Returns the next character in the input. * * @return the next character in the input. '\0' if there are no more characters in the input or if the CharInput is stopped. */ char nextChar(); /** * Returns the last character returned by the {@link #nextChar()} method. * * @return the last character returned by the {@link #nextChar()} method.'\0' if there are no more characters in the input or if the CharInput is stopped. */ char getChar(); }CharInputReader.java000077500000000000000000000240241475274123300344450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; import java.io.*; /** * The definition of a character input reader used by all univocity-parsers that extend {@link AbstractParser}. * *

This interface declares basic functionalities to provide a common input manipulation structure for all parser classes. *

Implementations of this interface MUST convert the sequence of newline characters defined by {@link Format#getLineSeparator()} into the normalized newline character provided in {@link Format#getNormalizedNewline()}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.Format */ public interface CharInputReader extends CharInput { /** * Initializes the CharInputReader implementation with a {@link java.io.Reader} which provides access to the input. * * @param reader A {@link java.io.Reader} that provides access to the input. */ void start(Reader reader); /** * Stops the CharInputReader from reading characters from the {@link java.io.Reader} provided in {@link CharInputReader#start(Reader)} and closes it. */ void stop(); /** * Returns the next character in the input provided by the active {@link java.io.Reader}. *

If the input contains a sequence of newline characters (defined by {@link Format#getLineSeparator()}), this method will automatically converted them to the newline character specified in {@link Format#getNormalizedNewline()}. *

A subsequent call to this method will return the character after the newline sequence. * * @return the next character in the input. '\0' if there are no more characters in the input or if the CharInputReader was stopped. */ char nextChar(); /** * Returns the last character returned by the {@link #nextChar()} method. * * @return the last character returned by the {@link #nextChar()} method.'\0' if there are no more characters in the input or if the CharInputReader was stopped. */ char getChar(); /** * Returns the number of characters returned by {@link CharInputReader#nextChar()} at any given time. * * @return the number of characters returned by {@link CharInputReader#nextChar()} */ long charCount(); /** * Returns the number of newlines read so far. * * @return the number of newlines read so far. */ long lineCount(); /** * Skips characters in the input until the given number of lines is discarded. * * @param lineCount the number of lines to skip from the current location in the input */ void skipLines(long lineCount); /** * Collects the comment line found on the input. * * @return the text found in the comment from the current position. */ String readComment(); /** * Indicates to the input reader that the parser is running in "escape" mode and * new lines should be returned as-is to prevent modifying the content of the parsed value. * * @param escaping flag indicating that the parser is escaping values and line separators are to be returned as-is. */ void enableNormalizeLineEndings(boolean escaping); /** * Returns the line separator by this character input reader. This could be the line separator defined * in the {@link Format#getLineSeparator()} configuration, or the line separator sequence identified automatically * when {@link CommonParserSettings#isLineSeparatorDetectionEnabled()} evaluates to {@code true}. * * @return the line separator in use. */ char[] getLineSeparator(); /** * Skips characters from the current input position, until a non-whitespace character, or a stop character is found * * @param current the current character of the input * @param stopChar1 the first stop character (which can be a whitespace) * @param stopChar2 the second character (which can be a whitespace) * * @return the first non-whitespace character (or delimiter) found in the input. */ char skipWhitespace(char current, char stopChar1, char stopChar2); /** * Returns the length of the character sequence parsed to produce the current record. * @return the length of the text content parsed for the current input record */ int currentParsedContentLength(); /** * Returns a String with the input character sequence parsed to produce the current record. * * @return the text content parsed for the current input record. */ String currentParsedContent(); /** * Returns the last index of a given character in the current parsed content * @param ch the character to look for * @return the last position of the given character in the current parsed content, or {@code -1} if not found. */ int lastIndexOf(char ch); /** * Marks the start of a new record in the input, used internally to calculate the result of {@link #currentParsedContent()} */ void markRecordStart(); /** * Attempts to collect a {@code String} from the current position until a stop character is found on the input, * or a line ending is reached. If the {@code String} can be obtained, the current position of the parser will be updated to * the last consumed character. If the internal buffer needs to be reloaded, this method will return {@code null} * and the current position of the buffer will remain unchanged. * * @param ch the current character to be considered. If equal to the stop character the {@code nullValue} will be returned * @param stop the stop character that identifies the end of the content to be collected * @param trim flag indicating whether or not trailing whitespaces should be discarded * @param nullValue value to return when the length of the content to be returned is {@code 0}. * @param maxLength the maximum length of the {@code String} to be returned. If the length exceeds this limit, {@code null} will be returned * * @return the {@code String} found on the input, or {@code null} if the buffer needs to reloaded or the maximum length has been exceeded. */ String getString(char ch, char stop, boolean trim, String nullValue, int maxLength); /** * Attempts to skip a {@code String} from the current position until a stop character is found on the input, * or a line ending is reached. If the {@code String} can be skipped, the current position of the parser will be updated to * the last consumed character. If the internal buffer needs to be reloaded, this method will return {@code false} * and the current position of the buffer will remain unchanged. * * @param ch the current character to be considered. If equal to the stop character {@code false} will be returned * @param stop the stop character that identifies the end of the content to be collected * * @return {@code true} if an entire {@code String} value was found on the input and skipped, or {@code false} if the buffer needs to reloaded. */ boolean skipString(char ch, char stop); /** * Attempts to collect a quoted {@code String} from the current position until a closing quote or stop character is found on the input, * or a line ending is reached. If the {@code String} can be obtained, the current position of the parser will be updated to * the last consumed character. If the internal buffer needs to be reloaded, this method will return {@code null} * and the current position of the buffer will remain unchanged. * * @param quote the quote character * @param escape the quote escape character * @param escapeEscape the escape of the quote escape character * @param maxLength the maximum length of the {@code String} to be returned. If the length exceeds this limit, {@code null} will be returned * @param stop1 the first stop character that identifies the end of the content to be collected * @param stop2 the second stop character that identifies the end of the content to be collected * @param keepQuotes flag to indicate the quotes that wrap the resulting {@code String} should be kept. * @param keepEscape flag to indicate that escape sequences should be kept * @param trimLeading flag to indicate leading whitespaces should be trimmed * @param trimTrailing flag to indicate that trailing whitespaces should be trimmed * @return the {@code String} found on the input, or {@code null} if the buffer needs to reloaded or the maximum length has been exceeded. */ String getQuotedString(char quote, char escape, char escapeEscape, int maxLength, char stop1, char stop2, boolean keepQuotes, boolean keepEscape, boolean trimLeading, boolean trimTrailing); /** * Attempts to skip a quoted {@code String} from the current position until a stop character is found on the input, * or a line ending is reached. If the {@code String} can be skipped, the current position of the parser will be updated to * the last consumed character. If the internal buffer needs to be reloaded, this method will return {@code false} * and the current position of the buffer will remain unchanged. * * @param quote the quote character * @param escape the quote escape character * @param stop1 the first stop character that identifies the end of the content to be collected * @param stop2 the second stop character that identifies the end of the content to be collected * * @return {@code true} if an entire {@code String} value was found on the input and skipped, or {@code false} if the buffer needs to reloaded. */ boolean skipQuotedString(char quote, char escape, char stop1, char stop2); }DefaultCharAppender.java000077500000000000000000000275101475274123300352710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; /** * Default implementation of the {@link CharAppender} interface */ public class DefaultCharAppender implements CharAppender { final int whitespaceRangeStart; final char[] emptyChars; // default value to return when no characters have been accumulated char[] chars; int index; final String emptyValue; // default value to return when no characters have been accumulated int whitespaceCount; /** * Creates a DefaultCharAppender with a maximum limit of characters to append and the default value to return when no characters have been accumulated. * The padding character is defaulted to a whitespace character ' '. * * @param maxLength maximum limit of characters to append * @param emptyValue default value to return when no characters have been accumulated * @param whitespaceRangeStart starting range of characters considered to be whitespace. */ public DefaultCharAppender(int maxLength, String emptyValue, int whitespaceRangeStart) { this.whitespaceRangeStart = whitespaceRangeStart; this.chars = new char[maxLength]; this.emptyValue = emptyValue; if (emptyValue == null) { emptyChars = null; } else { emptyChars = emptyValue.toCharArray(); } } @Override public void appendIgnoringPadding(char ch, char padding) { chars[index++] = ch; if (ch == padding) { whitespaceCount++; } else { whitespaceCount = 0; } } @Override public void appendIgnoringWhitespaceAndPadding(char ch, char padding) { chars[index++] = ch; if (ch == padding || (ch <= ' ' && whitespaceRangeStart < ch)) { whitespaceCount++; } else { whitespaceCount = 0; } } @Override public void appendIgnoringWhitespace(char ch) { chars[index++] = ch; if (ch <= ' ' && whitespaceRangeStart < ch) { whitespaceCount++; } else { whitespaceCount = 0; } } @Override public int indexOf(char ch, int from) { int len = index - whitespaceCount; for (int i = from; i < len; i++) { if (chars[i] == ch) { return i; } } return -1; } @Override public int indexOfAny(char[] chars, int from) { int len = index - whitespaceCount; for (int i = from; i < len; i++) { for (int j = 0; j < chars.length; j++) { if (this.chars[i] == chars[j]) { return i; } } } return -1; } @Override public String substring(int from, int length) { return new String(chars, from, length); } @Override public void remove(int from, int length) { if (length > 0) { int srcPos = from + length; int len = index - length; if (srcPos + len > index) { len = len - from; } System.arraycopy(chars, srcPos, chars, from, len); index -= length; } } @Override public void append(char ch) { chars[index++] = ch; } @Override public final void append(Object o) { append(String.valueOf(o)); } @Override public final void append(int ch) { if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { append((char) ch); } else { int off = ch - Character.MIN_SUPPLEMENTARY_CODE_POINT; append((char) ((off >>> 10) + Character.MIN_HIGH_SURROGATE)); append((char) ((off & 0x3ff) + Character.MIN_LOW_SURROGATE)); } } @Override public final void append(int[] ch) { for (int i = 0; i < ch.length; i++) { append(ch[i]); } } /** * Returns the accumulated value as a String, discarding any trailing whitespace characters identified when using {@link DefaultCharAppender#appendIgnoringWhitespace(char)}, {@link DefaultCharAppender#appendIgnoringPadding(char, char)} or {@link DefaultCharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

The internal accumulated value is discarded after invoking this method (as in {@link DefaultCharAppender#reset()}) *

If the accumulated value is empty (i.e. no characters were appended, or all appended characters where ignored as whitespace or padding), then the return value will be {@link DefaultCharAppender#emptyValue} attribute defined in the constructor of this class. * * @return a String containing the accumulated characters without the trailing white spaces. Or the {@link DefaultCharAppender#emptyValue} defined in the constructor of this class. */ @Override public String getAndReset() { String out = emptyValue; if (index > whitespaceCount) { out = new String(chars, 0, index - whitespaceCount); } index = 0; whitespaceCount = 0; return out; } /** * Returns the accumulated value as a String, discarding any trailing whitespace characters identified when using {@link DefaultCharAppender#appendIgnoringWhitespace(char)}, {@link DefaultCharAppender#appendIgnoringPadding(char, char)} or {@link DefaultCharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

Does not discard the accumulated value. *

If the accumulated value is empty (i.e. no characters were appended, or all appended characters where ignored as whitespace or padding), then the return value will be {@link DefaultCharAppender#emptyValue} attribute defined in the constructor of this class. * * @return a String containing the accumulated characters without the trailing white spaces. Or the {@link DefaultCharAppender#emptyValue} defined in the constructor of this class. */ @Override public final String toString() { if (index <= whitespaceCount) { return emptyValue; } return new String(chars, 0, index - whitespaceCount); } @Override public final int length() { return index - whitespaceCount; } /** * Returns the accumulated characters, discarding any trailing whitespace characters identified when using {@link DefaultCharAppender#appendIgnoringWhitespace(char)}, {@link DefaultCharAppender#appendIgnoringPadding(char, char)} or {@link DefaultCharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

The internal accumulated value is discarded after invoking this method (as in {@link DefaultCharAppender#reset()}) *

If the accumulated value is empty (i.e. no characters were appended, or all appended characters where ignored as whitespace or padding), then the return value will be character sequence of the {@link DefaultCharAppender#emptyValue} attribute defined in the constructor of this class. * * @return a character array containing the accumulated characters without the trailing white spaces. Or the characters of the {@link DefaultCharAppender#emptyValue} defined in the constructor of this class. */ @Override public char[] getCharsAndReset() { char[] out = emptyChars; if (index > whitespaceCount) { int length = index - whitespaceCount; out = new char[length]; System.arraycopy(chars, 0, out, 0, length); } index = 0; whitespaceCount = 0; return out; } @Override public final int whitespaceCount() { return whitespaceCount; } @Override public void reset() { index = 0; whitespaceCount = 0; } /** * Appends the contents of another DefaultCharAppender, discarding any of its trailing whitespace characters * * @param appender The DefaultCharAppender instance got get contents from. */ public void append(DefaultCharAppender appender) { System.arraycopy(appender.chars, 0, this.chars, this.index, appender.index - appender.whitespaceCount); this.index += appender.index - appender.whitespaceCount; appender.reset(); } @Override public final void resetWhitespaceCount() { whitespaceCount = 0; } @Override public final char[] getChars() { return chars; } @Override public void fill(char ch, int length) { for (int i = 0; i < length; i++) { chars[index++] = ch; } } /** * Prepends the current accumulated value with a character * * @param ch the character to prepend in front of the current accumulated value. */ @Override public void prepend(char ch) { System.arraycopy(chars, 0, this.chars, 1, index); chars[0] = ch; index++; } @Override public void prepend(char ch1, char ch2) { System.arraycopy(chars, 0, this.chars, 2, index); chars[0] = ch1; chars[1] = ch2; index += 2; } @Override public void prepend(char[] chars) { System.arraycopy(this.chars, 0, this.chars, chars.length, index); System.arraycopy(chars, 0, this.chars, 0, chars.length); index += chars.length; } /** * Updates the internal whitespace count of this appender to trim trailing whitespaces. */ public final void updateWhitespace() { whitespaceCount = 0; for (int i = index - 1; i >= 0 && chars[i] <= ' ' && whitespaceRangeStart < chars[i]; i--, whitespaceCount++) ; } public char appendUntil(char ch, CharInput input, char stop) { for (; ch != stop; ch = input.nextChar()) { chars[index++] = ch; } return ch; } public char appendUntil(char ch, CharInput input, char stop1, char stop2) { for (; ch != stop1 && ch != stop2; ch = input.nextChar()) { chars[index++] = ch; } return ch; } public char appendUntil(char ch, CharInput input, char stop1, char stop2, char stop3) { for (; ch != stop1 && ch != stop2 && ch != stop3; ch = input.nextChar()) { chars[index++] = ch; } return ch; } @Override public void append(char[] ch, int from, int length) { System.arraycopy(ch, from, chars, index, length); index += length; } @Override public final void append(char[] ch) { append(ch, 0, ch.length); } public void append(String string, int from, int to) { string.getChars(from, to, chars, index); index += to - from; } @Override public final void append(String string) { append(string, 0, string.length()); } @Override public final char charAt(int i) { return chars[i]; } @Override public final String subSequence(int from, int to) { return new String(chars, from, to - from); } @Override public final void ignore(int count) { whitespaceCount += count; } @Override public void delete(int count) { index -= count; if (index < 0) { index = 0; } whitespaceCount = 0; } @Override public int indexOf(char[] charSequence, int fromIndex) { if (charSequence.length == 0) { return fromIndex; } if (fromIndex >= index) { return -1; } char first = charSequence[0]; int max = index - charSequence.length; for (int i = fromIndex; i <= max; i++) { if (chars[i] != first) { while (++i <= max && chars[i] != first) ; } if (i <= max) { int j = i + 1; int end = j + charSequence.length - 1; for (int k = 1; j < end && chars[j] == charSequence[k]; j++, k++) ; if (j == end) { return i; } } } return -1; } @Override public int indexOf(CharSequence charSequence, int fromIndex) { if (charSequence.length() == 0) { return fromIndex; } if (fromIndex >= index) { return -1; } char first = charSequence.charAt(0); int max = index - charSequence.length(); for (int i = fromIndex; i <= max; i++) { if (chars[i] != first) { while (++i <= max && chars[i] != first) ; } if (i <= max) { int j = i + 1; int end = j + charSequence.length() - 1; for (int k = 1; j < end && chars[j] == charSequence.charAt(k); j++, k++) ; if (j == end) { return i; } } } return -1; } @Override public boolean isEmpty() { return index > whitespaceCount; } @Override public int lastIndexOf(char ch) { for (int x = index - whitespaceCount -1; x >= 0; x--) { if (chars[x] == ch) { return x; } } return -1; } } DefaultCharInputReader.java000077500000000000000000000077201475274123300357560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; import java.io.*; /** * A default CharInputReader which only loads batches of characters when requested by the {@link AbstractCharInputReader} through the {@link DefaultCharInputReader#reloadBuffer} method. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class DefaultCharInputReader extends AbstractCharInputReader { private Reader reader; private boolean unwrapping = false; /** * Creates a new instance with the mandatory characters for handling newlines transparently. Line separators will be detected automatically. * * @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) that is used to replace any lineSeparator sequence found in the input. * @param bufferSize the buffer size used to store characters read from the input. * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param closeOnStop indicates whether to automatically close the input when {@link #stop()} is called */ public DefaultCharInputReader(char normalizedLineSeparator, int bufferSize, int whitespaceRangeStart, boolean closeOnStop) { super(normalizedLineSeparator, whitespaceRangeStart, closeOnStop); super.buffer = new char[bufferSize]; } /** * Creates a new instance with the mandatory characters for handling newlines transparently. * * @param lineSeparator the sequence of characters that represent a newline, as defined in {@link Format#getLineSeparator()} * @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) that is used to replace any lineSeparator sequence found in the input. * @param bufferSize the buffer size used to store characters read from the input. * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param closeOnStop indicates whether to automatically close the input when {@link #stop()} is called */ public DefaultCharInputReader(char[] lineSeparator, char normalizedLineSeparator, int bufferSize, int whitespaceRangeStart, boolean closeOnStop) { super(lineSeparator, normalizedLineSeparator, whitespaceRangeStart, closeOnStop); super.buffer = new char[bufferSize]; } @Override public void stop() { try { if (!unwrapping && closeOnStop && reader != null) { reader.close(); } } catch (IOException e) { throw new IllegalStateException("Error closing input", e); } } @Override protected void setReader(Reader reader) { this.reader = reader; unwrapping = false; } /** * Copies a sequence of characters from the input into the {@link DefaultCharInputReader#buffer}, and updates the {@link DefaultCharInputReader#length} to the number of characters read. */ @Override public void reloadBuffer() { try { super.length = reader.read(buffer, 0, buffer.length); } catch (IOException e) { throw new IllegalStateException("Error reading from input", e); } catch (BomInput.BytesProcessedNotification notification) { unwrapping = true; unwrapInputStream(notification); } } } EOFException.java000066400000000000000000000022041475274123300337060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; /** * Internal exception marker to signalize the end of the input. */ public final class EOFException extends RuntimeException { private static final long serialVersionUID = -4064380464076294133L; /** * Creates a new exception */ public EOFException() { super(); } @Override public Throwable fillInStackTrace() { return this; } } ElasticCharAppender.java000066400000000000000000000037531475274123300352710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/inputpackage com.univocity.parsers.common.input; /** * A character appender that restores its internal buffer size after expanding to accommodate larger contents. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public class ElasticCharAppender extends ExpandingCharAppender { private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private int defaultLength; public ElasticCharAppender(String emptyValue) { this(4096, emptyValue); } public ElasticCharAppender(int defaultLength, String emptyValue) { super(defaultLength, emptyValue, 0); this.defaultLength = defaultLength; } @Override public String getAndReset() { String out = super.getAndReset(); if (chars.length > defaultLength) { chars = new char[defaultLength]; } return out; } @Override public char[] getCharsAndReset() { char[] out = super.getCharsAndReset(); if (chars.length > defaultLength) { chars = new char[defaultLength]; } return out; } @Override public void reset() { if (chars.length > defaultLength) { chars = new char[defaultLength]; } super.reset(); } public String getTrimmedStringAndReset() { int length = index - whitespaceCount; int start = 0; while (start < length && chars[start] <= ' ') { start++; } if (start >= length) { return emptyValue; } while (chars[length - 1] <= ' ') { length--; } length -= start; if (length <= 0) { return emptyValue; } String out = new String(chars, start, length); reset(); return out; } public char[] getTrimmedCharsAndReset() { int length = index - whitespaceCount; int start = 0; while (start < length && chars[start] <= ' ') { start++; } if (start >= length) { return EMPTY_CHAR_ARRAY; } while (chars[length - 1] <= ' ') { length--; } length -= start; if (length <= 0) { return EMPTY_CHAR_ARRAY; } char[] out = new char[length]; System.arraycopy(chars, start, out, 0, length); reset(); return out; } } ExpandingCharAppender.java000066400000000000000000000137621475274123300356230ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; import java.util.*; /** * An implementation {@link CharAppender} that expands the internal buffer of characters as required. * * @author Univocity Software Pty Ltd - dev@univocity.com */ public class ExpandingCharAppender extends DefaultCharAppender { private static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8; /** * Creates an {@code ExpandingCharAppender} a the default value to return when no characters have been accumulated. * The padding character is defaulted to a whitespace character ' '. * * @param emptyValue default value to return when no characters have been accumulated * @param whitespaceRangeStart starting range of characters considered to be whitespace. */ public ExpandingCharAppender(String emptyValue, int whitespaceRangeStart) { this(8192, emptyValue, whitespaceRangeStart); } /** * Creates an {@code ExpandingCharAppender} a the default value to return when no characters have been accumulated. * The padding character is defaulted to a whitespace character ' '. * * @param initialBufferLength the initial length of the internal buffer. * @param emptyValue default value to return when no characters have been accumulated * @param whitespaceRangeStart starting range of characters considered to be whitespace. */ public ExpandingCharAppender(int initialBufferLength, String emptyValue, int whitespaceRangeStart) { super(initialBufferLength, emptyValue, whitespaceRangeStart); } @Override public void appendIgnoringWhitespace(char ch) { try { super.appendIgnoringWhitespace(ch); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); super.appendIgnoringWhitespace(ch); } } @Override public void appendIgnoringPadding(char ch, char padding) { try { super.appendIgnoringPadding(ch, padding); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); super.appendIgnoringPadding(ch, padding); } } @Override public void appendIgnoringWhitespaceAndPadding(char ch, char padding) { try { super.appendIgnoringWhitespaceAndPadding(ch, padding); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); super.appendIgnoringWhitespaceAndPadding(ch, padding); } } @Override public void append(char ch) { try { super.append(ch); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); super.append(ch); } } @Override public final void fill(char ch, int length) { try { super.fill(ch, length); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); super.fill(ch, length); } } final void expandAndRetry() { expand(); index--; } private void expand(int additionalLength, double factor) { if (chars.length == MAX_ARRAY_LENGTH) { throw new TextParsingException(null, "Can't expand internal appender array to over " + MAX_ARRAY_LENGTH + " characters in length."); } chars = Arrays.copyOf(chars, (int) Math.min(((index + additionalLength) * factor), MAX_ARRAY_LENGTH)); } final void expand() { expand(0, 2.0); } final void expand(int additionalLength) { expand(additionalLength, 1.5); } @Override public final void prepend(char ch) { try { super.prepend(ch); } catch (ArrayIndexOutOfBoundsException e) { expand(); super.prepend(ch); } } @Override public final void prepend(char ch1, char ch2) { try { super.prepend(ch1, ch2); } catch (ArrayIndexOutOfBoundsException e) { expand(2); super.prepend(ch1, ch2); } } @Override public final void prepend(char[] chars) { try { super.prepend(chars); } catch (ArrayIndexOutOfBoundsException e) { expand(chars.length); super.prepend(chars); } } public final void append(DefaultCharAppender appender) { try { super.append(appender); } catch (ArrayIndexOutOfBoundsException e) { expand(appender.index); this.append(appender); } } public final char appendUntil(char ch, CharInput input, char stop) { try { return super.appendUntil(ch, input, stop); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); return this.appendUntil(input.getChar(), input, stop); } } public final char appendUntil(char ch, CharInput input, char stop1, char stop2) { try { return super.appendUntil(ch, input, stop1, stop2); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); return this.appendUntil(input.getChar(), input, stop1, stop2); } } public final char appendUntil(char ch, CharInput input, char stop1, char stop2, char stop3) { try { return super.appendUntil(ch, input, stop1, stop2, stop3); } catch (ArrayIndexOutOfBoundsException e) { expandAndRetry(); return this.appendUntil(input.getChar(), input, stop1, stop2, stop3); } } @Override public final void append(char[] ch, int from, int length) { if (index + length <= chars.length) { super.append(ch, from, length); } else { chars = Arrays.copyOf(chars, Math.min(((chars.length + length + index)), MAX_ARRAY_LENGTH)); super.append(ch, from, length); } } public final void append(String string, int from, int to) { try { super.append(string, from, to); } catch (IndexOutOfBoundsException e) { expand(to - from); super.append(string, from, to); } } } InputAnalysisProcess.java000066400000000000000000000032501475274123300355620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; /** * A process to be executed over a sample of data being parsed. When {@link AbstractCharInputReader#reloadBuffer()} loads a batch of characters from the input, * the {@code InputAnalysisProcess} will be executed and then discarded. * *

Parsers can implement their custom analysis processes to identify patterns and attempt to automatically derive configuration options to process the input * by calling {@link AbstractCharInputReader#addInputAnalysisProcess(InputAnalysisProcess)} at any time.

* * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface InputAnalysisProcess { /** * A sequence of characters of the input buffer to be analyzed. * @param characters the input buffer * @param length the last character position loaded into the buffer. */ void execute(char[] characters, int length); } LineSeparatorDetector.java000066400000000000000000000036061475274123300356670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; /** * An {@link InputAnalysisProcess} to detect the line separators used in the input. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class LineSeparatorDetector implements InputAnalysisProcess { @Override public void execute(char[] characters, int length) { char separator1 = '\0'; char separator2 = '\0'; for (int c = 0; c < length; c++) { char ch = characters[c]; if (ch == '\n' || ch == '\r') { if (separator1 == '\0') { separator1 = ch; } else { separator2 = ch; break; } } else if (separator1 != '\0') { break; } } char lineSeparator1 = separator1; char lineSeparator2 = separator2; if (separator1 != '\0') { if (separator1 == '\n') { lineSeparator1 = '\n'; lineSeparator2 = '\0'; } else { lineSeparator1 = '\r'; if (separator2 == '\n') { lineSeparator2 = '\n'; } else { lineSeparator2 = '\0'; } } } apply(lineSeparator1, lineSeparator2); } protected abstract void apply(char lineSeparator1, char lineSeparator2); } LookaheadCharInputReader.java000066400000000000000000000174171475274123300362620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import java.io.*; import java.util.*; /** * A special implementation of {@link CharInputReader} that wraps another {@link CharInputReader} and * collects a sequence of characters from the wrapped input, in order to analyze what the buffer contains * ahead of the current position. */ public class LookaheadCharInputReader implements CharInputReader { private final CharInputReader reader; private char[] lookahead = new char[0]; private int length = 0; private int start = 0; private final char newLine; private char delimiter; private final int whitespaceRangeStart; /** * Creates a lookahead input reader by wrapping a given {@link CharInputReader} implementation * * @param reader the input reader whose characters will read and stored in a limited internal buffer, * in order to allow a parser to query what the characters are available ahead of the current input position. * @param newLine the normalized character that represents a line ending. Used internally as a stop character. * @param whitespaceRangeStart starting range of characters considered to be whitespace. */ public LookaheadCharInputReader(CharInputReader reader, char newLine, int whitespaceRangeStart) { this.reader = reader; this.newLine = newLine; this.whitespaceRangeStart = whitespaceRangeStart; } /** * Matches a sequence of characters against the current lookahead buffer. * * @param current the last character used by the parser, which should match the first character in the lookahead buffer * @param sequence the expected sequence of characters after the current character, that are expected appear in the current lookahead buffer * @param wildcard character used in the sequence as a wildcard (e.g. * or ?), meaning any character is acceptable in its place. * * @return {@code true} if the current character and the sequence characters that follows are present in the lookahead, otherwise {@code false} */ public boolean matches(char current, char[] sequence, char wildcard) { if (sequence.length > length - start) { return false; } if (sequence[0] != current && sequence[0] != wildcard) { return false; } for (int i = 1; i < sequence.length; i++) { char ch = sequence[i]; if (ch != wildcard && ch != lookahead[i - 1 + start]) { return false; } } return true; } /** * Matches a sequence of characters against the current lookahead buffer. * * @param sequence the expected sequence of characters that are expected appear in the current lookahead buffer * @param wildcard character used in the sequence as a wildcard (e.g. * or ?), meaning any character is acceptable in its place. * * @return {@code true} if the given sequence of characters is present in the lookahead, otherwise {@code false} */ public boolean matches(char[] sequence, char wildcard) { if (sequence.length > length - start) { return false; } for (int i = 0; i < sequence.length; i++) { char ch = sequence[i]; if (ch != wildcard && sequence[i] != lookahead[i + start]) { return false; } } return true; } /** * Returns the current lookahead value. * * @return the current lookahead value, or an empty {@code String} if the lookahead buffer is empty. */ public String getLookahead() { if (start >= length) { return ""; } return new String(lookahead, start, length); } /** * Returns the lookahead value prepended with the current character * * @param current the current character obtained by the parser * * @return a {@code String} formed by the given character followed by the lookahead value (if any). */ public String getLookahead(char current) { if (start >= length) { return String.valueOf(current); } return current + new String(lookahead, start, length - 1); } /** * Fills the lookahead buffer with a given number of characters that will be extracted from the wrapped {@link CharInputReader} * * @param numberOfCharacters the number of characters to read from the wrapped {@link CharInputReader}, given in the constructor of this class. */ public void lookahead(int numberOfCharacters) { numberOfCharacters += length - start; if (lookahead.length < numberOfCharacters) { lookahead = Arrays.copyOf(lookahead, numberOfCharacters); } if (start >= length) { start = 0; length = 0; } try { numberOfCharacters -= length; while (numberOfCharacters-- > 0) { lookahead[length] = reader.nextChar(); length++; } } catch (EOFException ex) { //ignore. } } @Override public void start(Reader reader) { this.reader.start(reader); } @Override public void stop() { this.reader.stop(); } @Override public char nextChar() { if (start >= length) { return reader.nextChar(); } else { return lookahead[start++]; } } @Override public long charCount() { return reader.charCount(); } @Override public long lineCount() { return reader.lineCount(); } @Override public void skipLines(long lineCount) { reader.skipLines(lineCount); } @Override public void enableNormalizeLineEndings(boolean escaping) { reader.enableNormalizeLineEndings(escaping); } @Override public String readComment() { return reader.readComment(); } @Override public char[] getLineSeparator() { return reader.getLineSeparator(); } @Override public final char getChar() { if (start != 0 && start >= length) { return reader.getChar(); } else { return lookahead[start - 1]; } } @Override public char skipWhitespace(char ch, char stopChar1, char stopChar2) { while (start < length && ch <= ' ' && ch != stopChar1 && ch != newLine && ch != stopChar2 && whitespaceRangeStart < ch) { ch = lookahead[start++]; } return reader.skipWhitespace(ch, stopChar1, stopChar2); } @Override public String currentParsedContent() { return reader.currentParsedContent(); } @Override public void markRecordStart() { reader.markRecordStart(); } @Override public String getString(char ch, char stop, boolean trim, String nullValue, int maxLength) { return reader.getString(ch, stop, trim, nullValue, maxLength); } @Override public String getQuotedString(char quote, char escape, char escapeEscape, int maxLength, char stop1, char stop2, boolean keepQuotes, boolean keepEscape, boolean trimLeading, boolean trimTrailing) { return reader.getQuotedString(quote, escape, escapeEscape, maxLength, stop1, stop2, keepQuotes, keepEscape, trimLeading, trimTrailing); } @Override public int currentParsedContentLength() { return reader.currentParsedContentLength(); } @Override public boolean skipString(char ch, char stop) { return reader.skipString(ch, stop); } @Override public boolean skipQuotedString(char quote, char escape, char stop1, char stop2) { return reader.skipQuotedString(quote, escape, stop1, stop2); } @Override public int lastIndexOf(char ch) { return reader.lastIndexOf(ch); } public void reloadBuffer() { if (reader instanceof DefaultCharInputReader) { ((DefaultCharInputReader) reader).reloadBuffer(); } } } NoopCharAppender.java000077500000000000000000000127361475274123300346240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; /** * An implementation of {@link CharAppender} that does nothing. Used by {@link ParserOutput} to transparently discard any unwanted input while parsing. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.ParserOutput * @see com.univocity.parsers.common.input.CharAppender */ public class NoopCharAppender implements CharAppender { private static final NoopCharAppender instance = new NoopCharAppender(); /** * Returns the singleton instance of NoopCharAppender * * @return the singleton instance of NoopCharAppender */ public static CharAppender getInstance() { return instance; } /** * This is a singleton class and cannot be instantiated. Use {@link NoopCharAppender#getInstance()}. */ private NoopCharAppender() { } /** * Returns -1 as this appender does nothing. * * @return -1 as this appender does nothing. */ @Override public int length() { return -1; } /** * Returns null as this appender does nothing. * * @return null as this appender does nothing. */ @Override public String getAndReset() { return null; } /** * Does nothing */ @Override public void appendIgnoringWhitespace(char ch) { } /** * Does nothing */ @Override public void append(char ch) { } /** * Returns null as this appender does nothing. * * @return null as this appender does nothing. */ @Override public char[] getCharsAndReset() { return null; } /** * Returns 0 as this appender does nothing. * * @return 0 as this appender does nothing. */ @Override public int whitespaceCount() { return 0; } /** * Does nothing */ @Override public void reset() { } /** * Does nothing */ @Override public void resetWhitespaceCount() { } /** * Does nothing */ @Override public char[] getChars() { return null; } /** * Does nothing */ @Override public void fill(char ch, int length) { } /** * Does nothing */ @Override public void appendIgnoringPadding(char ch, char padding) { } /** * Does nothing */ @Override public void appendIgnoringWhitespaceAndPadding(char ch, char padding) { } /** * Does nothing */ @Override public void prepend(char ch) { } /** * Does nothing */ @Override public void updateWhitespace() { } @Override public char appendUntil(char ch, CharInput input, char stop) { for (; ch != stop; ch = input.nextChar()) ; return ch; } @Override public final char appendUntil(char ch, CharInput input, char stop1, char stop2) { for (; ch != stop1 && ch != stop2; ch = input.nextChar()) ; return ch; } @Override public final char appendUntil(char ch, CharInput input, char stop1, char stop2, char stop3) { for (; ch != stop1 && ch != stop2 && ch != stop3; ch = input.nextChar()) ; return ch; } /** * Does nothing */ @Override public void append(char[] ch, int from, int length) { } /** * Does nothing */ @Override public void prepend(char ch1, char ch2) { } /** * Does nothing */ @Override public void prepend(char[] chars) { } /** * Does nothing */ @Override public void append(char[] ch) { } /** * Does nothing */ @Override public void append(String string) { } /** * Does nothing */ @Override public void append(String string, int from, int to) { } /** * Does nothing */ @Override public char charAt(int i) { return 0; } /** * Does nothing */ @Override public CharSequence subSequence(int i, int i1) { return null; } /** * Does nothing */ @Override public void append(int ch) { } /** * Does nothing */ @Override public void append(int[] ch) { } /** * Does nothing */ @Override public void append(Object obj) { } /** * Does nothing */ @Override public void ignore(int count) { } /** * Does nothing */ @Override public int indexOf(char ch, int from) { return -1; } /** * Does nothing */ @Override public String substring(int from, int length) { return null; } /** * Does nothing */ @Override public void remove(int from, int length) { } /** * Does nothing */ @Override public void delete(int count) { } /** * Does nothing */ @Override public int indexOfAny(char[] chars, int from) { return -1; } /** * Does nothing */ @Override public int indexOf(char[] charSequence, int from) { return -1; } /** * Does nothing */ @Override public int indexOf(CharSequence charSequence, int from) { return -1; } /** * Returns {@code true} as it's always empty. */ @Override public boolean isEmpty() { return true; } @Override public int lastIndexOf(char ch) { return -1; } } WriterCharAppender.java000066400000000000000000000163601475274123300351570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import com.univocity.parsers.common.*; import java.io.*; /** * Extension of the {@link DefaultCharAppender} class to include facilities for writing to an output. Used by writers extending {@link AbstractWriter}. * *

This class introduces the handling of the normalized newline character defined in {@link Format#getNormalizedNewline()} and converts it to the newline sequence in {@link Format#getLineSeparator()} *

It also introduces methods to write to an instance of {@link java.io.Writer} directly to avoid unnecessary String instantiations. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.Format * @see com.univocity.parsers.common.AbstractWriter */ public class WriterCharAppender extends ExpandingCharAppender { private final char lineSeparator1; private final char lineSeparator2; private final char newLine; private boolean denormalizeLineEndings = true; /** * Creates a WriterCharAppender with: *

    *
  • a maximum limit of characters to append
  • *
  • the default value to return when no characters have been accumulated.
  • *
  • the basic {@link Format} specification for handling newlines
  • *
* * The padding character is defaulted to a whitespace character ' '. * * @param maxLength maximum limit of characters to append * @param emptyValue default value to return when no characters have been accumulated * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param format output format specification used for newline handling */ public WriterCharAppender(int maxLength, String emptyValue, int whitespaceRangeStart, Format format) { super(maxLength == -1 ? 8192 : maxLength, emptyValue, whitespaceRangeStart); char[] lineSeparator = format.getLineSeparator(); this.lineSeparator1 = lineSeparator[0]; this.lineSeparator2 = lineSeparator.length > 1 ? lineSeparator[1] : '\0'; newLine = format.getNormalizedNewline(); } /** * Appends the given character and marks it as ignored if it is a whitespace ({@code ch <= ' '}) * *

If the given character is equal to {@link Format#getNormalizedNewline()}, then the character sequence returned by {@link Format#getLineSeparator()} is going to be appended. * * @param ch character to append */ @Override public final void appendIgnoringWhitespace(char ch) { if (ch == newLine && denormalizeLineEndings) { super.appendIgnoringWhitespace(lineSeparator1); if (lineSeparator2 != '\0') { super.appendIgnoringWhitespace(lineSeparator2); } } else { super.appendIgnoringWhitespace(ch); } } /** * Appends the given character and marks it as ignored if it is a padding character * *

If the given character is equal to {@link Format#getNormalizedNewline()}, then the character sequence returned by {@link Format#getLineSeparator()} is going to be appended. * * @param ch character to append * @param padding the padding character */ @Override public final void appendIgnoringPadding(char ch, char padding) { if (ch == newLine && denormalizeLineEndings) { super.appendIgnoringPadding(lineSeparator1, padding); if (lineSeparator2 != '\0') { super.appendIgnoringPadding(lineSeparator2, padding); } } else { super.appendIgnoringPadding(ch, padding); } } /** * Appends the given character and marks it as ignored if it is a whitespace ({@code ch <= ' '}) or a padding character * *

If the given character is equal to {@link Format#getNormalizedNewline()}, then the character sequence returned by {@link Format#getLineSeparator()} is going to be appended. * * @param ch character to append * @param padding the padding character */ @Override public final void appendIgnoringWhitespaceAndPadding(char ch, char padding) { if (ch == newLine && denormalizeLineEndings) { super.appendIgnoringWhitespaceAndPadding(lineSeparator1, padding); if (lineSeparator2 != '\0') { super.appendIgnoringWhitespaceAndPadding(lineSeparator2, padding); } } else { super.appendIgnoringWhitespaceAndPadding(ch, padding); } } /** * Appends the given character. * *

If the given character is equal to {@link Format#getNormalizedNewline()}, then the character sequence returned by {@link Format#getLineSeparator()} is going to be appended. * * @param ch the character to append */ @Override public final void append(char ch) { if (ch == newLine && denormalizeLineEndings) { appendNewLine(); } else { super.append(ch); } } /** * Writes the accumulated value to the {@link java.io.Writer}, discarding any trailing whitespace characters identified when using * {@link WriterCharAppender#appendIgnoringWhitespace(char)}, {@link WriterCharAppender#appendIgnoringPadding(char, char)} or {@link WriterCharAppender#appendIgnoringWhitespaceAndPadding(char, char)} *

The internal accumulated value is discarded after invoking this method (as in {@link DefaultCharAppender#reset()}) *

If the accumulated value is empty (i.e. no characters were appended, or all appended characters where ignored as whitespace or padding), then the written value will be the {@link DefaultCharAppender#emptyValue} attribute defined in the constructor of this class. * * @param writer the output writer * * @throws IOException if an error occurs while writing to the output. */ public final void writeCharsAndReset(Writer writer) throws IOException { if (index - whitespaceCount > 0) { writer.write(chars, 0, index - whitespaceCount); } else if (emptyChars != null) { writer.write(emptyChars, 0, emptyChars.length); } index = 0; whitespaceCount = 0; } /** * Appends the newline character sequence specified in {@link Format#getLineSeparator()} */ public final void appendNewLine() { if (index + 2 >= chars.length) { expand(); } chars[index++] = lineSeparator1; if (lineSeparator2 != '\0') { chars[index++] = lineSeparator2; } } /** * Configures the appender to allow line ending sequences to be appended as-is, without replacing them by the * normalized line separator character. * * @param enableDenormalizedLineEndings flag indicating whether denormalized line endings are allowed. The writer * won't convert line separators automatically. */ public final void enableDenormalizedLineEndings(boolean enableDenormalizedLineEndings) { this.denormalizeLineEndings = enableDenormalizedLineEndings; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/concurrent/000077500000000000000000000000001475274123300330165ustar00rootroot00000000000000CharBucket.java000077500000000000000000000050301475274123300356160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/concurrent/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input.concurrent; import java.io.*; import java.util.*; /** * A buffer of characters. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ class CharBucket { /** * The bucket data */ final char[] data; /** * The number of characters this bucket contain. It is modified every time {@link CharBucket#fill(Reader)} is called. */ int length = -1; /** * Creates a bucket capable of holding a fixed number of characters * @param bucketSize the maximum capacity of the bucket */ public CharBucket(int bucketSize) { if (bucketSize > 0) { data = new char[bucketSize]; } else { data = new char[0]; } } /** * Creates a bucket capable of holding a fixed number of characters * @param bucketSize the maximum capacity of the bucket * @param fillWith a character used to fill all positions of the bucket. */ public CharBucket(int bucketSize, char fillWith) { this(bucketSize); if (bucketSize > 0) { Arrays.fill(data, fillWith); } } /** * Fills the bucket with the characters take from a {@link java.io.Reader} *

The {@link CharBucket#length} attribute will be updated with the number of characters extracted * @param reader the source of characters used to fill the bucket * @return the number of characters extracted from the reader * @throws IOException if any error occurs while extracting characters from the reader */ public int fill(Reader reader) throws IOException { length = reader.read(data, 0, data.length); return length; } /** * Returns true if the bucket is empty (i.e. length <= 0), false otherwise. * @return true if the bucket is empty (i.e. length <= 0), false otherwise. */ public boolean isEmpty() { return length <= 0; } } ConcurrentCharInputReader.java000077500000000000000000000130451475274123300406730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/concurrent/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input.concurrent; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.*; import java.io.*; /** * A concurrent CharInputReader that loads batches of characters in a separate thread and assigns them to buffer in {@link AbstractCharInputReader} when requested. * *

This class loads "buckets" of characters in the background and provides them sequentially to the {@link ConcurrentCharInputReader#buffer} * attribute in {@link AbstractCharInputReader}. *

The bucket loading process will block and wait while all buckets are full. *

Similarly, the reader will block while all buckets are empty. * * This CharInputReader implementation provides a better throughput than {@link DefaultCharInputReader} when reading large inputs ({@code > 100 mb}). * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see CharInputReader * @see ConcurrentCharLoader * @see CharBucket */ public class ConcurrentCharInputReader extends AbstractCharInputReader { private ConcurrentCharLoader bucketLoader; private final int bucketSize; private final int bucketQuantity; private boolean unwrapping = false; /** * Creates a new instance with the mandatory characters for handling newlines transparently. Line separators will be detected automatically. * * @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) * that is used to replace any lineSeparator sequence found in the input. * @param bucketSize the size of an each individual "bucket" used to store characters read from the input. * @param bucketQuantity the number of "buckets" to load in memory. Note the reader will stop if all buckets are full. * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param closeOnStop indicates whether to automatically close the input when {@link #stop()} is called */ public ConcurrentCharInputReader(char normalizedLineSeparator, int bucketSize, int bucketQuantity, int whitespaceRangeStart, boolean closeOnStop) { super(normalizedLineSeparator, whitespaceRangeStart, closeOnStop); this.bucketSize = bucketSize; this.bucketQuantity = bucketQuantity; } /** * Creates a new instance with the mandatory characters for handling newlines transparently. * * @param lineSeparator the sequence of characters that represent a newline, as defined in {@link Format#getLineSeparator()} * @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) * that is used to replace any lineSeparator sequence found in the input. * @param bucketSize the size of an each individual "bucket" used to store characters read from the input. * @param bucketQuantity the number of "buckets" to load in memory. Note the reader will stop if all buckets are full. * @param whitespaceRangeStart starting range of characters considered to be whitespace. * @param closeOnStop indicates whether to automatically close the input when {@link #stop()} is called */ public ConcurrentCharInputReader(char[] lineSeparator, char normalizedLineSeparator, int bucketSize, int bucketQuantity, int whitespaceRangeStart, boolean closeOnStop) { super(lineSeparator, normalizedLineSeparator, whitespaceRangeStart, closeOnStop); this.bucketSize = bucketSize; this.bucketQuantity = bucketQuantity; } /** * Stops the CharInputReader from reading characters from the {@link java.io.Reader} provided in {@link ConcurrentCharInputReader#start(Reader)} and closes it. * Also stops the input reading thread. */ @Override public void stop() { if (!unwrapping && bucketLoader != null) { bucketLoader.stopReading(); bucketLoader.reportError(); } } /** * Starts an input reading thread to load characters from the given reader into "buckets" of characters */ @Override protected void setReader(Reader reader) { if(!unwrapping) { stop(); bucketLoader = new ConcurrentCharLoader(reader, bucketSize, bucketQuantity, closeOnStop); bucketLoader.reportError(); } else { bucketLoader.reader = reader; } unwrapping = false; } /** * Assigns the next "bucket" of characters to the {@link ConcurrentCharInputReader#buffer} attribute, and updates the {@link ConcurrentCharInputReader#length} to the number of characters read. */ @Override protected void reloadBuffer() { try { CharBucket currentBucket = bucketLoader.nextBucket(); bucketLoader.reportError(); super.buffer = currentBucket.data; super.length = currentBucket.length; } catch (BomInput.BytesProcessedNotification e) { unwrapping = true; unwrapInputStream(e); } } } ConcurrentCharLoader.java000077500000000000000000000130131475274123300376520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/concurrent/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input.concurrent; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.*; import java.io.*; import java.util.concurrent.*; /** * A concurrent character loader for loading a pool of {@link CharBucket} instances using a {@link java.io.Reader} in a separate thread * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see ConcurrentCharInputReader * @see CharBucket * @see Entry */ class ConcurrentCharLoader implements Runnable { private final ArrayBlockingQueue buckets; private final CharBucket end; private final FixedInstancePool instances; private Entry currentBucket; private boolean finished = false; private boolean active; Reader reader; private Thread activeExecution; private Exception error; private final boolean closeOnStop; /** * Creates a {@link FixedInstancePool} with a given amount of {@link CharBucket} instances and starts a thread to fill each one. * * @param reader The source of characters to extract and fill {@link CharBucket} instances * @param bucketSize The size of each individual {@link CharBucket} * @param bucketQuantity The number of {@link CharBucket} instances used to extract characters from the given reader. * @param closeOnStop Indicates whether to automatically close the input when {@link #stopReading()} is called */ public ConcurrentCharLoader(Reader reader, final int bucketSize, int bucketQuantity, boolean closeOnStop) { this.closeOnStop = closeOnStop; this.end = new CharBucket(-1); this.buckets = new ArrayBlockingQueue(bucketQuantity); this.reader = reader; this.instances = new FixedInstancePool(bucketQuantity) { @Override protected CharBucket newInstance() { return new CharBucket(bucketSize); } }; finished = false; active = true; } private int readBucket() throws IOException, InterruptedException { Entry bucket = instances.allocate(); int length = bucket.get().fill(reader); if (length != -1) { buckets.put(bucket); } else { instances.release(bucket); } return length; } /** * The {@link CharBucket} loading process that executes in parallel until the input is completely read. * Once the end of the input is reached, the {@link java.io.Reader} instance provided in the constructor is closed. */ @Override public void run() { try { try { while (active && readBucket() != -1) ; } finally { buckets.put(end); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { finished = true; setError(e); } finally { stopReading(); } } private void setError(Exception e){ if(active) { error = e; } //else if not active then input was closed externally - we can ignore the exception. } /** * Returns the next available bucket. Blocks until a bucket is made available or the reading process stops. * * @return the next available bucket. */ @SuppressWarnings("unchecked") public synchronized CharBucket nextBucket() { if (activeExecution == null && !finished) { int length = -1; try { length = readBucket(); if (length >= 0 && length <= 4) { length = readBucket(); } } catch (BomInput.BytesProcessedNotification e) { throw e; } catch (Exception e) { setError(e); } if(length != -1) { activeExecution = new Thread(this, "unVocity-parsers input reading thread"); activeExecution.start(); } else { finished = true; try { buckets.put(end); } catch(InterruptedException e){ Thread.currentThread().interrupt(); } finally { stopReading(); } } } try { if (finished) { if (buckets.size() <= 1) { return end; } } if (currentBucket != null) { instances.release(currentBucket); } Object element = buckets.take(); if (element == end) { finished = true; return end; } else { currentBucket = (Entry) element; } return currentBucket.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); finished = true; return end; } } /** * Stops the {@link CharBucket} loading process and closes the reader provided in the constructor of this class */ public void stopReading() { active = false; try { if(closeOnStop) { reader.close(); } } catch (IOException e) { throw new IllegalStateException("Error closing input", e); } finally { try { if (activeExecution != null) { activeExecution.interrupt(); } } catch (Throwable ex) { throw new IllegalStateException("Error stopping input reader thread", ex); } } } void reportError() { if (error != null) { ArgumentUtils.throwUnchecked(error); } } } Entry.java000077500000000000000000000030761475274123300347140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/concurrent/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input.concurrent; /** * An entry used by the {@link FixedInstancePool} * @param the type of this entry. * * @see FixedInstancePool * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ class Entry { final T entry; final int index; /** * Creates a new entry with an object and its position in the {@link FixedInstancePool} * @param entry the value in this entry * @param index the position of this entry in the {@link FixedInstancePool} */ Entry(T entry, int index) { this.entry = entry; this.index = index; } /** * Returns the object stored in this {@link FixedInstancePool} entry. * @return the object stored in this {@link FixedInstancePool} entry. */ public T get() { return this.entry; } } FixedInstancePool.java000077500000000000000000000075321475274123300371720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/input/concurrent/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input.concurrent; import java.util.*; /** * A very simple object instance pool with a fixed size. * *

This is essentially an immutable circular queue. Elements are not added nor removed. Pointers to the head and tail of the queue identify what is the next available entry. *

Use {@link FixedInstancePool#allocate()} to get an available {@link Entry} from the pool. If all objects are allocated then the thread will block until an element is released. *

{@link FixedInstancePool#release(Entry)} releases an allocated {@link Entry} for reuse. * * @param the class of objects stored in the instance pool * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see Entry */ abstract class FixedInstancePool { final Entry[] instancePool; private final int[] instanceIndexes; private int head = 0; private int tail = 0; int count = 0; private int lastInstanceIndex = 0; /** * Creates a new instance pool with the given size. Upon instantiation, the {@link FixedInstancePool#newInstance()} method will be called to fill in the instance pool, and the pool * can then have its entries allocated for use (and reuse). * * @param size the size of the fixed instance pool. */ @SuppressWarnings("unchecked") FixedInstancePool(int size) { instancePool = new Entry[size]; instanceIndexes = new int[size]; Arrays.fill(instanceIndexes, -1); instancePool[0] = new Entry(newInstance(), 0); instanceIndexes[0] = 0; } /** * Creates a new instance of the given type of objects stored as entries of this instance pool * This method is called in the constructor of this class for initialization of the instance array and must always return a new instance. * * @return returns a new instance to use in the pool */ protected abstract T newInstance(); /** * Retrieves the next available entry in this instance pool. Blocks until an entry becomes available (through {@link FixedInstancePool#release(Entry)}). * * @return the next available entry in this instance pool */ public synchronized Entry allocate() { while (count == instancePool.length) { try { wait(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new Entry(newInstance(), -1); } } int index = instanceIndexes[head]; if (index == -1) { index = ++lastInstanceIndex; instanceIndexes[index] = index; instancePool[index] = new Entry(newInstance(), index); } Entry out = instancePool[index]; // instanceIndexes[head] = -1; //enable to print the queue's contents for debugging purposes head++; if (head == instancePool.length) { head = 0; } count++; return out; } /** * Releases the given entry and makes it available for allocation (by {@link FixedInstancePool#allocate()}) * * @param e the entry to be released and made available for reuse. */ public synchronized void release(Entry e) { if (e.index != -1) { instanceIndexes[tail++] = e.index; if (tail == instancePool.length) { tail = 0; } count--; } notify(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/iterators/000077500000000000000000000000001475274123300315115ustar00rootroot00000000000000ParserIterator.java000066400000000000000000000062011475274123300352420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/iterators/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.iterators; import com.univocity.parsers.common.*; import com.univocity.parsers.common.record.*; import java.util.*; /** * An {@link Iterator} over the parser enabling easy iteration against rows and records * Multiple iterations are possible if Files are being fed into the parser, * but other forms of input (such as {@code InputStream}s and {@code Reader}s) can not be iterated over more than once. * * @author Univocity Software Pty Ltd - dev@univocity.com */ abstract class ParserIterator implements IterableResult { protected final AbstractParser parser; /** * Creates a {@code ParserIterator} using the provided {@code parser} * * @param parser the {@code parser} to iterate over */ protected ParserIterator(AbstractParser parser) { this.parser = parser; } @Override public final ParsingContext getContext() { if (parser.getContext() == null) { beginParsing(); } return parser.getContext(); } /** * This method is called whenever the {@code iterator} is starting to iterate over the * results. * an example implementation of this is: *


*
	 *     {@code
	 *     @Override
	 *     public void beginParsing(){
	 *         parser.beginParsing(input);
	 *     }}
	 * 
*
* This is to allow for different input types such as {@code Reader, File, or InputStream} without large code * reuse. */ protected abstract void beginParsing(); @Override public final ResultIterator iterator() { return new ResultIterator() { T next; boolean started; @Override public ParsingContext getContext() { return parser.getContext(); } @Override public boolean hasNext() { if (started) { return next != null; } else { started = true; if (parser.getContext() == null) { beginParsing(); } next = nextResult(); return next != null; } } @Override public T next() { if (!started) { hasNext(); } T out = next; next = nextResult(); return out; } @Override public void remove() { throw new UnsupportedOperationException("Can't remove row"); } }; } /** * Returns the next record (either a String[] or a {@link Record}) * * @return the next record if available. */ protected abstract T nextResult(); } RecordIterator.java000066400000000000000000000025601475274123300352300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/iterators/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.iterators; import com.univocity.parsers.common.*; import com.univocity.parsers.common.record.*; import java.io.*; /** * An iterator of {@link Record}s. Created when {@link AbstractParser#iterateRecords(File)} * (and its overloaded counterparts) is called * * @author Univocity Software Pty Ltd - dev@univocity.com */ public abstract class RecordIterator extends ParserIterator { public RecordIterator(AbstractParser parser) { super(parser); } @Override protected final Record nextResult() { return parser.parseNextRecord(); } } RowIterator.java000066400000000000000000000024641475274123300345640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/iterators/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.iterators; import com.univocity.parsers.common.*; import java.io.*; /** * An iterator of {@code String[]}. Created when {@link AbstractParser#iterate(File)} * (and its overloaded counterparts) is called * * @author Univocity Software Pty Ltd - dev@univocity.com */ public abstract class RowIterator extends ParserIterator { public RowIterator(AbstractParser parser) { super(parser); } @Override protected final String[] nextResult() { return parser.parseNext(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/000077500000000000000000000000001475274123300315145ustar00rootroot00000000000000AbstractRowProcessor.java000077500000000000000000000023131475274123300364350ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A {@link RowProcessor} implementation that just implements all methods defined by the interface. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class AbstractRowProcessor extends AbstractProcessor implements RowProcessor { } BatchedColumnProcessor.java000066400000000000000000000046121475274123300367130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A {@link RowProcessor} implementation that stores values of columns in batches. Use this implementation in favor of {@link ColumnProcessor} * when processing large inputs to avoid running out of memory. * * Values parsed in each row will be split into columns of Strings. Each column has its own list of values. * *

During the execution of the process, the {@link #batchProcessed(int)} method will be invoked after a given number of rows has been processed.

*

The user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

*

After {@link #batchProcessed(int)} is invoked, all values will be discarded and the next batch of column values will be accumulated. * This process will repeat until there's no more rows in the input. * * @author Univocity Software Pty Ltd - parsers@univocity.com * * @see AbstractParser * @see RowProcessor * @see AbstractBatchedColumnProcessor */ public abstract class BatchedColumnProcessor extends AbstractBatchedColumnProcessor implements RowProcessor { /** * Constructs a batched column processor configured to invoke the {@link #batchesProcessed} method after a given number of rows has been processed. * @param rowsPerBatch the number of rows to process in each batch. */ public BatchedColumnProcessor(int rowsPerBatch) { super(rowsPerBatch); } } BatchedObjectColumnProcessor.java000066400000000000000000000051701475274123300400420ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.conversions.*; /** * * A {@link RowProcessor} implementation for converting batches of rows extracted from any implementation of {@link AbstractParser} into columns of objects. *

This uses the value conversions provided by {@link Conversion} instances.

* *

For each row processed, a sequence of conversions will be executed to generate the appropriate object. Each resulting object will then be stored in * a list that contains the values of the corresponding column.

* *

During the execution of the process, the {@link #batchProcessed(int)} method will be invoked after a given number of rows has been processed.

*

The user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

*

After {@link #batchProcessed(int)} is invoked, all values will be discarded and the next batch of column values will be accumulated. * This process will repeat until there's no more rows in the input. * * @see AbstractParser * @see RowProcessor * @see AbstractBatchedColumnProcessor * @see Conversion * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class BatchedObjectColumnProcessor extends AbstractBatchedObjectColumnProcessor implements RowProcessor { /** * Constructs a batched column processor configured to invoke the {@link #batchesProcessed} method after a given number of rows has been processed. * @param rowsPerBatch the number of rows to process in each batch. */ public BatchedObjectColumnProcessor(int rowsPerBatch) { super(rowsPerBatch); } } BeanListProcessor.java000066400000000000000000000052741475274123300357110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * A convenience {@link BeanProcessor} implementation for storing all java objects generated form the parsed input into a list. * A typical use case of this class will be: * *


{@code
 *
 * parserSettings.setRowProcessor(new BeanListProcessor(MyObject.class));
 * parser.parse(reader); // will invoke the {@link BeanListProcessor#beanProcessed(Object, Context)} method for each generated object.
 *
 * List<T> beans = rowProcessor.getBeans();
 * }

* * @param the annotated class type. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see BeanProcessor * @see RowProcessor * @see AbstractParser * @see AbstractBeanListProcessor */ public class BeanListProcessor extends AbstractBeanListProcessor implements RowProcessor { /** * Creates a processor that stores java beans of a given type into a list * * @param beanType the class with its attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public BeanListProcessor(Class beanType) { super(beanType); } /** * Creates a processor that stores java beans of a given type into a list * * @param beanType the class with its attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * returned by {@link #getBeans()} */ public BeanListProcessor(Class beanType, int expectedBeanCount) { super(beanType, expectedBeanCount); } } BeanProcessor.java000066400000000000000000000041341475274123300350470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * * A {@link RowProcessor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects. *

The class type of the object must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For each row processed, a java bean instance of a given class will be created with its fields populated. *

This instance will then be sent to the {@link BeanProcessor#beanProcessed(Object, Context)} method, where the user can access it. * * @see AbstractParser * @see RowProcessor * @see AbstractBeanProcessor * * @param the annotated class type. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class BeanProcessor extends AbstractBeanProcessor implements RowProcessor{ /** * Creates a processor for java beans of a given type. * @param beanType the class with its attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public BeanProcessor(Class beanType) { super(beanType, MethodFilter.ONLY_SETTERS); } } BeanWriterProcessor.java000066400000000000000000000077471475274123300362610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.conversions.*; /** * * A {@link RowWriterProcessor} implementation for converting annotated java objects into object arrays suitable for writing in any implementation of {@link AbstractWriter}. *

The class type of the object must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For any given java bean instance, this processor will read and convert annotated fields into an object array. * * * @param the annotated class type. * * @see AbstractWriter * @see RowWriterProcessor * @see BeanConversionProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class BeanWriterProcessor extends BeanConversionProcessor implements RowWriterProcessor { private NormalizedString[] normalizedHeaders; private String[] previousHeaders; /** * Initializes the BeanWriterProcessor with the annotated bean class * @param beanType the class annotated with one or more of the annotations provided in {@link com.univocity.parsers.annotations}. */ public BeanWriterProcessor(Class beanType) { super(beanType, MethodFilter.ONLY_GETTERS); } /** * Converts the java bean instance into a sequence of values for writing. * * @param input an instance of the type defined in this class constructor. * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @return a row of objects containing the values extracted from the java bean */ public Object[] write(T input, String[] headers, int[] indexesToWrite) { if (previousHeaders != headers) { previousHeaders = headers; normalizedHeaders = NormalizedString.toArray(headers); } return write(input, normalizedHeaders, indexesToWrite); } /** * Converts the java bean instance into a sequence of values for writing. * * @param input an instance of the type defined in this class constructor. * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @return a row of objects containing the values extracted from the java bean */ @Override public Object[] write(T input, NormalizedString[] headers, int[] indexesToWrite) { if (!initialized) { super.initialize(headers); } return reverseConversions(input, headers, indexesToWrite); } @Override protected FieldConversionMapping cloneConversions(){ return null; } } ColumnProcessor.java000066400000000000000000000041451475274123300354410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A simple {@link RowProcessor} implementation that stores values of columns. * Values parsed in each row will be split into columns of Strings. Each column has its own list of values. * *

At the end of the process, the user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

* * *

Note: Storing the values of all columns may be memory intensive. For large inputs, use a {@link BatchedColumnProcessor} instead

* * @author Univocity Software Pty Ltd - parsers@univocity.com * * @see AbstractParser * @see RowProcessor */ public class ColumnProcessor extends AbstractColumnProcessor implements RowProcessor { /** * Constructs a column processor, pre-allocating room for 1000 rows. */ public ColumnProcessor() { super(1000); } /** * Constructs a column processor pre-allocating room for the expected number of rows to be processed * @param expectedRowCount the expected number of rows to be processed */ public ColumnProcessor(int expectedRowCount) { super(expectedRowCount); } } CompositeRowProcessor.java000077500000000000000000000026471475274123300366460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A utility {@link RowProcessor} implementation that facilitates using multiple implementations of {@link RowProcessor} at the * same time. */ public class CompositeRowProcessor extends CompositeProcessor implements RowProcessor { /** * Creates a new {@code CompositeProcessor} with the list of {@link Processor} implementations to be used. * * @param processors the sequence of {@link Processor} implementations to be used. */ public CompositeRowProcessor(Processor... processors) { super(processors); } }ConcurrentRowProcessor.java000066400000000000000000000051041475274123300370120ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A {@link RowProcessor} implementation to perform row processing tasks in parallel. The {@code ConcurrentRowProcessor} wraps another {@link RowProcessor}, and collects rows read from the input. * The actual row processing is performed in by wrapped {@link RowProcessor} in a separate thread. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see RowProcessor */ public class ConcurrentRowProcessor extends AbstractConcurrentProcessor implements RowProcessor { /** * Creates a non-blocking {@code ConcurrentRowProcessor}, to perform processing of rows parsed from the input in a separate thread. * * @param rowProcessor a regular {@link RowProcessor} implementation which will be executed in a separate thread. */ public ConcurrentRowProcessor(RowProcessor rowProcessor) { super(rowProcessor); } /** * Creates a blocking {@code ConcurrentRowProcessor}, to perform processing of rows parsed from the input in a separate thread. * * @param rowProcessor a regular {@link RowProcessor} implementation which will be executed in a separate thread. * @param limit the limit of rows to be kept in memory before the input parsing process is blocked. */ public ConcurrentRowProcessor(RowProcessor rowProcessor, int limit) { super(rowProcessor, limit); } @Override protected ParsingContext copyContext(ParsingContext context) { return new ParsingContextSnapshot(context); } @Override protected ParsingContext wrapContext(ParsingContext context) { return new ParsingContextWrapper(context) { @Override public long currentRecord() { return getRowCount(); } }; } } CustomMatcher.java000066400000000000000000000021341475274123300350560ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor; /** * Interface used by {@link InputValueSwitch} to allow users to to provide custom matching rules against input values. */ public interface CustomMatcher { /** * Matches a parsed value against a user provided rule (implementation provided by the user) * @param value the value to be matched * @return {@code true} if the given value matches the user provided rule, otherwise {@code false} */ boolean matches(String value); } InputValueSwitch.java000066400000000000000000000051341475274123300355610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A concrete implementation of {@link RowProcessorSwitch} that allows switching among different implementations of * {@link RowProcessor} based on values found on the rows parsed from the input. */ public class InputValueSwitch extends AbstractInputValueSwitch implements RowProcessor{ /** * Creates a switch that will analyze the first column of rows found in the input to determine which * {@link RowProcessor} to use for each parsed row */ public InputValueSwitch() { this(0); } /** * Creates a switch that will analyze a column of rows parsed from the input to determine which * {@link RowProcessor} to use. * * @param columnIndex the column index whose value will be used to determine which {@link RowProcessor} to use for each parsed row. */ public InputValueSwitch(int columnIndex) { super(columnIndex); } /** * Creates a switch that will analyze a column in rows parsed from the input to determine which * {@link RowProcessor} to use. * * @param columnName name of the column whose values will be used to determine which {@link RowProcessor} to use for each parsed row. */ public InputValueSwitch(String columnName) { super(columnName); } @Override protected final ParsingContext wrapContext(ParsingContext context) { return new ParsingContextWrapper(context) { private final String[] fieldNames = getHeaders(); private final int[] indexes = getIndexes(); @Override public String[] headers() { return fieldNames == null || fieldNames.length == 0 ? context.headers() : fieldNames; } @Override public int[] extractedFieldIndexes() { return indexes == null || indexes.length == 0 ? context.extractedFieldIndexes() : indexes; } }; } } MasterDetailListProcessor.java000066400000000000000000000042411475274123300374130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * * A convenience {@link MasterDetailProcessor} implementation for storing all {@link MasterDetailRecord} generated form the parsed input into a list. * A typical use case of this class will be: * *


{@code
 *
 * ObjectRowListProcessor detailProcessor = new ObjectRowListProcessor();
 * MasterDetailListProcessor masterRowProcessor = new MasterDetailListProcessor(detailProcessor) {
 *      protected boolean isMasterRecord(String[] row, ParsingContext context) {
 *          return "Total".equals(row[0]);
 *      }
 * };
 *
 * parserSettings.setRowProcessor(masterRowProcessor);
 *
 * List<MasterDetailRecord> rows = masterRowProcessor.getRecords();
 * }

* * @see MasterDetailProcessor * @see RowProcessor * @see AbstractParser * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class MasterDetailListProcessor extends AbstractMasterDetailListProcessor implements RowProcessor { public MasterDetailListProcessor(RowPlacement rowPlacement, AbstractObjectListProcessor detailProcessor) { super(rowPlacement, detailProcessor); } public MasterDetailListProcessor(AbstractObjectListProcessor detailProcessor) { super(detailProcessor); } } MasterDetailProcessor.java000066400000000000000000000057121475274123300365630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.conversions.*; /** * * A {@link RowProcessor} implementation for associating rows extracted from any implementation of {@link AbstractParser} into {@link MasterDetailRecord} instances. * *

For each row processed, a call to {@link MasterDetailProcessor#isMasterRecord(String[], Context)} will be made to identify whether or not it is a master row. *

The detail rows are automatically associated with the master record in an instance of {@link MasterDetailRecord}. *

When the master record is fully processed (i.e. {@link MasterDetailRecord} contains a master row and all associated detail rows), * it is sent to the user for processing in {@link MasterDetailProcessor#masterDetailRecordProcessed(MasterDetailRecord, Context)}. * *

Note this class extends {@link ObjectRowProcessor} and value conversions provided by {@link Conversion} instances are fully supported. * * @see MasterDetailRecord * @see RowPlacement * @see AbstractParser * @see ObjectRowListProcessor * @see RowProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class MasterDetailProcessor extends AbstractMasterDetailProcessor { /** * Creates a MasterDetailProcessor * * @param rowPlacement indication whether the master records are placed in relation its detail records in the input. * *


	 *
	 * Master record (Totals)       Master record (Totals)
	 *  above detail records         under detail records
	 *
	 *    Totals | 100                 Item   | 60
	 *    Item   | 60                  Item   | 40
	 *    Item   | 40                  Totals | 100
	 * 

* @param detailProcessor the {@link ObjectRowListProcessor} that processes detail rows. */ public MasterDetailProcessor(RowPlacement rowPlacement, ObjectRowListProcessor detailProcessor) { super(rowPlacement, detailProcessor); } public MasterDetailProcessor(ObjectRowListProcessor detailProcessor) { super(RowPlacement.TOP, detailProcessor); } } MasterDetailRecord.java000066400000000000000000000050611475274123300360170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import java.util.*; /** * An utility class to store data of a master row and its detail records. * * Instances of this class are typically generated by an instance of {@link AbstractParser} during the parsing of an input using a {@link MasterDetailProcessor}. * * @see MasterDetailProcessor * @see RowProcessor * @see AbstractParser * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class MasterDetailRecord implements Cloneable { private Object[] masterRow = null; private List detailRows = Collections.emptyList(); /** * Returns the master row as identified by a {@link MasterDetailProcessor} * @return the master row */ public Object[] getMasterRow() { return masterRow; } /** * Sets the master row data. * @param masterRow the data of a master row */ public void setMasterRow(Object[] masterRow) { this.masterRow = masterRow; } /** * Returns the detail rows which are associated with the master row * @return the detail rows which are associated with the master row */ public List getDetailRows() { return detailRows; } /** * Sets the detail rows associated with the master row * @param detailRows the list of rows associated with the master row */ public void setDetailRows(List detailRows) { this.detailRows = detailRows; } /** * Empties the detail rows and sets the master row to null. */ public void clear() { this.detailRows = Collections.emptyList(); this.masterRow = null; } @Override public MasterDetailRecord clone() { try { return (MasterDetailRecord) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.getMessage()); } } } MultiBeanListProcessor.java000066400000000000000000000053161475274123300367210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * A {@link RowProcessor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects, storing * them into lists. This processor stores beans in separate lists, one for each type of bean processed. * All lists of all types will have the same number of entries as the number of records in the input. * When an object of a particular type can't be generated from a row, {@code null} will be added to the list. This ensures all lists are the same size, * and each element of each list contains the exact information parsed from each row. * *

The class types passed to the constructor of this class must contain the annotations provided in {@link com.univocity.parsers.annotations}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see RowProcessor * @see BeanProcessor * @see MultiBeanProcessor */ public class MultiBeanListProcessor extends AbstractMultiBeanListProcessor implements RowProcessor { /** * Creates a processor for java beans of multiple types * * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} returned by {@link #getBeans()} * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public MultiBeanListProcessor(int expectedBeanCount, Class... beanTypes) { super(expectedBeanCount, beanTypes); } /** * Creates a processor for java beans of multiple types * * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public MultiBeanListProcessor(Class... beanTypes) { super(beanTypes); } } MultiBeanProcessor.java000066400000000000000000000037051475274123300360650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * * A {@link RowProcessor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects. * *

The class types passed to the constructor of this class must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For each row processed, one or more java bean instances of any given class will be created with their fields populated. *

Each individual instance will then be sent to the {@link MultiBeanProcessor#beanProcessed(Class, Object, Context)} method, where the user can access the * beans parsed for each row. * * @see AbstractParser * @see RowProcessor * @see BeanProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class MultiBeanProcessor extends AbstractMultiBeanProcessor implements RowProcessor{ /** * Creates a processor for java beans of multiple types * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public MultiBeanProcessor(Class ... beanTypes){ super(beanTypes); } } MultiBeanRowProcessor.java000066400000000000000000000040521475274123300365510ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * * A {@link RowProcessor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects. * *

The class types passed to the constructor of this class must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For each row processed, one or more java bean instances of any given class will be created with their fields populated. *

Once all beans are populated from an individual input record, they will be sent to through the {@link AbstractMultiBeanRowProcessor#rowProcessed(Map, Context)} method, * where the user can access all beans parsed for that row. * * @see AbstractParser * @see RowProcessor * @see BeanProcessor * @see MultiBeanProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class MultiBeanRowProcessor extends AbstractMultiBeanRowProcessor implements RowProcessor{ /** * Creates a processor for java beans of multiple types * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public MultiBeanRowProcessor(Class... beanTypes) { super(beanTypes); } }NoopRowProcessor.java000066400000000000000000000021541475274123300356050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; /** * A singleton instance of a {@link RowProcessor} that does nothing. */ public final class NoopRowProcessor extends AbstractRowProcessor { /** * The singleton instance of the no-op {@link RowProcessor} */ public static final RowProcessor instance = new NoopRowProcessor(); private NoopRowProcessor() { } } ObjectColumnProcessor.java000066400000000000000000000047521475274123300365740ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.conversions.*; /** * * A {@link RowProcessor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into columns of objects. *

This uses the value conversions provided by {@link Conversion} instances.

* *

For each row processed, a sequence of conversions will be executed to generate the appropriate object. Each resulting object will then be stored in * a list that contains the values of the corresponding column.

* *

At the end of the process, the user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

* *

Note: Storing the values of all columns may be memory intensive. For large inputs, use a {@link BatchedObjectColumnProcessor} instead

* * @see AbstractParser * @see RowProcessor * @see ColumnProcessor * @see Conversion * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ObjectColumnProcessor extends AbstractObjectColumnProcessor implements RowProcessor { /** * Constructs a column processor, pre-allocating room for 1000 rows. */ public ObjectColumnProcessor() { this(1000); } /** * Constructs a column processor pre-allocating room for the expected number of rows to be processed * @param expectedRowCount the expected number of rows to be processed */ public ObjectColumnProcessor(int expectedRowCount) { super(expectedRowCount); } } ObjectRowListProcessor.java000077500000000000000000000047061475274123300367440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * A convenience {@link RowProcessor} implementation for storing all rows parsed and converted to Object arrays into a list. * A typical use case of this class will be: * *
{@code
 *
 * ObjectRowListProcessor processor = new ObjectRowListProcessor();
 * processor.convertIndexes(Conversions.toBigDecimal()).set(4, 6);
 * parserSettings.setRowProcessor(new ObjectRowListProcessor());
 * parser.parse(reader); // will invoke the {@link AbstractObjectListProcessor#rowProcessed(Object[], Context)} method for each parsed record.
 *
 * String[] headers = rowProcessor.getHeaders();
 * List<Object[]> rows = rowProcessor.getRows();
 * BigDecimal value1 = (BigDecimal) row.get(4);
 * BigDecimal value2 = (BigDecimal) row.get(6);
 * }

* * @author Univocity Software Pty Ltd - parsers@univocity.com * @see RowProcessor * @see ObjectRowProcessor * @see AbstractParser */ public class ObjectRowListProcessor extends AbstractObjectListProcessor implements RowProcessor { /** * Creates a new processor of {@code Object[]} rows with varying types. */ public ObjectRowListProcessor() { } /** * Creates a new processor of {@code Object[]} rows with varying types. * * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} returned by {@link #getRows()} */ public ObjectRowListProcessor(int expectedRowCount) { super(expectedRowCount); } } ObjectRowProcessor.java000066400000000000000000000033501475274123300360770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.conversions.*; /** * * A {@link RowProcessor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into arrays of objects. *

This uses the value conversions provided by {@link Conversion} instances. * *

For each row processed, a sequence of conversions will be executed and stored in an object array, at its original position. *

The row with the result of these conversions will then be sent to the {@link ObjectRowProcessor#rowProcessed(Object[], Context)} method, where the user can access it. * * @see AbstractParser * @see RowProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class ObjectRowProcessor extends AbstractObjectProcessor implements RowProcessor { } ObjectRowWriterProcessor.java000066400000000000000000000107171475274123300373010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; /** * * A {@link RowWriterProcessor} implementation for executing conversion sequences in object arrays before for writing them using any implementation of {@link AbstractWriter}. * * @see AbstractWriter * @see RowWriterProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ObjectRowWriterProcessor extends DefaultConversionProcessor implements RowWriterProcessor { private NormalizedString[] normalizedHeaders; private String[] previousHeaders; /** * Executes the sequences of conversions defined using {@link DefaultConversionProcessor#convertFields(Conversion...)}, {@link DefaultConversionProcessor#convertIndexes(Conversion...)} and {@link DefaultConversionProcessor#convertAll(Conversion...)}, for every field in the given row. * *

Each field will be transformed using the {@link Conversion#execute(Object)} method. *

In general the conversions will process a String and convert it to some object value (such as booleans, dates, etc). * * @param input the object array that represents a record with its individual fields. * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @return an row of Object instances containing the values obtained after the execution of all conversions. *

Fields that do not have any conversion defined will just be copied to the object array into their original positions. */ public Object[] write(Object[] input, String[] headers, int[] indexesToWrite) { if (previousHeaders != headers) { previousHeaders = headers; normalizedHeaders = NormalizedString.toArray(headers); } return write(input, normalizedHeaders, indexesToWrite); } /** * Executes the sequences of conversions defined using {@link DefaultConversionProcessor#convertFields(Conversion...)}, {@link DefaultConversionProcessor#convertIndexes(Conversion...)} and {@link DefaultConversionProcessor#convertAll(Conversion...)}, for every field in the given row. * *

Each field will be transformed using the {@link Conversion#execute(Object)} method. *

In general the conversions will process a String and convert it to some object value (such as booleans, dates, etc). * * @param input the object array that represents a record with its individual fields. * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @return an row of Object instances containing the values obtained after the execution of all conversions. *

Fields that do not have any conversion defined will just be copied to the object array into their original positions. */ @Override public Object[] write(Object[] input, NormalizedString[] headers, int[] indexesToWrite) { if (input == null) { return null; } Object[] output = new Object[input.length]; System.arraycopy(input, 0, output, 0, input.length); if (reverseConversions(false, output, headers, indexesToWrite)) { return output; } return null; } } OutputValueSwitch.java000066400000000000000000000330411475274123300357600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; /** * A concrete implementation of {@link RowWriterProcessorSwitch} that allows switching among different implementations of * {@link RowWriterProcessor} based on values found on rows to be written to an output */ public class OutputValueSwitch extends RowWriterProcessorSwitch { private Switch defaultSwitch; private Switch[] switches = new Switch[0]; private Switch selectedSwitch; private Class[] types = new Class[0]; private final int columnIndex; private final String headerName; @SuppressWarnings("rawtypes") private Comparator comparator = new Comparator() { @Override public int compare(Object o1, Object o2) { return o1 == o2 ? 0 : o1 != null && o1.equals(o2) ? 0 : 1; } }; /** * Creates a switch that will analyze the first column of output rows to determine which * {@link RowWriterProcessor} to use for each output row */ public OutputValueSwitch() { this(0); } /** * Creates a switch that will analyze a column of output rows to determine which * {@link RowWriterProcessor} to use. * * @param columnIndex the column index whose value will be used to determine which {@link RowWriterProcessor} to use for each output row. */ public OutputValueSwitch(int columnIndex) { this.columnIndex = getValidatedIndex(columnIndex); this.headerName = null; } /** * Creates a switch that will analyze a column of output rows to determine which {@link RowWriterProcessor} to use. * When no column index is defined, the switch will use the first column of any input rows sent for writing. * * @param headerName the column name whose value will be used to determine which {@link RowWriterProcessor} to use for each output row. */ public OutputValueSwitch(String headerName) { this.headerName = getValidatedHeaderName(headerName); this.columnIndex = 0; } /** * Creates a switch that will analyze a column of output rows to determine which * {@link RowWriterProcessor} to use. * * @param headerName the column name whose value will be used to determine which {@link RowWriterProcessor} to use for each output row. * @param columnIndex the position of an input column to use to perform the switch when no headers are available. */ public OutputValueSwitch(String headerName, int columnIndex) { this.columnIndex = getValidatedIndex(columnIndex); this.headerName = getValidatedHeaderName(headerName); } private int getValidatedIndex(int columnIndex) { if (columnIndex < 0) { throw new IllegalArgumentException("Column index must be positive"); } return columnIndex; } private String getValidatedHeaderName(String headerName) { if (headerName == null || headerName.trim().length() == 0) { throw new IllegalArgumentException("Header name cannot be blank"); } return headerName; } /** * Configures the switch to use a custom {@link Comparator} to compare values in the column to analyze which is given in the constructor of this class. * * @param comparator the comparator to use for matching values in the output column with the values provided in {@link #addSwitchForValue(Object, RowWriterProcessor)} */ public void setComparator(Comparator comparator) { if (comparator == null) { throw new IllegalArgumentException("Comparator must not be null"); } this.comparator = comparator; } /** * Defines a default {@link RowWriterProcessor} implementation to use when no matching value is found in the output row. * * @param rowProcessor the default row writer processor implementation * @param headersToUse the (optional) sequence of headers to assign to the given row writer processor */ public void setDefaultSwitch(RowWriterProcessor rowProcessor, String... headersToUse) { defaultSwitch = new Switch(rowProcessor, headersToUse, null, null); } /** * Defines a default {@link RowWriterProcessor} implementation to use when no matching value is found in the output row. * * @param rowProcessor the default row writer processor implementation * @param indexesToUse the (optional) sequence of column indexes to assign to the given row writer processor */ public void setDefaultSwitch(RowWriterProcessor rowProcessor, int... indexesToUse) { defaultSwitch = new Switch(rowProcessor, null, indexesToUse, null); } @Override protected NormalizedString[] getHeaders() { return selectedSwitch != null ? selectedSwitch.headers : null; } @Override protected int[] getIndexes() { return selectedSwitch != null ? selectedSwitch.indexes : null; } private Switch getSwitch(Object value) { if (value instanceof Object[]) { Object[] row = (Object[]) value; if (row.length < columnIndex) { return defaultSwitch; } value = row[columnIndex]; } for (int i = 0; i < switches.length; i++) { Switch s = switches[i]; Class type = types[i]; if (type != null) { if (type.isAssignableFrom(value.getClass())) { return s; } } else if (comparator.compare(value, s.value) == 0) { return s; } } return defaultSwitch; } @SuppressWarnings("unchecked") @Override protected RowWriterProcessor switchRowProcessor(Object row) { selectedSwitch = getSwitch(row); return selectedSwitch != null ? selectedSwitch.processor : null; } /** * Associates a {@link RowWriterProcessor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param value the value to match against the column of incoming output rows and trigger the usage of the given row writer processor implementation. * @param rowProcessor the row writer processor implementation to use when the given value matches with the contents of the column provided in the constructor of this class. * @param headersToUse the (optional) sequence of headers to assign to the given row writer processor */ public void addSwitchForValue(Object value, RowWriterProcessor rowProcessor, String... headersToUse) { addSwitch(new Switch(rowProcessor, headersToUse, null, value)); } /** * Associates a {@link RowWriterProcessor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param value the value to match against the column of incoming output rows and trigger the usage of the given row writer processor implementation. * @param rowProcessor the row writer processor implementation to use when the given value matches with the contents of the column provided in the constructor of this class. */ public void addSwitchForValue(Object value, RowWriterProcessor rowProcessor) { addSwitch(new Switch(rowProcessor, null, null, value)); } /** * Associates a {@link RowWriterProcessor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param value the value to match against the column of incoming output rows and trigger the usage of the given row writer processor implementation. * @param rowProcessor the row writer processor implementation to use when the given value matches with the contents of the column provided in the constructor of this class. * @param indexesToUse the (optional) sequence of column indexes to assign to the given row writer processor */ public void addSwitchForValue(Object value, RowWriterProcessor rowProcessor, int... indexesToUse) { addSwitch(new Switch(rowProcessor, null, indexesToUse, value)); } /** * Associates a {@link RowWriterProcessor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param beanType the type of annotated java beans whose instances will be used to trigger the usage of a different format. * @param headersToUse the (optional) sequence of headers to assign to the given row writer processor * @param the type of annotated java beans whose instances will be used to trigger the usage of a different format. */ public void addSwitchForType(Class beanType, String... headersToUse) { addSwitch(new Switch(headersToUse, null, beanType)); } /** * Associates a {@link RowWriterProcessor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param beanType the type of annotated java beans whose instances will be used to trigger the usage of a different format. * @param indexesToUse the (optional) sequence of column indexes to assign to the given row writer processor * @param the type of annotated java beans whose instances will be used to trigger the usage of a different format. */ public void addSwitchForType(Class beanType, int... indexesToUse) { addSwitch(new Switch(null, indexesToUse, beanType)); } /** * Associates a {@link RowWriterProcessor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param beanType the type of annotated java beans whose instances will be used to trigger the usage of a different format. * @param the type of annotated java beans whose instances will be used to trigger the usage of a different format. */ public void addSwitchForType(Class beanType) { addSwitch(new Switch(null, null, beanType)); } private void addSwitch(Switch newSwitch) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = newSwitch; types = Arrays.copyOf(types, types.length + 1); if (newSwitch.value != null && newSwitch.value.getClass() == Class.class) { types[types.length - 1] = (Class) newSwitch.value; } } private V getValue(Map map, int index) { int i = 0; for (Map.Entry e : map.entrySet()) { if (i == index) { return e.getValue(); } } return null; } private NormalizedString[] getHeadersFromSwitch(Object value) { for (int i = 0; i < switches.length; i++) { Switch s = getSwitch(value); if (s != null) { return s.headers; } } return null; } @Override public NormalizedString[] getHeaders(Object input) { if (input instanceof Object[]) { Object[] row = (Object[]) input; if (columnIndex < row.length) { return getHeadersFromSwitch(row[columnIndex]); } return null; } else { return getHeadersFromSwitch(input); } } @Override public NormalizedString[] getHeaders(Map headerMapping, Map mapInput) { Object mapValue = null; if (mapInput != null && !mapInput.isEmpty()) { String headerToUse = headerName; if (headerMapping != null) { if (headerName != null) { Object value = headerMapping.get(headerName); headerToUse = value == null ? null : value.toString(); } else if (columnIndex != -1) { Object value = getValue(headerMapping, columnIndex); headerToUse = value == null ? null : value.toString(); } } if (headerToUse != null) { mapValue = mapInput.get(headerToUse); } else { mapValue = getValue(mapInput, columnIndex); } } return getHeadersFromSwitch(mapValue); } /** * Returns the column index whose values will be used to switching from a row processor to another. * * @return the column index targeted by this switch. */ public int getColumnIndex() { return columnIndex; } private List getSwitchValues() { List values = new ArrayList(switches.length); for (Switch s : switches) { values.add(s.value); } return values; } @Override protected String describeSwitch() { return "Expecting one of values: " + getSwitchValues() + " at column index " + getColumnIndex(); } private static class Switch { final RowWriterProcessor processor; final NormalizedString[] headers; final int[] indexes; final Object value; Switch(RowWriterProcessor processor, String[] headers, int[] indexes, Object value) { this(processor, headers, indexes, value, null); } Switch(String[] headers, int[] indexes, Class type) { this(null, headers, indexes, type, type); } private Switch(RowWriterProcessor processor, String[] headers, int[] indexes, Object value, Class type) { if (type != null) { processor = new BeanWriterProcessor(type); if (headers == null && indexes == null) { headers = AnnotationHelper.deriveHeaderNamesFromFields(type, MethodFilter.ONLY_GETTERS); indexes = ArgumentUtils.toIntArray(Arrays.asList(AnnotationHelper.getSelectedIndexes(type, MethodFilter.ONLY_GETTERS))); } } this.processor = processor; this.headers = headers == null || headers.length == 0 ? null : NormalizedString.toIdentifierGroupArray(headers); this.indexes = indexes == null || indexes.length == 0 ? null : indexes; this.value = value; } } } RowListProcessor.java000077500000000000000000000040651475274123300356130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import java.util.*; /** * * A convenience {@link RowProcessor} implementation for storing all rows parsed into a list. * A typical use case of this class will be: * *
 *
 * parserSettings.setRowProcessor(new RowListProcessor());
 * parser.parse(reader); // will invoke the {@link RowListProcessor#rowProcessed(String[], ParsingContext)} method for each parsed record.
 *
 * String[] headers = rowProcessor.getHeaders();
 * List<String[]> rows = rowProcessor.getRows();
 *
 * 

* * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class RowListProcessor extends AbstractListProcessor implements RowProcessor{ /** * Creates a new processor of {@code String[]} rows. */ public RowListProcessor() { } /** * Creates a new processor of {@code String[]} rows. * * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} returned by {@link #getRows()} */ public RowListProcessor(int expectedRowCount) { super(expectedRowCount); } } RowPlacement.java000066400000000000000000000022551475274123300347040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; /** * An indicator of where the input a row is placed in relation to others. Currently used by {@link MasterDetailProcessor}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public enum RowPlacement { /** * Indicates a row is above other rows. */ TOP, /** * Indicates a row is below other rows. */ BOTTOM } RowProcessor.java000077500000000000000000000114131475274123300347520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; import com.univocity.parsers.conversions.*; /** * The essential callback interface to handle records parsed by any parser that extends {@link AbstractParser}. * *

When parsing an input, univocity-parsers will obtain the RowProcessor from {@link CommonParserSettings#getRowProcessor()}, and * delegate each parsed row to {@link RowProcessor#rowProcessed(String[], ParsingContext)}. * *

Before parsing the first row, the parser will invoke the {@link RowProcessor#processStarted(ParsingContext)} method. * By this time the input buffer will be already loaded and ready to be consumed. * *

After parsing the last row, all resources are closed and the processing stops. Only after the {@link RowProcessor#processEnded(ParsingContext)} is called so you * can perform any additional housekeeping you might need. * *

More control and information over the parsing process are provided by the {@link ParsingContext} object. * *

univocity-parsers provides many useful default implementations of this interface in the package {@link com.univocity.parsers.common.processor}, namely: * *

    *
  • {@link RowListProcessor}: convenience class for storing the processed rows into a list.
  • *
  • {@link ObjectRowProcessor}: used for processing rows and executing conversions of parsed values to objects using instances of {@link Conversion}
  • *
  • {@link ObjectRowListProcessor}: convenience class for rows of converted objects using {@link ObjectRowProcessor} into a list.
  • *
  • {@link MasterDetailProcessor}: used for reading inputs where records are organized in a master-detail fashion (with a master element that contains a list of associated elements)
  • *
  • {@link MasterDetailListProcessor}: convenience class for storing {@link MasterDetailRecord} created by instances created by {@link MasterDetailProcessor} into a list
  • *
  • {@link BeanProcessor}: used for automatically create and populate javabeans annotated with the annotations provided in package {@link com.univocity.parsers.annotations}
  • *
  • {@link BeanListProcessor}: convenience class for storing all javabeans created by {@link BeanProcessor} into a list
  • *
* * @see com.univocity.parsers.common.AbstractParser * @see com.univocity.parsers.common.CommonParserSettings * @see com.univocity.parsers.common.ParsingContext * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface RowProcessor extends Processor { /** * This method will by invoked by the parser once, when it is ready to start processing the input. * * @param context A contextual object with information and controls over the current state of the parsing process */ void processStarted(ParsingContext context); /** * Invoked by the parser after all values of a valid record have been processed. * * @param row the data extracted by the parser for an individual record. Note that: *
    *
  • it will never by null.
  • *
  • it will never be empty unless explicitly configured using {@link CommonSettings#setSkipEmptyLines(boolean)}
  • *
  • it won't contain lines identified by the parser as comments. To disable comment processing set {@link Format#setComment(char)} to '\0'
  • *
* @param context A contextual object with information and controls over the current state of the parsing process */ void rowProcessed(String[] row, ParsingContext context); /** * This method will by invoked by the parser once, after the parsing process stopped and all resources were closed. *

It will always be called by the parser: in case of errors, if the end of the input us reached, or if the user stopped the process manually using {@link ParsingContext#stop()}. * * @param context A contextual object with information and controls over the state of the parsing process */ void processEnded(ParsingContext context); } RowProcessorSwitch.java000066400000000000000000000031141475274123300361300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.core.*; /** * A special {@link RowProcessor} implementation that combines and allows switching among different * RowProcessors. Each RowProcessor will have its own {@link ParsingContext}. Concrete implementations of this class * are expected to implement the {@link #switchRowProcessor(String[], Context)} method and analyze the input row * to determine whether or not the current {@link RowProcessor} implementation must be changed to handle a special * circumstance (determined by the concrete implementation) such as a different row format. * * When the row processor is switched, the {@link #rowProcessorSwitched(RowProcessor, RowProcessor)} will be called, and * must be overridden, to notify the change to the user. */ public abstract class RowProcessorSwitch extends AbstractProcessorSwitch implements RowProcessor { }RowWriterProcessor.java000066400000000000000000000067261475274123300361570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import com.univocity.parsers.fixed.*; /** * The essential callback interface to convert input objects into a manageable format for writing. Used by any writer that extends {@link AbstractWriter}. * *

When writing to an output, the writer will obtain the RowWriterProcessor from {@link CommonWriterSettings#getRowWriterProcessor()}, and * invoke {@link RowWriterProcessor#write(Object, NormalizedString[], int[])} to convert the input to an array of objects. This array of objects will in turn be handed to the writer to produce a record in the expected format. * *

univocity-parsers provides some useful default implementations of this interface in the package {@link com.univocity.parsers.common.processor}, namely: * *

    *
  • {@link ObjectRowWriterProcessor}: used for executing conversions of Object values on input rows using instances of {@link Conversion} before writing to the output
  • *
  • {@link BeanWriterProcessor}: used for converting javabeans annotated with the annotations provided in package {@link com.univocity.parsers.annotations} into an object row before writing to the output
  • *
* * @see com.univocity.parsers.common.AbstractWriter * @see com.univocity.parsers.common.CommonWriterSettings * * @param the type that is converted by this implementation into an Object array, suitable for writing to the output. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface RowWriterProcessor { /** * * Converts the given input into an Object array that is suitable for writing. Used by format-specific writers that extend {@link AbstractWriter}. * * @param input The original input record that must be converted into an Object array before writing to an output. * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @return an Object array that is suitable for writing. If null or an empty array is returned then the writer might either skip this value or write an empty record (if {@link CommonSettings#getSkipEmptyLines()} is false) * * @see CsvWriter * @see FixedWidthWriter * @see CommonSettings * @see AbstractWriter */ Object[] write(T input, NormalizedString[] headers, int[] indexesToWrite); } RowWriterProcessorSwitch.java000066400000000000000000000142341475274123300373320ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import java.util.Arrays; import java.util.Map; /** * A special {@link RowWriterProcessor} implementation that combines and allows switching among different * RowWriterProcessors. Concrete implementations of this class * are expected to implement the {@code switchRowProcessor(T)} method and analyze the input row * to determine whether or not the current {@link RowWriterProcessor} implementation must be changed to handle a special * circumstance (determined by the concrete implementation) such as a different row format. * * When the row writer processor is switched, the {@link #rowProcessorSwitched(RowWriterProcessor, RowWriterProcessor)} * will be called, and must be overridden, to notify the change to the user. */ public abstract class RowWriterProcessorSwitch implements RowWriterProcessor { private RowWriterProcessor selectedRowWriterProcessor = null; private int minimumRowLength = Integer.MIN_VALUE; private NormalizedString[] normalizedHeaders; private String[] previousHeaders; /** * Analyzes an output row to determine whether or not the row writer processor implementation must be changed * * @param row a record with data to be written to the output * * @return the row writer processor implementation to use. If it is not the same as the one used by the previous row, * the returned row writer processor will be used, and the {@link #rowProcessorSwitched(RowWriterProcessor, RowWriterProcessor)} method * will be called. */ protected abstract RowWriterProcessor switchRowProcessor(Object row); /** * Returns the headers in use by the current row writer processor implementation, which can vary among row writer processors. * If {@code null}, the headers defined in {@link CommonWriterSettings#getHeaders()} will be returned. * * @return the current sequence of headers to use. */ protected NormalizedString[] getHeaders() { return null; } /** * Returns the indexes in use by the current row writer processor implementation, which can vary among row writer processors. * If {@code null}, the indexes of fields that have been selected using {@link CommonSettings#selectFields(String...)} * or {@link CommonSettings#selectIndexes(Integer...)} will be returned. * * @return the current sequence of indexes to use. */ protected int[] getIndexes() { return null; } /** * Notifies a change of row writer processor implementation. Users are expected to override this method to receive the notification. * * @param from the row writer processor previously in use * @param to the new row writer processor to use to continue processing the output rows. */ public void rowProcessorSwitched(RowWriterProcessor from, RowWriterProcessor to) { } /** * Returns the sequence of headers to use for processing an input record represented by a map * * A map of headers can be optionally provided to assign a name to the keys of the input map. This is useful when * the input map has keys will generate unwanted header names. * * @param headerMapping an optional map associating keys of the rowData map with expected header names * @param mapInput the record data * * @return the sequence of headers to use when processing the given input map. */ public abstract NormalizedString[] getHeaders(Map headerMapping, Map mapInput); /** * Returns the sequence of headers to use for processing an input record. * * @param input the record data * * @return the sequence of headers to use when processing the given record. */ public abstract NormalizedString[] getHeaders(Object input); protected abstract String describeSwitch(); /** * Returns the minimum row length based on the number of headers and index sizes * * @return the minimum length a row must have in order to be sent to the output */ public final int getMinimumRowLength() { if (minimumRowLength == Integer.MIN_VALUE) { minimumRowLength = 0; if (getHeaders() != null) { minimumRowLength = getHeaders().length; } if (getIndexes() != null) { for (int index : getIndexes()) { if (index + 1 > minimumRowLength) { minimumRowLength = index + 1; } } } } return minimumRowLength; } public Object[] write(Object input, String[] headers, int[] indicesToWrite) { if (previousHeaders != headers) { previousHeaders = headers; normalizedHeaders = NormalizedString.toArray(headers); } return write(input, normalizedHeaders, indicesToWrite); } @Override public Object[] write(Object input, NormalizedString[] headers, int[] indicesToWrite) { RowWriterProcessor processor = switchRowProcessor(input); if (processor == null) { DataProcessingException ex = new DataProcessingException("Cannot find switch for input. Headers: {headers}, indices to write: " + Arrays.toString(indicesToWrite) + ". " + describeSwitch()); ex.setValue("headers", Arrays.toString(headers)); ex.setValue(input); throw ex; } if (processor != selectedRowWriterProcessor) { rowProcessorSwitched(selectedRowWriterProcessor, processor); selectedRowWriterProcessor = processor; } NormalizedString[] headersToUse = getHeaders(); int[] indexesToUse = getIndexes(); headersToUse = headersToUse == null ? headers : headersToUse; indexesToUse = indexesToUse == null ? indicesToWrite : indexesToUse; return selectedRowWriterProcessor.write(input, headersToUse, indexesToUse); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/000077500000000000000000000000001475274123300324445ustar00rootroot00000000000000AbstractBatchedColumnProcessor.java000066400000000000000000000104001475274123300413170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * A {@link Processor} implementation that stores values of columns in batches. Use this implementation in favor of {@link AbstractColumnProcessor} * when processing large inputs to avoid running out of memory. * * Values parsed in each row will be split into columns of Strings. Each column has its own list of values. * *

During the execution of the process, the {@link #batchProcessed(int)} method will be invoked after a given number of rows has been processed.

*

The user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

*

After {@link #batchProcessed(int)} is invoked, all values will be discarded and the next batch of column values will be accumulated. * This process will repeat until there's no more rows in the input. * * @author Univocity Software Pty Ltd - parsers@univocity.com * * @see AbstractParser * @see BatchedColumnReader * @see Processor */ public abstract class AbstractBatchedColumnProcessor implements Processor, BatchedColumnReader { private final ColumnSplitter splitter; private final int rowsPerBatch; private int batchCount; private int batchesProcessed; /** * Constructs a batched column processor configured to invoke the {@link #batchesProcessed} method after a given number of rows has been processed. * @param rowsPerBatch the number of rows to process in each batch. */ public AbstractBatchedColumnProcessor(int rowsPerBatch) { splitter = new ColumnSplitter(rowsPerBatch); this.rowsPerBatch = rowsPerBatch; } @Override public void processStarted(T context) { splitter.reset(); batchCount = 0; batchesProcessed = 0; } @Override public void rowProcessed(String[] row, T context) { splitter.addValuesToColumns(row, context); batchCount++; if (batchCount >= rowsPerBatch) { batchProcessed(batchCount); batchCount = 0; splitter.clearValues(); batchesProcessed++; } } @Override public void processEnded(T context) { if (batchCount > 0) { batchProcessed(batchCount); } } @Override public final String[] getHeaders() { return splitter.getHeaders(); } @Override public final List> getColumnValuesAsList() { return splitter.getColumnValues(); } @Override public final void putColumnValuesInMapOfNames(Map> map) { splitter.putColumnValuesInMapOfNames(map); } @Override public final void putColumnValuesInMapOfIndexes(Map> map) { splitter.putColumnValuesInMapOfIndexes(map); } @Override public final Map> getColumnValuesAsMapOfNames() { return splitter.getColumnValuesAsMapOfNames(); } @Override public final Map> getColumnValuesAsMapOfIndexes() { return splitter.getColumnValuesAsMapOfIndexes(); } @Override public List getColumn(String columnName) { return splitter.getColumnValues(columnName, String.class); } @Override public List getColumn(int columnIndex) { return splitter.getColumnValues(columnIndex, String.class); } @Override public int getRowsPerBatch() { return rowsPerBatch; } @Override public int getBatchesProcessed() { return batchesProcessed; } @Override public abstract void batchProcessed(int rowsInThisBatch); } AbstractBatchedObjectColumnProcessor.java000066400000000000000000000126471475274123300424650ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import java.util.*; /** * * A {@link Processor} implementation for converting batches of rows extracted from any implementation of {@link AbstractParser} into columns of objects. *

This uses the value conversions provided by {@link Conversion} instances.

* *

For each row processed, a sequence of conversions will be executed to generate the appropriate object. Each resulting object will then be stored in * a list that contains the values of the corresponding column.

* *

During the execution of the process, the {@link #batchProcessed(int)} method will be invoked after a given number of rows has been processed.

*

The user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

*

After {@link #batchProcessed(int)} is invoked, all values will be discarded and the next batch of column values will be accumulated. * This process will repeat until there's no more rows in the input. * * @see AbstractParser * @see Processor * @see BatchedColumnReader * @see Conversion * @see AbstractObjectProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractBatchedObjectColumnProcessor extends AbstractObjectProcessor implements Processor, BatchedColumnReader { private final ColumnSplitter splitter; private final int rowsPerBatch; private int batchCount; private int batchesProcessed; /** * Constructs a abstract batched column processor configured to invoke the {@link #batchesProcessed} method after a given number of rows has been processed. * @param rowsPerBatch the number of rows to process in each batch. */ public AbstractBatchedObjectColumnProcessor(int rowsPerBatch) { splitter = new ColumnSplitter(rowsPerBatch); this.rowsPerBatch = rowsPerBatch; } @Override public void processStarted(T context) { super.processStarted(context); splitter.reset(); batchCount = 0; batchesProcessed = 0; } @Override public void rowProcessed(Object[] row, T context) { splitter.addValuesToColumns(row, context); batchCount++; if (batchCount >= rowsPerBatch) { batchProcessed(batchCount); batchCount = 0; splitter.clearValues(); batchesProcessed++; } } @Override public void processEnded(T context) { super.processEnded(context); if (batchCount > 0) { batchProcessed(batchCount); } } @Override public final String[] getHeaders() { return splitter.getHeaders(); } @Override public final List> getColumnValuesAsList() { return splitter.getColumnValues(); } @Override public final void putColumnValuesInMapOfNames(Map> map) { splitter.putColumnValuesInMapOfNames(map); } @Override public final void putColumnValuesInMapOfIndexes(Map> map) { splitter.putColumnValuesInMapOfIndexes(map); } @Override public final Map> getColumnValuesAsMapOfNames() { return splitter.getColumnValuesAsMapOfNames(); } @Override public final Map> getColumnValuesAsMapOfIndexes() { return splitter.getColumnValuesAsMapOfIndexes(); } @Override public List getColumn(String columnName) { return splitter.getColumnValues(columnName, Object.class); } @Override public List getColumn(int columnIndex) { return splitter.getColumnValues(columnIndex, Object.class); } /** * Returns the values of a given column. * @param columnName the name of the column in the input. * @param columnType the type of data in that column * @param the type of data in that column * @return a list with all data stored in the given column */ public List getColumn(String columnName, Class columnType){ return splitter.getColumnValues(columnName, columnType); } /** * Returns the values of a given column. * @param columnIndex the position of the column in the input (0-based). * @param columnType the type of data in that column * @param the type of data in that column * @return a list with all data stored in the given column */ public List getColumn(int columnIndex, Class columnType){ return splitter.getColumnValues(columnIndex, columnType); } @Override public int getRowsPerBatch() { return rowsPerBatch; } @Override public int getBatchesProcessed() { return batchesProcessed; } @Override public abstract void batchProcessed(int rowsInThisBatch); } AbstractBeanListProcessor.java000066400000000000000000000101611475274123300403140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import java.util.*; /** * A convenience {@link Processor} implementation for storing all java objects generated form the parsed input into a list. * A typical use case of this class will be: * *
{@code
 *
 * parserSettings.setRowProcessor(new BeanListProcessor(MyObject.class));
 * parser.parse(reader); // will invoke the {@link AbstractBeanListProcessor#beanProcessed(Object, C)} method for each generated object.
 *
 * List<T> beans = rowProcessor.getBeans();
 * }

* * @param the annotated class type. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see Processor * @see AbstractParser * @see AbstractBeanProcessor * @see BeanConversionProcessor */ public abstract class AbstractBeanListProcessor extends AbstractBeanProcessor { private List beans; private String[] headers; private final int expectedBeanCount; /** * Creates a processor that stores java beans of a given type into a list * * @param beanType the class with its attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public AbstractBeanListProcessor(Class beanType) { this(beanType, 0); } /** * Creates a processor that stores java beans of a given type into a list * * @param beanType the class with its attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} returned by {@link #getBeans()} */ public AbstractBeanListProcessor(Class beanType, int expectedBeanCount) { super(beanType, MethodFilter.ONLY_SETTERS); this.expectedBeanCount = expectedBeanCount <= 0 ? 10000 : expectedBeanCount; } /** * Stores the generated java bean produced with a parsed record into a list. * * @param bean java bean generated with the information extracted by the parser for an individual record * @param context A contextual object with information and controls over the current state of the parsing process * * @see com.univocity.parsers.common.processor.BeanProcessor */ @Override public void beanProcessed(T bean, C context) { beans.add(bean); } /** * Returns the list of generated java beans at the end of the parsing process. * * @return the list of generated java beans at the end of the parsing process. */ public List getBeans() { return beans == null ? Collections.emptyList() : beans; } @Override public void processStarted(C context) { super.processStarted(context); beans = new ArrayList(expectedBeanCount); } @Override public void processEnded(C context) { headers = context.headers(); super.processEnded(context); } /** * Returns the record headers. This can be either the headers defined in {@link CommonSettings#getHeaders()} or the headers parsed in the file when {@link CommonSettings#getHeaders()} equals true * * @return the headers of all records parsed. */ public String[] getHeaders() { return headers; } } AbstractBeanProcessor.java000066400000000000000000000063731475274123300374720ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; /** * A {@link Processor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects. *

The class type of the object must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For each row processed, a java bean instance of a given class will be created with its fields populated. *

This instance will then be sent to the {@link AbstractBeanProcessor#beanProcessed(Object, Context)} method, where the user can access it. * * @param the annotated class type. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see Processor */ public abstract class AbstractBeanProcessor extends BeanConversionProcessor implements Processor { /** * Creates a processor for java beans of a given type. * * @param beanType the class with its attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. * @param methodFilter filter to apply over annotated methods when the processor is reading data from beans (to write values to an output) * or writing values into beans (when parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. */ public AbstractBeanProcessor(Class beanType, MethodFilter methodFilter) { super(beanType, methodFilter); } /** * Converts a parsed row to a java object */ @Override public final void rowProcessed(String[] row, C context) { T instance = createBean(row, context); if (instance != null) { beanProcessed(instance, context); } } /** * Invoked by the processor after all values of a valid record have been processed and converted into a java object. * * @param bean java object created with the information extracted by the parser for an individual record. * @param context A contextual object with information and controls over the current state of the parsing process */ public abstract void beanProcessed(T bean, C context); @Override public void processStarted(C context) { super.initialize(NormalizedString.toArray(context.headers())); } @Override public void processEnded(C context) { } } AbstractColumnProcessor.java000066400000000000000000000066601475274123300400610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * A simple {@link Processor} implementation that stores values of columns. * Values parsed in each row will be split into columns of Strings. Each column has its own list of values. * *

At the end of the process, the user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

* * *

Note: Storing the values of all columns may be memory intensive. For large inputs, use a {@link AbstractBatchedColumnProcessor} instead

* * @author Univocity Software Pty Ltd - parsers@univocity.com * * @see AbstractParser * @see Processor * @see ColumnReader */ public abstract class AbstractColumnProcessor implements Processor, ColumnReader { private final ColumnSplitter splitter; /** * Constructs a column processor, pre-allocating room for 1000 rows. */ public AbstractColumnProcessor() { this(1000); } /** * Constructs a column processor pre-allocating room for the expected number of rows to be processed * @param expectedRowCount the expected number of rows to be processed */ public AbstractColumnProcessor(int expectedRowCount) { splitter = new ColumnSplitter(expectedRowCount); } @Override public void processStarted(T context) { splitter.reset(); } @Override public void rowProcessed(String[] row, T context) { splitter.addValuesToColumns(row, context); } @Override public void processEnded(T context) { } @Override public final String[] getHeaders() { return splitter.getHeaders(); } @Override public final List> getColumnValuesAsList() { return splitter.getColumnValues(); } @Override public final void putColumnValuesInMapOfNames(Map> map) { splitter.putColumnValuesInMapOfNames(map); } @Override public final void putColumnValuesInMapOfIndexes(Map> map) { splitter.putColumnValuesInMapOfIndexes(map); } @Override public final Map> getColumnValuesAsMapOfNames() { return splitter.getColumnValuesAsMapOfNames(); } @Override public final Map> getColumnValuesAsMapOfIndexes() { return splitter.getColumnValuesAsMapOfIndexes(); } @Override public List getColumn(String columnName) { return splitter.getColumnValues(columnName, String.class); } @Override public List getColumn(int columnIndex) { return splitter.getColumnValues(columnIndex, String.class); } } AbstractConcurrentProcessor.java000066400000000000000000000155471475274123300407520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.concurrent.*; /** * A {@link Processor} implementation to perform row processing tasks in parallel. The {@code ConcurrentRowProcessor} * wraps another {@link Processor}, and collects rows read from the input. * The actual row processing is performed in by wrapped {@link Processor} in a separate thread. * * Note: by default the {@link Context} object passed on to the wrapped {@link Processor} will not reflect the * state of the parser at the time the row as generated, but the current state of the parser instead. You can enable the * {@link #contextCopyingEnabled} flag to generate copies of the {@link Context} at the time each row was generated. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see Processor */ public abstract class AbstractConcurrentProcessor implements Processor { private final Processor processor; private boolean ended = false; private static class Node { public Node(String[] row, T context) { this.row = row; this.context = context; } public final T context; public final String[] row; public Node next; } private final ExecutorService executor = Executors.newSingleThreadExecutor(); private volatile long rowCount; private Future process; private T currentContext; private Node inputQueue; private volatile Node outputQueue; private final int limit; private volatile long input; private volatile long output; private final Object lock; private boolean contextCopyingEnabled = false; /** * Creates a non-blocking {@code AbstractConcurrentProcessor}, to perform processing of rows parsed from the input in a separate thread. * * @param processor a regular {@link Processor} implementation which will be executed in a separate thread. */ public AbstractConcurrentProcessor(Processor processor) { this(processor, -1); } /** * Creates a blocking {@code ConcurrentProcessor}, to perform processing of rows parsed from the input in a separate thread. * * @param processor a regular {@link Processor} implementation which will be executed in a separate thread. * @param limit the limit of rows to be kept in memory before blocking the input parsing process. */ public AbstractConcurrentProcessor(Processor processor, int limit) { if (processor == null) { throw new IllegalArgumentException("Row processor cannot be null"); } this.processor = processor; input = 0; output = 0; lock = new Object(); this.limit = limit; } /** * Indicates whether this processor should persist the {@link Context} object that is sent to the wrapped {@link Processor} * given in the constructor of this class, so all methods of {@link Context} reflect the parser state at the time * each row was parsed. * * Defaults to {@code false} * * @return a flag indicating whether the parsing context must be persisted along with the parsed row * so its methods reflect the state of the parser at the time the record was produced. */ public boolean isContextCopyingEnabled() { return contextCopyingEnabled; } /** * Configures this processor to persist the {@link Context} object that is sent to the wrapped {@link Processor} * given in the constructor of this class, so all methods of {@link Context} reflect the parser state at the time * each row was parsed. * * Defaults to {@code false} * * @param contextCopyingEnabled a flag indicating whether the parsing context must be persisted along with the parsed row * so its methods reflect the state of the parser at the time the record was produced. */ public void setContextCopyingEnabled(boolean contextCopyingEnabled) { this.contextCopyingEnabled = contextCopyingEnabled; } @Override public final void processStarted(T context) { currentContext = wrapContext(context); processor.processStarted(currentContext); startProcess(); } private void startProcess() { ended = false; rowCount = 0; process = executor.submit(new Callable() { @Override public Void call() { while (outputQueue == null && !ended) { Thread.yield(); } while (!ended) { rowCount++; processor.rowProcessed(outputQueue.row, outputQueue.context); while (outputQueue.next == null) { if (ended && outputQueue.next == null) { return null; } Thread.yield(); } outputQueue = outputQueue.next; output++; if (limit > 1) { synchronized (lock) { lock.notify(); } } } while (outputQueue != null) { rowCount++; processor.rowProcessed(outputQueue.row, outputQueue.context); outputQueue = outputQueue.next; } return null; } }); } @Override public final void rowProcessed(String[] row, T context) { if (inputQueue == null) { inputQueue = new Node(row, grabContext(context)); outputQueue = inputQueue; } else { if (limit > 1) { synchronized (lock) { try { if (input - output >= limit) { lock.wait(); } } catch (InterruptedException e) { ended = true; Thread.currentThread().interrupt(); return; } } } inputQueue.next = new Node(row, grabContext(context)); inputQueue = inputQueue.next; } input++; } @Override public final void processEnded(T context) { ended = true; if (limit > 1) { synchronized (lock) { lock.notify(); } } try { process.get(); } catch (ExecutionException e) { throw new DataProcessingException("Error executing process", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { try { processor.processEnded(grabContext(context)); } finally{ executor.shutdown(); } } } private T grabContext(T context) { if (contextCopyingEnabled) { return copyContext(context); } return currentContext; } protected final long getRowCount(){ return rowCount; } protected abstract T copyContext(T context); protected abstract T wrapContext(T context); } AbstractInputValueSwitch.java000066400000000000000000000314551475274123300402020ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import java.util.*; /** * A concrete implementation of {@link Processor} that allows switching among different implementations of * {@link Processor} based on values found on the rows parsed from the input. */ public abstract class AbstractInputValueSwitch extends AbstractProcessorSwitch { private int columnIndex = -1; private NormalizedString columnName = null; private Switch[] switches = new Switch[0]; private Switch defaultSwitch = null; private String[] headers; private int[] indexes; private static final Comparator caseSensitiveComparator = new Comparator() { @Override public int compare(String o1, String o2) { return (o1 == o2 || o1 != null && o1.equals(o2)) ? 0 : 1; //strings are interned, no issues here } }; private static final Comparator caseInsensitiveComparator = new Comparator() { @Override public int compare(String o1, String o2) { return (o1 == o2 || o1 != null && o1.equalsIgnoreCase(o2)) ? 0 : 1; //strings are interned, no issues here } }; private Comparator comparator = caseInsensitiveComparator; /** * Creates a switch that will analyze the first column of rows found in the input to determine which * {@link Processor} to use for each parsed row */ public AbstractInputValueSwitch() { this(0); } /** * Creates a switch that will analyze a column of rows parsed from the input to determine which * {@link Processor} to use. * * @param columnIndex the column index whose value will be used to determine which {@link Processor} to use for each parsed row. */ public AbstractInputValueSwitch(int columnIndex) { if (columnIndex < 0) { throw new IllegalArgumentException("Column index must be positive"); } this.columnIndex = columnIndex; } /** * Creates a switch that will analyze a column in rows parsed from the input to determine which * {@link Processor} to use. * * @param columnName name of the column whose values will be used to determine which {@link Processor} to use for each parsed row. */ public AbstractInputValueSwitch(String columnName) { if (columnName == null || columnName.trim().isEmpty()) { throw new IllegalArgumentException("Column name cannot be blank"); } this.columnName = NormalizedString.valueOf(columnName); } /** * Configures the switch to be case sensitive when comparing values provided in {@link #addSwitchForValue(String, Processor, String...)} * with the column given in the constructor of this class. * * @param caseSensitive a flag indicating whether the switch should compare values not considering the character case. */ public void setCaseSensitive(boolean caseSensitive) { this.comparator = caseSensitive ? caseSensitiveComparator : caseInsensitiveComparator; } /** * Configures the switch to use a custom {@link Comparator} to compare values in the column to analyze which is given in the constructor of this class. * * @param comparator the comparator to use for matching values in the input column with the values provided in {@link #addSwitchForValue(String, Processor, String...)} */ public void setComparator(Comparator comparator) { if (comparator == null) { throw new IllegalArgumentException("Comparator must not be null"); } this.comparator = comparator; } /** * Defines a default {@link Processor} implementation to use when no matching value is found in the input row. * * @param processor the default processor implementation * @param headersToUse the (optional) sequence of headers to assign to the {@link ParsingContext} of the given processor */ public void setDefaultSwitch(Processor processor, String... headersToUse) { defaultSwitch = new Switch(processor, headersToUse, null, null, null); } /** * Defines a default {@link Processor} implementation to use when no matching value is found in the input row. * * @param processor the default processor implementation */ public void setDefaultSwitch(Processor processor) { defaultSwitch = new Switch(processor, null, null, null, null); } /** * Defines a default {@link Processor} implementation to use when no matching value is found in the input row. * * @param processor the default processor implementation * @param indexesToUse the (optional) sequence of column indexes to assign to the {@link ParsingContext} of the given processor */ public void setDefaultSwitch(Processor processor, int... indexesToUse) { defaultSwitch = new Switch(processor, null, indexesToUse, null, null); } /** * Returns a flag indicating whether this switch contains a default {@link Processor} implementation to use when no matching value is found in the input row. * @return {@code true} if a {@link Processor} implementation has been provided to process input rows that doesn't have any matching value. */ public boolean hasDefaultSwitch() { return defaultSwitch != null; } /** * Associates a {@link Processor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param value the value to match against the column of the current input row and trigger the usage of the given processor implementation. * @param processor the processor implementation when the given value matches with the contents in the column provided in the constructor of this class. */ public void addSwitchForValue(String value, Processor processor) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = new Switch(processor, null, null, value, null); } /** * Associates a {@link Processor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param value the value to match against the column of the current input row and trigger the usage of the given processor implementation. * @param processor the processor implementation when the given value matches with the contents in the column provided in the constructor of this class. * @param headersToUse the (optional) sequence of headers to assign to the {@link ParsingContext} of the given processor */ public void addSwitchForValue(String value, Processor processor, String... headersToUse) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = new Switch(processor, headersToUse, null, value, null); } /** * Associates a {@link Processor} implementation with a custom matching algorithm to be executed in the column provided in the constructor of this class. * * @param matcher a user defined matching implementation to execute against the values in the column of the current input row and trigger the usage of the given processor implementation. * @param processor the processor implementation when the given value matches with the contents in the column provided in the constructor of this class. */ public void addSwitchForValue(CustomMatcher matcher, Processor processor) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = new Switch(processor, null, null, null, matcher); } /** * Associates a {@link Processor} implementation with a custom matching algorithm to be executed in the column provided in the constructor of this class. * * @param matcher a user defined matching implementation to execute against the values in the column of the current input row and trigger the usage of the given processor implementation. * @param processor the processor implementation when the given value matches with the contents in the column provided in the constructor of this class. * @param headersToUse the (optional) sequence of headers to assign to the {@link ParsingContext} of the given processor */ public void addSwitchForValue(CustomMatcher matcher, Processor processor, String... headersToUse) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = new Switch(processor, headersToUse, null, null, matcher); } /** * Associates a {@link Processor} implementation with an expected value to be matched in the column provided in the constructor of this class. * * @param value the value to match against the column of the current input row and trigger the usage of the given processor implementation. * @param processor the processor implementation when the given value matches with the contents in the column provided in the constructor of this class. * @param indexesToUse the (optional) sequence of column indexes to assign to the {@link ParsingContext} of the given processor */ public void addSwitchForValue(String value, Processor processor, int... indexesToUse) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = new Switch(processor, null, indexesToUse, value, null); } /** * Associates a {@link Processor} implementation with a custom matching algorithm to be executed in the column provided in the constructor of this class. * * @param matcher a user defined matching implementation to execute against the values in the column of the current input row and trigger the usage of the given processor implementation. * @param processor the processor implementation when the given value matches with the contents in the column provided in the constructor of this class. * @param indexesToUse the (optional) sequence of column indexes to assign to the {@link ParsingContext} of the given processor */ public void addSwitchForValue(CustomMatcher matcher, Processor processor, int... indexesToUse) { switches = Arrays.copyOf(switches, switches.length + 1); switches[switches.length - 1] = new Switch(processor, null, indexesToUse, null, matcher); } @Override public String[] getHeaders() { return headers; } @Override public int[] getIndexes() { return indexes; } @Override protected final Processor switchRowProcessor(String[] row, T context) { if (columnIndex == -1) { NormalizedString[] headers = NormalizedString.toIdentifierGroupArray(context.headers()); if (headers == null) { throw new DataProcessingException("Unable to determine position of column named '" + columnName + "' as no headers have been defined nor extracted from the input"); } columnIndex = ArgumentUtils.indexOf(headers, columnName); if (columnIndex == -1) { throw new DataProcessingException("Unable to determine position of column named '" + columnName + "' as it does not exist in the headers. Available headers are " + Arrays.toString(headers)); } } if (columnIndex < row.length) { String valueToMatch = row[columnIndex]; for (int i = 0; i < switches.length; i++) { Switch s = switches[i]; if ((s.matcher != null && s.matcher.matches(valueToMatch)) || comparator.compare(valueToMatch, s.value) == 0) { headers = s.headers; indexes = s.indexes; return s.processor; } } } if (defaultSwitch != null) { headers = defaultSwitch.headers; indexes = defaultSwitch.indexes; return defaultSwitch.processor; } headers = null; indexes = null; throw new DataProcessingException("Unable to process input row. No switches activated and no default switch defined.", columnIndex, row, null); } private static class Switch { final Processor processor; final String[] headers; final int[] indexes; final String value; final CustomMatcher matcher; Switch(Processor processor, String[] headers, int[] indexes, String value, CustomMatcher matcher) { this.processor = processor; this.headers = headers == null || headers.length == 0 ? null : headers; this.indexes = indexes == null || indexes.length == 0 ? null : indexes; this.value = value == null ? null : value.intern(); this.matcher = matcher; } @Override public String toString() { return "Switch{" + "processor=" + processor + ", headers=" + Arrays.toString(headers) + ", indexes=" + Arrays.toString(indexes) + ", value='" + value + '\'' + ", matcher=" + matcher + '}'; } } } AbstractListProcessor.java000077500000000000000000000067561475274123300375500ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * * A convenience {@link Processor} implementation for storing all rows parsed into a list. * A typical use case of this class will be: * *
 *
 * parserSettings.setRowProcessor(new RowListProcessor());
 * parser.parse(reader); // will invoke the {@link AbstractListProcessor#rowProcessed(String[], Context)} method for each parsed record.
 *
 * String[] headers = rowProcessor.getHeaders();
 * List<String[]> rows = rowProcessor.getRows();
 *
 * 

* * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractListProcessor implements Processor { private List rows; private String[] headers; private final int expectedRowCount; /** * Creates a new processor of {@code String[]} rows. */ public AbstractListProcessor() { this(0); } /** * Creates a new processor of {@code String[]} rows. * * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} returned by {@link #getRows()} */ public AbstractListProcessor(int expectedRowCount) { this.expectedRowCount = expectedRowCount <= 0 ? 10000 : expectedRowCount; } @Override public void processStarted(T context) { rows = new ArrayList(expectedRowCount); } /** * Stores the row extracted by the parser into a list. * * @param row the data extracted by the parser for an individual record. Note that: *
    *
  • it will never by null.
  • *
  • it will never be empty unless explicitly configured using {@link CommonSettings#setSkipEmptyLines(boolean)}
  • *
  • it won't contain lines identified by the parser as comments. To disable comment processing set {@link Format#setComment(char)} to '\0'
  • *
* @param context A contextual object with information and controls over the current state of the parsing process */ @Override public void rowProcessed(String[] row, T context) { rows.add(row); } @Override public void processEnded(T context) { headers = context.headers(); } /** * The list of parsed records * @return the list of parsed records */ public List getRows() { return rows == null ? Collections.emptyList() : rows; } /** * Returns the record headers. This can be either the headers defined in {@link CommonSettings#getHeaders()} or the headers parsed in the file when {@link CommonSettings#getHeaders()} equals true * @return the headers of all records parsed. */ public String[] getHeaders() { return headers; } } AbstractMasterDetailListProcessor.java000066400000000000000000000103571475274123300420340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import java.util.*; /** * * A convenience {@link Processor} implementation for storing all {@link MasterDetailRecord} generated form the parsed input into a list. * A typical use case of this class will be: * *
{@code
 *
 * ObjectRowListProcessor detailProcessor = new ObjectRowListProcessor();
 * MasterDetailListProcessor masterRowProcessor = new MasterDetailListProcessor(detailProcessor) {
 *      protected boolean isMasterRecord(String[] row, ParsingContext context) {
 *          return "Total".equals(row[0]);
 *      }
 * };
 *
 * parserSettings.setRowProcessor(masterRowProcessor);
 *
 * List<MasterDetailRecord> rows = masterRowProcessor.getRecords();
 * }

* * @see AbstractMasterDetailProcessor * @see Processor * @see AbstractParser * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractMasterDetailListProcessor extends AbstractMasterDetailProcessor { private final List records = new ArrayList(); private String[] headers; /** * Creates a MasterDetailListProcessor * * @param rowPlacement indication whether the master records are placed in relation its detail records in the input. * *
	 *
	 * Master record (Totals)       Master record (Totals)
	 *  above detail records         under detail records
	 *
	 *    Totals | 100                 Item   | 60
	 *    Item   | 60                  Item   | 40
	 *    Item   | 40                  Totals | 100
	 * 

* @param detailProcessor the {@link ObjectRowListProcessor} that processes detail rows. */ public AbstractMasterDetailListProcessor(RowPlacement rowPlacement, AbstractObjectListProcessor detailProcessor) { super(rowPlacement, detailProcessor); } /** * Creates a MasterDetailListProcessor assuming master records are positioned above its detail records in the input. * * @param detailProcessor the {@link ObjectRowListProcessor} that processes detail rows. */ public AbstractMasterDetailListProcessor(AbstractObjectListProcessor detailProcessor) { super(detailProcessor); } /** * Stores the generated {@link MasterDetailRecord} with the set of associated parsed records into a list. * * @param record {@link MasterDetailRecord} generated with a set of associated records extracted by the parser * @param context A contextual object with information and controls over the current state of the parsing process * * @see MasterDetailRecord */ @Override protected void masterDetailRecordProcessed(MasterDetailRecord record, T context) { records.add(record); } @Override public void processEnded(T context) { headers = context.headers(); super.processEnded(context); } /** * Returns the list of generated MasterDetailRecords at the end of the parsing process. * @return the list of generated MasterDetailRecords at the end of the parsing process. */ public List getRecords() { return this.records; } /** * Returns the record headers. This can be either the headers defined in {@link CommonSettings#getHeaders()} or the headers parsed in the file when {@link CommonSettings#getHeaders()} equals true * @return the headers of all records parsed. */ public String[] getHeaders() { return headers; } } AbstractMasterDetailProcessor.java000066400000000000000000000157311475274123300412010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.util.*; /** * * A {@link Processor} implementation for associating rows extracted from any implementation of {@link AbstractParser} into {@link MasterDetailRecord} instances. * *

For each row processed, a call to {@link AbstractMasterDetailProcessor#isMasterRecord(String[], Context)} will be made to identify whether or not it is a master row. *

The detail rows are automatically associated with the master record in an instance of {@link MasterDetailRecord}. *

When the master record is fully processed (i.e. {@link MasterDetailRecord} contains a master row and all associated detail rows), * it is sent to the user for processing in {@link AbstractMasterDetailProcessor#masterDetailRecordProcessed(MasterDetailRecord, Context)}. * *

Note this class extends {@link AbstractObjectProcessor} and value conversions provided by {@link Conversion} instances are fully supported. * * @see MasterDetailRecord * @see RowPlacement * @see AbstractParser * @see ObjectRowListProcessor * @see Processor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractMasterDetailProcessor extends AbstractObjectProcessor { private final AbstractObjectListProcessor detailProcessor; private MasterDetailRecord record; private final boolean isMasterRowAboveDetail; /** * Creates a MasterDetailProcessor * * @param rowPlacement indication whether the master records are placed in relation its detail records in the input. * *


	 *
	 * Master record (Totals)       Master record (Totals)
	 *  above detail records         under detail records
	 *
	 *    Totals | 100                 Item   | 60
	 *    Item   | 60                  Item   | 40
	 *    Item   | 40                  Totals | 100
	 * 

* @param detailProcessor the {@link ObjectRowListProcessor} that processes detail rows. */ public AbstractMasterDetailProcessor(RowPlacement rowPlacement, AbstractObjectListProcessor detailProcessor) { ArgumentUtils.noNulls("Row processor for reading detail rows", detailProcessor); this.detailProcessor = detailProcessor; this.isMasterRowAboveDetail = rowPlacement == RowPlacement.TOP; } /** * Creates a MasterDetailProcessor assuming master records are positioned above its detail records in the input. * * @param detailProcessor the {@link AbstractObjectListProcessor} that processes detail rows. */ public AbstractMasterDetailProcessor(AbstractObjectListProcessor detailProcessor) { this(RowPlacement.TOP, detailProcessor); } @Override public void processStarted(T context) { detailProcessor.processStarted(context); } /** * Invoked by the parser after all values of a valid record have been processed. * *

This method will then try to identify whether the given record is a master record. *

If it is, any conversions applied to the fields of the master record will be executed; *

Otherwise, the parsed row will be delegated to the {@link AbstractMasterDetailProcessor#detailProcessor} given in the constructor, and a detail record will be associated with the current {@link MasterDetailRecord} * * * @param row the data extracted by the parser for an individual record. * @param context A contextual object with information and controls over the current state of the parsing process */ @Override public final void rowProcessed(String[] row, T context) { if (isMasterRecord(row, context)) { super.rowProcessed(row, context); } else { if (isMasterRowAboveDetail && record == null) { return; } detailProcessor.rowProcessed(row, context); } } /** * Invoked by the parser after all values of a valid record have been processed and any conversions have been executed. * * @param row the data extracted by the parser for an individual record. * @param context A contextual object with information and controls over the current state of the parsing process */ @Override public final void rowProcessed(Object[] row, T context) { if (record == null) { record = new MasterDetailRecord(); record.setMasterRow(row); if (isMasterRowAboveDetail) { return; } } processRecord(row, context); } /** * Associates individual rows to a {@link MasterDetailRecord} and invokes {@link AbstractMasterDetailProcessor#masterDetailRecordProcessed(MasterDetailRecord, T)} when it is fully populated. * @param row a record extracted from the parser that had all (if any) conversions executed and is ready to be sent to the user. * @param context A contextual object with information and controls over the current state of the parsing process */ private void processRecord(Object[] row, T context) { List detailRows = detailProcessor.getRows(); record.setDetailRows(new ArrayList(detailRows)); if (!isMasterRowAboveDetail) { record.setMasterRow(row); } if (record.getMasterRow() != null) { masterDetailRecordProcessed(record.clone(), context); record.clear(); } detailRows.clear(); if (isMasterRowAboveDetail) { record.setMasterRow(row); } } @Override public void processEnded(T context) { super.processEnded(context); detailProcessor.processEnded(context); if (isMasterRowAboveDetail) { processRecord(null, context); } } /** * Queries whether or not the given row is a master record. * @param row the data extracted by the parser for an individual record. * @param context A contextual object with information and controls over the current state of the parsing process * @return true if the row is a master record, false if it is a detail record. */ protected abstract boolean isMasterRecord(String[] row, T context); /** * Invoked by the processor after a master row and all associated detail rows have been processed. * * @param record The master detail records * @param context A contextual object with information and controls over the current state of the parsing process */ protected abstract void masterDetailRecordProcessed(MasterDetailRecord record, T context); } AbstractMultiBeanListProcessor.java000066400000000000000000000113301475274123300413260ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import java.util.*; /** * A {@link Processor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects, storing * them into lists. This processor stores beans in separate lists, one for each type of bean processed. * All lists of all types will have the same number of entries as the number of records in the input. * When an object of a particular type can't be generated from a row, {@code null} will be added to the list. This ensures all lists are the same size, * and each element of each list contains the exact information parsed from each row. * *

The class types passed to the constructor of this class must contain the annotations provided in {@link com.univocity.parsers.annotations}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see Processor * @see AbstractBeanProcessor * @see AbstractMultiBeanProcessor */ public class AbstractMultiBeanListProcessor extends AbstractMultiBeanRowProcessor { private final Class[] beanTypes; private final List[] beans; private String[] headers; private final int expectedBeanCount; /** * Creates a processor for java beans of multiple types * * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} returned by {@link #getBeans()} * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public AbstractMultiBeanListProcessor(int expectedBeanCount, Class... beanTypes) { super(beanTypes); this.beanTypes = beanTypes; this.beans = new List[beanTypes.length]; this.expectedBeanCount = expectedBeanCount <= 0 ? 10000 : expectedBeanCount; } /** * Creates a processor for java beans of multiple types * * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public AbstractMultiBeanListProcessor(Class... beanTypes) { this(0, beanTypes); } @Override public final void processStarted(C context) { super.processStarted(context); for (int i = 0; i < beanTypes.length; i++) { beans[i] = new ArrayList(expectedBeanCount); } } @Override protected final void rowProcessed(Map, Object> row, C context) { for (int i = 0; i < beanTypes.length; i++) { Object bean = row.get(beanTypes[i]); beans[i].add(bean); } } @Override public final void processEnded(C context) { headers = context.headers(); super.processEnded(context); } /** * Returns the record headers. This can be either the headers defined in {@link CommonSettings#getHeaders()} or the headers parsed in the file when {@link CommonSettings#getHeaders()} equals true * * @return the headers of all records parsed. */ public final String[] getHeaders() { return headers; } /** * Returns the beans of a given type processed from the input. * * @param beanType the type of bean processed * @param the type of bean processed * * @return a list with all beans of the given that were processed from the input. Might contain nulls. */ public List getBeans(Class beanType) { int index = ArgumentUtils.indexOf(beanTypes, beanType); if (index == -1) { throw new IllegalArgumentException("Unknown bean type '" + beanType.getSimpleName() + "'. Available types are: " + Arrays.toString(beanTypes)); } return beans[index]; } /** * Returns a map of all beans processed from the input. * * @return all beans processed from the input. */ public Map, List> getBeans() { LinkedHashMap, List> out = new LinkedHashMap, List>(); for (int i = 0; i < beanTypes.length; i++) { out.put(beanTypes[i], beans[i]); } return out; } } AbstractMultiBeanProcessor.java000066400000000000000000000132721475274123300405010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.conversions.*; import java.util.*; /** * A {@link Processor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects. * *

The class types passed to the constructor of this class must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For each row processed, one or more java bean instances of any given class will be created with their fields populated. *

Each individual instance will then be sent to the {@link AbstractMultiBeanProcessor#beanProcessed(Class, Object, Context)} method, where the user can access the * beans parsed for each row. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see Processor * @see com.univocity.parsers.common.processor.BeanProcessor */ public abstract class AbstractMultiBeanProcessor implements Processor, ConversionProcessor { private final AbstractBeanProcessor[] beanProcessors; private final Map processorMap = new HashMap(); /** * Creates a processor for java beans of multiple types * * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public AbstractMultiBeanProcessor(Class... beanTypes) { ArgumentUtils.noNulls("Bean types", beanTypes); this.beanProcessors = new AbstractBeanProcessor[beanTypes.length]; for (int i = 0; i < beanTypes.length; i++) { final Class type = beanTypes[i]; beanProcessors[i] = new AbstractBeanProcessor(type, MethodFilter.ONLY_SETTERS) { @Override public void beanProcessed(Object bean, C context) { AbstractMultiBeanProcessor.this.beanProcessed(type, bean, context); } }; processorMap.put(type, beanProcessors[i]); } } public final Class[] getBeanClasses() { Class[] classes = new Class[beanProcessors.length]; for (int i = 0; i < beanProcessors.length; i++) { classes[i] = beanProcessors[i].beanClass; } return classes; } /** * Returns the {@link com.univocity.parsers.common.processor.BeanProcessor} responsible for processing a given class * * @param type the type of java bean being processed * @param the type of java bean being processed * * @return the {@link com.univocity.parsers.common.processor.BeanProcessor} that handles java beans of the given class. */ public AbstractBeanProcessor getProcessorOfType(Class type) { AbstractBeanProcessor processor = processorMap.get(type); if (processor == null) { throw new IllegalArgumentException("No processor of type '" + type.getName() + "' is available. Supported types are: " + processorMap.keySet()); } return processor; } /** * Invoked by the processor after all values of a valid record have been processed and converted into a java object. * * @param beanType the type of the object created by the parser using the information collected for an individual record. * @param beanInstance java object created with the information extracted by the parser for an individual record. * @param context A contextual object with information and controls over the current state of the parsing process */ public abstract void beanProcessed(Class beanType, Object beanInstance, C context); @Override public void processStarted(C context) { for (int i = 0; i < beanProcessors.length; i++) { beanProcessors[i].processStarted(context); } } @Override public final void rowProcessed(String[] row, C context) { for (int i = 0; i < beanProcessors.length; i++) { beanProcessors[i].rowProcessed(row, context); } } @Override public void processEnded(C context) { for (int i = 0; i < beanProcessors.length; i++) { beanProcessors[i].processEnded(context); } } @Override public FieldSet convertIndexes(Conversion... conversions) { List> sets = new ArrayList>(beanProcessors.length); for (int i = 0; i < beanProcessors.length; i++) { sets.add(beanProcessors[i].convertIndexes(conversions)); } return new FieldSet(sets); } @Override public void convertAll(Conversion... conversions) { for (int i = 0; i < beanProcessors.length; i++) { beanProcessors[i].convertAll(conversions); } } @Override public FieldSet convertFields(Conversion... conversions) { List> sets = new ArrayList>(beanProcessors.length); for (int i = 0; i < beanProcessors.length; i++) { sets.add(beanProcessors[i].convertFields(conversions)); } return new FieldSet(sets); } @Override public void convertType(Class type, Conversion... conversions) { for (int i = 0; i < beanProcessors.length; i++) { beanProcessors[i].convertType(type, conversions); } } } AbstractMultiBeanRowProcessor.java000066400000000000000000000061661475274123300411750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * * A {@link Processor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into java objects. * *

The class types passed to the constructor of this class must contain the annotations provided in {@link com.univocity.parsers.annotations}. * *

For each row processed, one or more java bean instances of any given class will be created with their fields populated. *

Once all beans are populated from an individual input record, they will be sent to through the {@link AbstractMultiBeanRowProcessor#rowProcessed(Map, Context)} method, * where the user can access all beans parsed for that row. * * @see AbstractParser * @see Processor * @see AbstractBeanProcessor * @see AbstractMultiBeanProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractMultiBeanRowProcessor extends AbstractMultiBeanProcessor { private final HashMap, Object> row = new HashMap, Object>(); private long record = -1L; /** * Creates a processor for java beans of multiple types * @param beanTypes the classes with their attributes mapped to fields of records parsed by an {@link AbstractParser} or written by an {@link AbstractWriter}. */ public AbstractMultiBeanRowProcessor(Class... beanTypes) { super(beanTypes); } public void processStarted(C context) { record = -1L; row.clear(); super.processStarted(context); } @Override public final void beanProcessed(Class beanType, Object beanInstance, C context) { if(record != context.currentRecord() && record != -1L){ submitRow(context); } record = context.currentRecord(); row.put(beanType, beanInstance); } private void submitRow(C context){ if(!row.isEmpty()){ rowProcessed(row, context); row.clear(); } } @Override public void processEnded(C context) { submitRow(context); super.processEnded(context); } /** * Invoked by the processor after all beans of a valid record have been processed. * @param row a map containing all object instances generated from an input row. The map is reused internally. Make a copy if you want to keep the map. * @param context A contextual object with information and controls over the current state of the parsing process */ protected abstract void rowProcessed(Map, Object> row, C context); }AbstractObjectColumnProcessor.java000066400000000000000000000111661475274123300412050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import java.util.*; /** * * A {@link Processor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into columns of objects. *

This uses the value conversions provided by {@link Conversion} instances.

* *

For each row processed, a sequence of conversions will be executed to generate the appropriate object. Each resulting object will then be stored in * a list that contains the values of the corresponding column.

* *

At the end of the process, the user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

* *

Note: Storing the values of all columns may be memory intensive. For large inputs, use a {@link AbstractBatchedObjectColumnProcessor} instead

* * @see AbstractParser * @see Processor * @see ColumnReader * @see Conversion * @see AbstractObjectProcessor * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractObjectColumnProcessor extends AbstractObjectProcessor implements ColumnReader { private final ColumnSplitter splitter; /** * Constructs a column processor, pre-allocating room for 1000 rows. */ public AbstractObjectColumnProcessor() { this(1000); } /** * Constructs a column processor pre-allocating room for the expected number of rows to be processed * @param expectedRowCount the expected number of rows to be processed */ public AbstractObjectColumnProcessor(int expectedRowCount) { splitter = new ColumnSplitter(expectedRowCount); } @Override public final String[] getHeaders() { return splitter.getHeaders(); } @Override public final List> getColumnValuesAsList() { return splitter.getColumnValues(); } @Override public final void putColumnValuesInMapOfNames(Map> map) { splitter.putColumnValuesInMapOfNames(map); } @Override public final void putColumnValuesInMapOfIndexes(Map> map) { splitter.putColumnValuesInMapOfIndexes(map); } @Override public final Map> getColumnValuesAsMapOfNames() { return splitter.getColumnValuesAsMapOfNames(); } @Override public final Map> getColumnValuesAsMapOfIndexes() { return splitter.getColumnValuesAsMapOfIndexes(); } @Override public void rowProcessed(Object[] row, T context) { splitter.addValuesToColumns(row, context); } @Override public void processStarted(T context) { super.processStarted(context); splitter.reset(); } /** * Returns the values of a given column. * @param columnName the name of the column in the input. * @param columnType the type of data in that column * @param the type of data in that column * @return a list with all data stored in the given column */ public List getColumn(String columnName, Class columnType){ return splitter.getColumnValues(columnName, columnType); } /** * Returns the values of a given column. * @param columnIndex the position of the column in the input (0-based). * @param columnType the type of data in that column * @param the type of data in that column * @return a list with all data stored in the given column */ public List getColumn(int columnIndex, Class columnType){ return splitter.getColumnValues(columnIndex, columnType); } @Override public List getColumn(String columnName) { return splitter.getColumnValues(columnName, Object.class); } @Override public List getColumn(int columnIndex) { return splitter.getColumnValues(columnIndex, Object.class); } } AbstractObjectListProcessor.java000077500000000000000000000074131475274123300406660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * A convenience {@link Processor} implementation for storing all rows parsed and converted to Object arrays into a list. * A typical use case of this class will be: * *
{@code
 *
 * ObjectRowListProcessor processor = new ObjectRowListProcessor();
 * processor.convertIndexes(Conversions.toBigDecimal()).set(4, 6);
 * parserSettings.setRowProcessor(new ObjectRowListProcessor());
 * parser.parse(reader); // will invoke the {@link AbstractObjectListProcessor#rowProcessed(Object[], T)} method for each parsed record.
 *
 * String[] headers = rowProcessor.getHeaders();
 * List<Object[]> rows = rowProcessor.getRows();
 * BigDecimal value1 = (BigDecimal) row.get(4);
 * BigDecimal value2 = (BigDecimal) row.get(6);
 * }

* * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see Processor * @see AbstractProcessor * @see AbstractObjectProcessor */ public abstract class AbstractObjectListProcessor extends AbstractObjectProcessor { private List rows; private String[] headers; private final int expectedRowCount; /** * Creates a new processor of {@code Object[]} rows with varying types. */ public AbstractObjectListProcessor() { this(0); } /** * Creates a new processor of {@code Object[]} rows with varying types. * * @param expectedRowCount expected number of rows to be parsed from the input. * Used to pre-allocate the size of the output {@link List} returned by {@link #getRows()} */ public AbstractObjectListProcessor(int expectedRowCount) { this.expectedRowCount = expectedRowCount <= 0 ? 10000 : expectedRowCount; } @Override public void processStarted(T context) { super.processStarted(context); rows = new ArrayList(expectedRowCount); } /** * Stores the row extracted by the parser and them converted to an Object array into a list. * * @param row the data extracted by the parser for an individual record and converted to an Object array. * @param context A contextual object with information and controls over the current state of the parsing process */ @Override public void rowProcessed(Object[] row, T context) { rows.add(row); } @Override public void processEnded(T context) { super.processEnded(context); this.headers = context.headers(); } /** * Returns the list of parsed and converted records * * @return the list of parsed and converted records */ public List getRows() { return rows == null ? Collections.emptyList() : rows; } /** * Returns the record headers. This can be either the headers defined in {@link CommonSettings#getHeaders()} or the headers parsed in the file when {@link CommonSettings#getHeaders()} equals true * * @return the headers of all records parsed. */ public String[] getHeaders() { return headers; } } AbstractObjectProcessor.java000066400000000000000000000063041475274123300400250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; /** * A {@link Processor} implementation for converting rows extracted from any implementation of {@link AbstractParser} into arrays of objects. *

This uses the value conversions provided by {@link Conversion} instances. * *

For each row processed, a sequence of conversions will be executed and stored in an object array, at its original position. *

The row with the result of these conversions will then be sent to the {@link AbstractObjectProcessor#rowProcessed(Object[], Context)} method, where the user can access it. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see AbstractParser * @see Processor */ public abstract class AbstractObjectProcessor extends DefaultConversionProcessor implements Processor { /** * Executes the sequences of conversions defined using {@link DefaultConversionProcessor#convertFields(Conversion...)}, * {@link DefaultConversionProcessor#convertIndexes(Conversion...)} and {@link DefaultConversionProcessor#convertAll(Conversion...)}, * for every field in the given row. * *

Each field will be transformed using the {@link Conversion#execute(Object)} method. *

In general the conversions will process a String and convert it to some object value (such as booleans, dates, etc). * * @param row the parsed record with its individual records as extracted from the original input. * @param context the current state of the parsing process. *

Fields that do not have any conversion defined will just be copied to the object array into their original positions. */ @Override public void rowProcessed(String[] row, T context) { Object[] objectRow = applyConversions(row, context); if (objectRow != null) { rowProcessed(objectRow, context); } } /** * Invoked by the processor after all values of a valid record have been processed and converted into an Object array. * * @param row object array created with the information extracted by the parser and then converted. * @param context A contextual object with information and controls over the current state of the parsing process */ public abstract void rowProcessed(Object[] row, T context); @Override public void processStarted(T context) { } @Override public void processEnded(T context) { } } AbstractProcessor.java000077500000000000000000000024701475274123300367010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; /** * A {@link Processor} implementation that just implements all methods defined by the interface. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public abstract class AbstractProcessor implements Processor { @Override public void processStarted(T context) { } @Override public void rowProcessed(String[] row, T context) { } @Override public void processEnded(T context) { } } AbstractProcessorSwitch.java000066400000000000000000000134221475274123300400570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import java.util.*; import java.util.Map.*; /** * A special {@link Processor} implementation that combines and allows switching among different * Processors. Each Processor will have its own {@link Context}. Concrete implementations of this class * are expected to implement the {@link #switchRowProcessor(String[], Context)} method and analyze the input row * to determine whether or not the current {@link Processor} implementation must be changed to handle a special * circumstance (determined by the concrete implementation) such as a different row format. * * When the processor is switched, the {@link #processorSwitched(Processor, Processor)} will be called, and * must be overridden, to notify the change to the user. */ public abstract class AbstractProcessorSwitch implements Processor, ColumnOrderDependent { private Map processors; private Processor selectedProcessor; private T contextForProcessor; /** * Analyzes the input to determine whether or not the row processor implementation must be changed * * @param row a row parsed from the input * @param context the current parsing context (not associated with the current row processor used by this class) * * @return the row processor implementation to use. If it is not the same as the one used by the previous row, * the returned row processor will be used, and the {@link #processorSwitched(Processor, Processor)} method * will be called. */ protected abstract Processor switchRowProcessor(String[] row, T context); /** * Returns the headers in use by the current row processor implementation, which can vary among row processors. * If {@code null}, the headers parsed by the input, or defined in {@link CommonParserSettings#getHeaders()} will be returned. * * @return the current sequence of headers to use. */ public String[] getHeaders() { return null; } /** * Returns the indexes in use by the current row processor implementation, which can vary among row processors. * If {@code null} all columns of a given record will be considered. * * @return the current sequence of indexes to use. */ public int[] getIndexes() { return null; } /** * Notifies a change of {@link Processor} implementation. Users are expected to override this method to receive the notification. * * @param from the processor previously in use * @param to the new processor to use to continue processing the input. */ public void processorSwitched(Processor from, Processor to) { if (from != null) { if (from instanceof RowProcessor) { if (to == null || to instanceof RowProcessor) { rowProcessorSwitched((RowProcessor) from, (RowProcessor) to); } } } else if (to != null && to instanceof RowProcessor) { rowProcessorSwitched((RowProcessor) from, (RowProcessor) to); } } /** * Notifies a change of {@link RowProcessor} implementation. Users are expected to override this method to receive the notification. * * @param from the row processor previously in use * @param to the new row processor to use to continue processing the input. */ public void rowProcessorSwitched(RowProcessor from, RowProcessor to) { } @Override public void processStarted(T context) { processors = new HashMap(); selectedProcessor = NoopProcessor.instance; } /** * Wraps a given parser context object that returns headers and extracted field indexes * associated with a given processor in this switch. * @param context the context to wrap * @return a wrapped context that returns the headers and extracted field * indexes from {@link #getHeaders()} and {@link #getIndexes()} */ protected abstract T wrapContext(T context); @Override public final void rowProcessed(String[] row, final T context) { Processor processor = switchRowProcessor(row, context); if (processor == null) { processor = NoopProcessor.instance; } if (processor != selectedProcessor) { contextForProcessor = processors.get(processor); if (processor != NoopProcessor.instance) { if (contextForProcessor == null) { contextForProcessor = wrapContext(context); processor.processStarted(contextForProcessor); processors.put(processor, contextForProcessor); } processorSwitched(selectedProcessor, processor); selectedProcessor = processor; if (getIndexes() != null) { int[] indexes = getIndexes(); String[] tmp = new String[indexes.length]; for (int i = 0; i < indexes.length; i++) { int index = indexes[i]; if (index < row.length) { tmp[i] = row[index]; } } row = tmp; } selectedProcessor.rowProcessed(row, contextForProcessor); } } else { selectedProcessor.rowProcessed(row, contextForProcessor); } } @Override public void processEnded(T context) { processorSwitched(selectedProcessor, null); selectedProcessor = NoopProcessor.instance; for (Entry e : processors.entrySet()) { e.getKey().processEnded(e.getValue()); } } public boolean preventColumnReordering() { return true; } }BatchedColumnReader.java000066400000000000000000000053021475274123300370630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; /** * A common interface for {@link Processor}s that collect the values parsed from each column in a row and store values of columns in batches. *

Use implementations of this interface implementation in favor of {@link ColumnReader} when processing large inputs to avoid running out of memory.

* *

During the execution of the process, the {@link #batchProcessed(int)} method will be invoked after a given number of rows has been processed.

* *

The user can access the lists with values parsed for all columns using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}.

*

After {@link #batchProcessed(int)} is invoked, all values will be discarded and the next batch of column values will be accumulated. * This process will repeat until there's no more rows in the input. * * @see AbstractBatchedColumnProcessor * @see AbstractBatchedObjectColumnProcessor * @see Processor * * @author Univocity Software Pty Ltd - parsers@univocity.com * * @param the type of the data stored by the columns. */ interface BatchedColumnReader extends ColumnReader { /** * Returns the number of rows processed in each batch * @return the number of rows per batch */ int getRowsPerBatch(); /** * Returns the number of batches already processed * @return the number of batches already processed */ int getBatchesProcessed(); /** * Callback to the user, where the lists with values parsed for all columns can be accessed using the methods {@link #getColumnValuesAsList()}, * {@link #getColumnValuesAsMapOfIndexes()} and {@link #getColumnValuesAsMapOfNames()}. * @param rowsInThisBatch the number of rows processed in the current batch. This corresponds to the number of elements of each list of each column. */ void batchProcessed(int rowsInThisBatch); } BeanConversionProcessor.java000066400000000000000000001001541475274123300400440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.beans.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; import static com.univocity.parsers.annotations.helpers.AnnotationHelper.*; /** * The base class for {@link Processor} and {@link RowWriterProcessor} implementations that support java beans annotated with the annotations provided in * {@link com.univocity.parsers.annotations}. * * @param the annotated class type. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see Processor * @see RowWriterProcessor */ public class BeanConversionProcessor extends DefaultConversionProcessor { final Class beanClass; final Constructor constructor; protected final Set parsedFields = new LinkedHashSet(); private int lastFieldIndexMapped = -1; private FieldMapping[] readOrder; private FieldMapping[] missing; private Object[] valuesForMissing; protected boolean initialized = false; boolean strictHeaderValidationEnabled = false; private NormalizedString[] syntheticHeaders = null; private Object[] row; private Map> nestedAttributes = null; protected final HeaderTransformer transformer; protected final MethodFilter methodFilter; private ColumnMapping columnMapper = new ColumnMapping(); private boolean mappingsForWritingValidated = false; /** * Initializes the BeanConversionProcessor with the annotated bean class. If any method of the given class has annotations, * only the setter methods will be used (getters will be ignored), making this processor useful mostly for parsing into * instances of the given class. * * @param beanType the class annotated with one or more of the annotations provided in {@link com.univocity.parsers.annotations}. * * @deprecated Use the {@link #BeanConversionProcessor(Class, MethodFilter)} constructor instead. */ @Deprecated public BeanConversionProcessor(Class beanType) { this(beanType, null, MethodFilter.ONLY_SETTERS); } /** * Initializes the BeanConversionProcessor with the annotated bean class * * @param beanType the class annotated with one or more of the annotations provided in {@link com.univocity.parsers.annotations}. * @param methodFilter filter to apply over annotated methods when the processor is reading data from beans (to write values to an output) * or writing values into beans (when parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. */ public BeanConversionProcessor(Class beanType, MethodFilter methodFilter) { this(beanType, null, methodFilter); } BeanConversionProcessor(Class beanType, HeaderTransformer transformer, MethodFilter methodFilter) { this.beanClass = beanType; this.transformer = transformer; this.methodFilter = methodFilter; Constructor c = null; for (Constructor constructor : this.beanClass.getDeclaredConstructors()) { if (constructor.getParameterTypes().length == 0) { c = constructor; break; } } if (c != null) { if (!c.isAccessible()) { c.setAccessible(true); } } this.constructor = (Constructor) c; } /** * Returns a flag indicating whether all headers declared in the annotated class must be present in the input. * If enabled, an exception will be thrown in case the input data does not contain all headers required. * * @return flag indicating whether strict validation of headers is enabled. */ public boolean isStrictHeaderValidationEnabled() { return strictHeaderValidationEnabled; } /** * Identifies and extracts fields annotated with the {@link Parsed} annotation */ public final void initialize() { initialize((NormalizedString[]) null); } /** * Returns a mapper that allows users to manually define mappings from * attributes/methods of a given class to columns to be parsed or written. * * This allows users to use instances of classes that are not annotated with {@link Parsed} nor * {@link Nested}. Any mappings defined with the column mapper will take * precedence over these annotations. * * @return the column mapper */ public final ColumnMapper getColumnMapper() { return columnMapper; } /** * Identifies and extracts fields annotated with the {@link Parsed} annotation * * @param headers headers parsed from the input. */ protected final void initialize(String[] headers) { initialize(NormalizedString.toArray(headers)); } /** * Identifies and extracts fields annotated with the {@link Parsed} annotation * * @param headers headers parsed from the input. */ protected final void initialize(NormalizedString[] headers) { if (!initialized) { initialized = true; Map allFields = AnnotationHelper.getAllFields(beanClass); Set nestedFields = columnMapper.getNestedAttributeNames(); for (String nestedAttributeName : nestedFields) { for (Map.Entry e : allFields.entrySet()) { Field field = e.getKey(); if (field.getName().equals(nestedAttributeName)) { Nested nested = AnnotationHelper.findAnnotation(field, Nested.class); if (nested == null) { processNestedField(field.getType(), field, field.getName(), e.getValue(), headers, null); } } } } for (Map.Entry e : allFields.entrySet()) { Field field = e.getKey(); PropertyWrapper property = e.getValue(); processField(field, field.getName(), property, headers); } for (Method method : AnnotationHelper.getAllMethods(beanClass, methodFilter)) { processField(method, method.getName(), null, headers); } readOrder = null; lastFieldIndexMapped = -1; identifyLiterals(); validateMappings(); } } private void identifyLiterals() { NormalizedString[] fieldNames = new NormalizedString[parsedFields.size()]; FieldMapping[] fields = parsedFields.toArray(new FieldMapping[0]); for (int i = 0; i < fieldNames.length; i++) { fieldNames[i] = fields[i].getFieldName(); } if (NormalizedString.identifyLiterals(fieldNames)) { for (int i = 0; i < fieldNames.length; i++) { fields[i].setFieldName(fieldNames[i]); } } } /** * Defines whether all headers declared in the annotated class must be present in the input. * If enabled, an exception will be thrown in case the input data does not contain all headers required. * * @param strictHeaderValidationEnabled flag indicating whether strict validation of headers is enabled. */ public void setStrictHeaderValidationEnabled(boolean strictHeaderValidationEnabled) { this.strictHeaderValidationEnabled = strictHeaderValidationEnabled; } void processField(AnnotatedElement element, String targetName, PropertyWrapper propertyDescriptor, NormalizedString[] headers) { FieldMapping mapping = null; Parsed annotation = AnnotationHelper.findAnnotation(element, Parsed.class); if (annotation != null) { mapping = new FieldMapping(beanClass, element, propertyDescriptor, transformer, headers); if (processField(mapping)) { parsedFields.add(mapping); setupConversions(element, mapping); } } MethodDescriptor descriptor = null; if (element instanceof Method) { descriptor = methodFilter.toDescriptor(columnMapper.getPrefix(), (Method) element); } if (columnMapper.isMapped(descriptor, targetName)) { if (mapping == null) { mapping = new FieldMapping(beanClass, element, propertyDescriptor, transformer, headers); columnMapper.updateMapping(mapping, targetName, descriptor); parsedFields.add(mapping); setupConversions(element, mapping); } else { columnMapper.updateMapping(mapping, targetName, descriptor); } } Nested nested = AnnotationHelper.findAnnotation(element, Nested.class); if (nested != null) { Class nestedType = AnnotationRegistry.getValue(element, nested, "type", nested.type()); if (nestedType == Object.class) { nestedType = getType(element); } processNestedField(nestedType, element, targetName, propertyDescriptor, headers, nested); } } private void processNestedField(Class nestedType, AnnotatedElement element, String targetName, PropertyWrapper propertyDescriptor, NormalizedString[] headers, Nested nested) { HeaderTransformer transformer = null; if (nested != null) { Class transformerType = AnnotationRegistry.getValue(element, nested, "headerTransformer", nested.headerTransformer()); if (transformerType != HeaderTransformer.class) { String[] args = AnnotationRegistry.getValue(element, nested, "args", nested.args()); transformer = AnnotationHelper.newInstance(HeaderTransformer.class, transformerType, args); } } FieldMapping mapping = new FieldMapping(nestedType, element, propertyDescriptor, null, headers); BeanConversionProcessor processor = createNestedProcessor(nested, nestedType, mapping, transformer); processor.conversions = this.conversions == null ? null : cloneConversions(); processor.columnMapper = new ColumnMapping(targetName, this.columnMapper); processor.initialize(headers); getNestedAttributes().put(mapping, processor); } /** * Creates a copy of the manually defined conversions to be applied over any columns. * * @return a copy of the currently defined conversions */ protected FieldConversionMapping cloneConversions() { return this.conversions.clone(); } Map> getNestedAttributes() { if (nestedAttributes == null) { nestedAttributes = new LinkedHashMap>(); } return nestedAttributes; } BeanConversionProcessor createNestedProcessor(Annotation annotation, Class nestedType, FieldMapping fieldMapping, HeaderTransformer transformer) { return new BeanConversionProcessor(nestedType, transformer, methodFilter); } /** * Determines whether or not an annotated field should be processed. * Can be overridden by subclasses for fine grained control. * * @param field the field to be processed * * @return {@code true} if the given field should be processed, otherwise {@code false}. */ protected boolean processField(FieldMapping field) { return true; } void validateMappings() { Map mappedNames = new HashMap(); Map mappedIndexes = new HashMap(); Set duplicateNames = new HashSet(); Set duplicateIndexes = new HashSet(); for (FieldMapping mapping : parsedFields) { NormalizedString name = mapping.getFieldName(); int index = mapping.getIndex(); if (index != -1) { if (mappedIndexes.containsKey(index)) { duplicateIndexes.add(mapping); duplicateIndexes.add(mappedIndexes.get(index)); } else { mappedIndexes.put(index, mapping); } } else { if (mappedNames.containsKey(name)) { duplicateNames.add(mapping); duplicateNames.add(mappedNames.get(name)); } else { mappedNames.put(name, mapping); } } } if (duplicateIndexes.size() > 0 || duplicateNames.size() > 0) { StringBuilder msg = new StringBuilder("Conflicting field mappings defined in annotated class: " + this.getBeanClass().getName()); for (FieldMapping mapping : duplicateIndexes) { msg.append("\n\tIndex: '").append(mapping.getIndex()).append("' of ").append(describeField(mapping.getTarget())); } for (FieldMapping mapping : duplicateNames) { msg.append("\n\tName: '").append(mapping.getFieldName()).append("' of ").append(describeField(mapping.getTarget())); } throw new DataProcessingException(msg.toString()); } } static String describeField(AnnotatedElement target) { if (target instanceof Method) { return "method: " + target; } return "field '" + AnnotationHelper.getName(target) + "' (" + getType(target).getName() + ')'; } /** * Goes through each field and method annotated with {@link Parsed} and extracts the sequence of {@link Conversion} elements associated with each one. * * @param target the field and method annotated with {@link Parsed} that must be associated with one or more {@link Conversion} objects * @param mapping a helper class to store information how the field or method is mapped to a parsed record. */ @SuppressWarnings("rawtypes") private void setupConversions(AnnotatedElement target, FieldMapping mapping) { List annotations = AnnotationHelper.findAllAnnotationsInPackage(target, Parsed.class.getPackage()); Conversion lastConversion = null; if (!annotations.isEmpty()) { Class targetType = getType(target); Parsed parsed = target == null ? null : findAnnotation(target, Parsed.class); String nullRead = getNullReadValue(target, parsed); String nullWrite = getNullWriteValue(target, parsed); for (Annotation annotation : annotations) { try { Conversion conversion = AnnotationHelper.getConversion(targetType, target, annotation, nullRead, nullWrite); if (conversion != null) { addConversion(conversion, mapping); lastConversion = conversion; } } catch (Throwable ex) { String path = annotation.annotationType().getSimpleName() + "' of field " + mapping; throw new DataProcessingException("Error processing annotation '" + path + ". " + ex.getMessage(), ex); } } if (targetType.isEnum()) { boolean hasEnumOptions = false; for (Annotation annotation : annotations) { if (annotation.annotationType() == EnumOptions.class) { hasEnumOptions = true; } } if (!hasEnumOptions) { Conversion conversion = createDefaultEnumConversion(targetType, nullRead, nullWrite); addConversion(conversion, mapping); lastConversion = conversion; } } } Parsed parsed = AnnotationHelper.findAnnotation(target, Parsed.class); boolean applyDefaultConversion = parsed == null || AnnotationRegistry.getValue(target, parsed, "applyDefaultConversion", parsed.applyDefaultConversion()); if (applyDefaultConversion) { Conversion defaultConversion = AnnotationHelper.getDefaultConversion(target); if (applyDefaultConversion(lastConversion, defaultConversion)) { addConversion(defaultConversion, mapping); } } } @SuppressWarnings("rawtypes") private boolean applyDefaultConversion(Conversion lastConversionApplied, Conversion defaultConversion) { if (defaultConversion == null) { return false; } if (lastConversionApplied == null) { return true; } if (lastConversionApplied.getClass() == defaultConversion.getClass()) { // no need to add the default conversion as it was manually specified by the user with his settings return false; } Method execute = getConversionMethod(lastConversionApplied, "execute"); Method revert = getConversionMethod(lastConversionApplied, "revert"); Method defaultExecute = getConversionMethod(defaultConversion, "execute"); Method defaultRevert = getConversionMethod(defaultConversion, "revert"); return !(execute.getReturnType() == defaultExecute.getReturnType() && revert.getReturnType() == defaultRevert.getReturnType()); } @SuppressWarnings("rawtypes") private Method getConversionMethod(Conversion conversion, String methodName) { Method targetMethod = null; for (Method method : conversion.getClass().getMethods()) { if (method.getName().equals(methodName) && !method.isSynthetic() && !method.isBridge() && ((method.getModifiers() & Modifier.PUBLIC) == 1) && method.getParameterTypes().length == 1 && method.getReturnType() != void.class) { if (targetMethod != null) { throw new DataProcessingException("Unable to convert values for class '" + beanClass + "'. Multiple '" + methodName + "' methods defined in conversion " + conversion.getClass() + '.'); } targetMethod = method; } } if (targetMethod != null) { return targetMethod; } //should never happen throw new DataProcessingException("Unable to convert values for class '" + beanClass + "'. Cannot find method '" + methodName + "' in conversion " + conversion.getClass() + '.'); } /** * Associates a conversion to a field of the java bean class. * * @param conversion The conversion object that must be executed against the given field * @param mapping the helper object that contains information about how a field is mapped. */ @SuppressWarnings("rawtypes") protected void addConversion(Conversion conversion, FieldMapping mapping) { if (conversion == null) { return; } if (mapping.isMappedToIndex()) { this.convertIndexes(conversion).add(mapping.getIndex()); } else { this.convertFields(conversion).add(NormalizedString.valueOf(mapping.getFieldName())); } } /** * Goes through a list of objects and associates each value to a particular field of a java bean instance * * @param instance the java bean instance that is going to have its properties set * @param row the values to associate with each field of the javabean. * @param context information about the current parsing process. */ void mapValuesToFields(T instance, Object[] row, Context context) { if (row.length > lastFieldIndexMapped) { this.lastFieldIndexMapped = row.length; mapFieldIndexes(context, row, NormalizedString.toIdentifierGroupArray(context.headers()), context.extractedFieldIndexes(), context.columnsReordered()); } int last = row.length < readOrder.length ? row.length : readOrder.length; int i = 0; for (; i < last; i++) { FieldMapping field = readOrder[i]; if (field != null) { Object value = row[i]; field.write(instance, value); } } if (conversions != null && row.length < readOrder.length) { i = last; for (; i < readOrder.length; i++) { FieldMapping field = readOrder[i]; if (field != null) { Object value = conversions.applyConversions(i, null, null); field.write(instance, value); } } } if (missing != null) { for (i = 0; i < missing.length; i++) { Object value = valuesForMissing[i]; if (value != null) { FieldMapping field = missing[i]; field.write(instance, value); } } } } /** * Identifies which fields are associated with which columns in a row. * * @param row A row with values for the given java bean. * @param headers The names of all fields of the record (including any header that is not mapped to the java bean). May be null if no headers have * been defined in {@link CommonSettings#getHeaders()} * @param indexes The indexes of the headers or row that are actually being used. May be null if no fields have been selected using * {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @param columnsReordered Indicates the indexes provided were reordered and do not match the original sequence of headers. */ private void mapFieldIndexes(Context context, Object[] row, NormalizedString[] headers, int[] indexes, boolean columnsReordered) { if (headers == null) { headers = ArgumentUtils.EMPTY_NORMALIZED_STRING_ARRAY; } boolean boundToIndex = false; int last = headers.length > row.length ? headers.length : row.length; for (FieldMapping mapping : parsedFields) { int index = mapping.getIndex(); if (last <= index) { last = index; boundToIndex = true; } } if (boundToIndex) { last++; } FieldMapping[] fieldOrder = new FieldMapping[last]; TreeSet fieldsNotFound = new TreeSet(); for (FieldMapping mapping : parsedFields) { if (mapping.isMappedToField()) { int[] positions = ArgumentUtils.indexesOf(headers, mapping.getFieldName()); if (positions.length == 0) { fieldsNotFound.add(mapping.getFieldName()); continue; } for (int i = 0; i < positions.length; i++) { fieldOrder[positions[i]] = mapping; } } else if (mapping.getIndex() < fieldOrder.length) { fieldOrder[mapping.getIndex()] = mapping; } } if (context != null && !fieldsNotFound.isEmpty()) { //Trigger this validation only when reading, not writing. if (headers.length == 0) { throw new DataProcessingException("Could not find fields " + fieldsNotFound.toString() + " in input. Please enable header extraction in the parser settings in order to match field names."); } if (strictHeaderValidationEnabled) { DataProcessingException exception = new DataProcessingException("Could not find fields " + fieldsNotFound.toString() + "' in input. Names found: {headers}"); exception.setValue("headers", Arrays.toString(headers)); throw exception; } } if (indexes != null) { // sets fields not read from CSV to null. for (int i = 0; i < fieldOrder.length; i++) { boolean isIndexUsed = false; for (int j = 0; j < indexes.length; j++) { if (indexes[j] == i) { isIndexUsed = true; break; } } if (!isIndexUsed) { fieldOrder[i] = null; } } // reorders the fields so they are positioned in the same order as in the incoming row[] if (columnsReordered) { FieldMapping[] newFieldOrder = new FieldMapping[indexes.length]; for (int i = 0; i < indexes.length; i++) { for (int j = 0; j < fieldOrder.length; j++) { int index = indexes[i]; if (index != -1) { FieldMapping field = fieldOrder[index]; newFieldOrder[i] = field; } } } fieldOrder = newFieldOrder; } } readOrder = fieldOrder; initializeValuesForMissing(); } private int nonNullReadOrderLength(){ int count = 0; for(int i = 0; i < readOrder.length; i++){ if(readOrder[i] != null){ count++; } } return count; } private void initializeValuesForMissing() { if (nonNullReadOrderLength() < parsedFields.size()) { Set unmapped = new LinkedHashSet(parsedFields); unmapped.removeAll(Arrays.asList(readOrder)); missing = unmapped.toArray(new FieldMapping[0]); String[] headers = new String[missing.length]; BeanConversionProcessor tmp = new BeanConversionProcessor(getBeanClass(), methodFilter) { protected void addConversion(Conversion conversion, FieldMapping mapping) { if (conversion == null) { return; } convertFields(conversion).add(NormalizedString.valueOf(mapping.getFieldName())); } }; for (int i = 0; i < missing.length; i++) { FieldMapping mapping = missing[i]; if (processField(mapping)) { tmp.setupConversions(mapping.getTarget(), mapping); } headers[i] = NormalizedString.valueOf(mapping.getFieldName()); } tmp.initializeConversions(headers, null); valuesForMissing = tmp.applyConversions(new String[missing.length], null); } else { missing = null; valuesForMissing = null; } } /** * Converts a record with values extracted from the parser into a java bean instance. * * @param row The values extracted from the parser * @param context The current state of the parsing process * * @return an instance of the java bean type defined in this class constructor. */ public T createBean(String[] row, Context context) { Object[] convertedRow = super.applyConversions(row, context); if (convertedRow == null) { return null; } T instance; try { instance = constructor.newInstance(); } catch (Throwable e) { throw new DataProcessingException("Unable to instantiate class '" + beanClass.getName() + '\'', row, e); } mapValuesToFields(instance, convertedRow, context); if (nestedAttributes != null) { processNestedAttributes(row, instance, context); } return instance; } void processNestedAttributes(String[] row, Object instance, Context context) { for (Map.Entry> e : nestedAttributes.entrySet()) { Object nested = e.getValue().createBean(row, context); if (nested != null) { e.getKey().write(instance, nested); } } } /** * Iterates over all fields in the java bean instance and extracts its values. * * @param instance the java bean instance to be read * @param row object array that will receive the values extracted from java bean * @param headers The names of all fields of the record (including any header that is not mapped to the java bean). May be null if no headers have * been defined in {@link CommonSettings#getHeaders()} * @param indexes The indexes of the headers or row that are actually being used. May be null if no fields have been selected using * {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @param columnsReordered Indicates the indexes provided were reordered and do not match the original sequence of headers. */ private void mapFieldsToValues(T instance, Object[] row, NormalizedString[] headers, int[] indexes, boolean columnsReordered) { if (row.length > this.lastFieldIndexMapped) { mapFieldIndexes(null, row, headers, indexes, columnsReordered); } int last = row.length < readOrder.length ? row.length : readOrder.length; for (int i = 0; i < last; i++) { FieldMapping field = readOrder[i]; if (field != null) { try { row[i] = field.read(instance); } catch (Throwable e) { if (!beanClass.isAssignableFrom(instance.getClass())) { handleConversionError(e, new Object[]{instance}, -1); throw toDataProcessingException(e, row, i); } else if (!handleConversionError(e, row, i)) { throw toDataProcessingException(e, row, i); }//else proceed } } } } /** * Converts a java bean instance into a sequence of values for writing. * * @param bean an instance of the type defined in this class constructor. * @param headers All field names used to produce records in a given destination. May be null if no headers have been defined in * {@link CommonSettings#getHeaders()} * @param indexesToWrite The indexes of the headers that are actually being written. May be null if no fields have been selected using * {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * * @return a row of objects containing the values extracted from the java bean */ public final Object[] reverseConversions(T bean, NormalizedString[] headers, int[] indexesToWrite) { if (!mappingsForWritingValidated) { mappingsForWritingValidated = true; validateMappingsForWriting(); } if (bean == null) { return null; } if (row == null) { if (headers != null) { row = new Object[headers.length]; } else if (indexesToWrite != null) { int minimumRowLength = 0; for (int index : indexesToWrite) { if (index + 1 > minimumRowLength) { minimumRowLength = index + 1; } } if (minimumRowLength < indexesToWrite.length) { minimumRowLength = indexesToWrite.length; } row = new Object[minimumRowLength]; } else { Set assignedIndexes = new HashSet(); int lastIndex = -1; for (FieldMapping f : parsedFields) { if (lastIndex < f.getIndex() + 1) { lastIndex = f.getIndex() + 1; } assignedIndexes.add(f.getIndex()); } if (lastIndex < parsedFields.size()) { lastIndex = parsedFields.size(); } row = new Object[lastIndex]; if (syntheticHeaders == null) { syntheticHeaders = new NormalizedString[lastIndex]; Iterator it = parsedFields.iterator(); for (int i = 0; i < lastIndex; i++) { if (assignedIndexes.contains(i)) { continue; } NormalizedString fieldName = null; while (it.hasNext() && (fieldName = it.next().getFieldName()) == null) ; syntheticHeaders[i] = fieldName; } } } } if (nestedAttributes != null) { for (Map.Entry> e : nestedAttributes.entrySet()) { Object nested = e.getKey().read(bean); if (nested != null) { BeanConversionProcessor nestedProcessor = (BeanConversionProcessor) e.getValue(); nestedProcessor.row = row; nestedProcessor.reverseConversions(nested, headers, indexesToWrite); } } } NormalizedString[] normalizedHeaders = NormalizedString.toIdentifierGroupArray(headers); if (syntheticHeaders != null) { normalizedHeaders = syntheticHeaders; } try { mapFieldsToValues(bean, row, normalizedHeaders, indexesToWrite, false); } catch (Throwable ex) { if (ex instanceof DataProcessingException) { DataProcessingException error = (DataProcessingException) ex; if (error.isHandled()) { return null; } else { throw error; } } else if (!handleConversionError(ex, row, -1)) { throw toDataProcessingException(ex, row, -1); } return null; } if (super.reverseConversions(true, row, normalizedHeaders, indexesToWrite)) { return row; } return null; } /** * Returns the class of the annotated java bean instances that will be manipulated by this processor. * * @return the class of the annotated java bean instances that will be manipulated by this processor. */ public Class getBeanClass() { return beanClass; } /** * Copies the given column mappings over to this processor. Further changes * to the given object won't be reflected on the copy stored internally. * * @param columnMapper the column mappings to use */ public void setColumnMapper(ColumnMapper columnMapper) { this.columnMapper = columnMapper == null ? new ColumnMapping() : (ColumnMapping) columnMapper.clone(); } private void validateMappingsForWriting() { Map targetCounts = new TreeMap(); Map targetSources = new HashMap(); populateTargetMaps(targetCounts, targetSources); StringBuilder msg = new StringBuilder(); for (Map.Entry e : targetCounts.entrySet()) { if (e.getValue() > 1) { String sources = targetSources.get(e.getKey()); if (msg.length() > 0) { msg.append("\n"); } msg.append('\t'); msg.append(e.getKey()); msg.append(": "); msg.append(sources); } } if (msg.length() > 0) { throw new DataProcessingException("Cannot write object as multiple attributes/methods have been mapped to the same output column:\n" + msg.toString()); } } private void populateTargetMaps(Map targetCounts, Map targetSources) { for (FieldMapping field : parsedFields) { Object outputColumn = field.getIndex() == -1 ? field.getFieldName() : NormalizedString.valueOf("Column #" + field.getIndex()); Integer count = targetCounts.get(outputColumn); if (count == null) { count = 0; } count++; targetCounts.put(outputColumn, count); String str = targetSources.get(outputColumn); String sourceName; if (field.getTarget() instanceof Method) { sourceName = ((Method) field.getTarget()).getName(); } else { sourceName = ((Field) field.getTarget()).getName(); } if (!columnMapper.getPrefix().isEmpty()) { sourceName = columnMapper.getPrefix() + '.' + sourceName; } if (str == null) { str = sourceName; } else { str += ", " + sourceName; } targetSources.put(outputColumn, str); } if (nestedAttributes != null) { for (BeanConversionProcessor nestedProcessor : nestedAttributes.values()) { nestedProcessor.populateTargetMaps(targetCounts, targetSources); } } } } ColumnOrderDependent.java000066400000000000000000000030231475274123300373060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.processor.*; /** * A marker interface used by special implementations of {@link RowProcessor} to indicate columns should not * be reordered by the parser. Conflicting settings provided in {@link com.univocity.parsers.common.CommonParserSettings#setColumnReorderingEnabled(boolean)} will be prevented. *

This marker is used to configure the parser automatically based on the specific {@link RowProcessor} implementation used. */ public interface ColumnOrderDependent { /** * Returns a flag indicating whether or not columns should be reordered by the parser * * @return a flag indicating whether or not columns should be reordered by the parser */ boolean preventColumnReordering(); } ColumnReader.java000066400000000000000000000070171475274123300356150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * A common interface for {@link Processor}s that collect the values parsed from each column in a row. * Namely: {@link AbstractColumnProcessor}, {@link AbstractObjectColumnProcessor}, {@link AbstractBatchedColumnProcessor} and {@link AbstractBatchedObjectColumnProcessor}. * * @see AbstractColumnProcessor * @see AbstractObjectColumnProcessor * @see AbstractBatchedColumnProcessor * @see AbstractBatchedObjectColumnProcessor * @see Processor * * @author Univocity Software Pty Ltd - parsers@univocity.com * * @param the type of the data stored by the columns. */ interface ColumnReader { /** * Returns the column headers. This can be either the headers defined in {@link CommonSettings#getHeaders()} or the headers parsed in * the input when {@link CommonSettings#getHeaders()} equals to {@code true} * @return the headers of all column parsed. */ String[] getHeaders(); /** * Returns the values processed for each column * @return a list of lists. The stored lists correspond to the position of the column processed from the input; Each list * contains the corresponding values parsed for a column, across multiple rows. */ List> getColumnValuesAsList(); /** * Fills a given map associating each column name to its list o values * @param map the map to hold the values of each column * @throws IllegalArgumentException if a column does not have a name associated to it. In this case, use {@link #putColumnValuesInMapOfIndexes(Map)} instead. */ void putColumnValuesInMapOfNames(Map> map); /** * Fills a given map associating each column index to its list of values * @param map the map to hold the values of each column */ void putColumnValuesInMapOfIndexes(Map> map); /** * Returns a map of column names and their respective list of values parsed from the input. * @return a map of column names and their respective list of values. */ Map> getColumnValuesAsMapOfNames(); /** * Returns a map of column indexes and their respective list of values parsed from the input. * @return a map of column indexes and their respective list of values. */ Map> getColumnValuesAsMapOfIndexes(); /** * Returns the values of a given column. * @param columnName the name of the column in the input. * @return a list with all data stored in the given column */ List getColumn(String columnName); /** * Returns the values of a given column. * @param columnIndex the position of the column in the input (0-based). * @return a list with all data stored in the given column */ List getColumn(int columnIndex); } ColumnSplitter.java000066400000000000000000000216371475274123300362250ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import java.util.*; /** * A utility class used split and store values columns parsed from each row in a {@link Processor}. Used to centralize common code used by implementations * of {@link ColumnReader}, namely: * {@link AbstractColumnProcessor}, {@link AbstractObjectColumnProcessor}, {@link AbstractBatchedColumnProcessor} and {@link AbstractBatchedObjectColumnProcessor}. * * @see ColumnReader * @see AbstractColumnProcessor * @see AbstractObjectColumnProcessor * @see AbstractBatchedColumnProcessor * @see AbstractBatchedObjectColumnProcessor * @see Processor * * @author Univocity Software Pty Ltd - parsers@univocity.com * * @param the type of values stored in the columns. */ class ColumnSplitter { private List> columnValues; private String[] headers = null; private int expectedRowCount = 1000; private long rowCount; private long addNullsFrom; /** * Creates a splitter allocating a space for a give number of expected rows to be read * @param expectedRowCount the expected number of rows to be parsed */ ColumnSplitter(int expectedRowCount) { if (expectedRowCount <= 0) { throw new IllegalArgumentException("Expected row count must be positive"); } this.expectedRowCount = expectedRowCount; } /** * Removes any column values previously processed */ void clearValues() { addNullsFrom = rowCount; this.columnValues = null; } /** * Prepares to execute a column splitting process from the beginning. * Removes any column values previously processed, as well as information about headers in the input. Resets row count to 0. */ void reset() { this.columnValues = null; this.headers = null; addNullsFrom = 0L; rowCount = 0L; } /** * Returns the values processed for each column * @return a list of lists. The stored lists correspond to the position of the column processed from the input; Each list * contains the corresponding values parsed for a column, across multiple rows. */ List> getColumnValues() { return columnValues; } /** * Returns the headers of the input. This can be either the headers defined in {@link CommonSettings#getHeaders()} * or the headers parsed in the input when {@link CommonSettings#getHeaders()} equals to {@code true} * @return the headers of all records parsed. */ String[] getHeaders() { return headers; } /** * Initializes the list of column values, the headers of each column and which columns to read if fields * have been selected using {@link CommonSettings#selectFields(String...)} or {@link CommonSettings#selectIndexes(Integer...)} * @param context the current active parsing context, which will be used to obtain information about headers and selected fields. */ private void initialize(Context context) { headers: if (this.headers == null) { String[] allHeaders = context.headers(); if (allHeaders == null) { headers = ArgumentUtils.EMPTY_STRING_ARRAY; break headers; } if (!context.columnsReordered()) { this.headers = allHeaders; break headers; } int[] selectedIndexes = context.extractedFieldIndexes(); final int last = Math.min(allHeaders.length, selectedIndexes.length); this.headers = new String[selectedIndexes.length]; for (int i = 0; i < last; i++) { int idx = selectedIndexes[i]; if(idx < allHeaders.length) { headers[i] = allHeaders[selectedIndexes[i]]; } } } columnValues = new ArrayList>(headers.length > 0 ? headers.length : 10); } /** * Returns the header of a particular column * @param columnIndex the index of the column whose header is to be obtained * @return the name of the column at the given index, or null if there's no header defined for the given column index. */ String getHeader(int columnIndex) { if (columnIndex < headers.length) { return headers[columnIndex]; } return null; } /** * Splits the row and add stores the value of each column in its corresponding list in {@link #columnValues} * @param row the row whose column values will be split * @param context the current active parsing context. */ void addValuesToColumns(T[] row, Context context) { if (columnValues == null) { initialize(context); } if (columnValues.size() < row.length) { int columnsToAdd = row.length - columnValues.size(); while (columnsToAdd-- > 0) { long records = context.currentRecord() - addNullsFrom; ArrayList values = new ArrayList(expectedRowCount < records ? (int) records : expectedRowCount); //adding nulls to the values of a new row with more columns than parsed before. //this ensures all columns will have the same number of values. while (--records > 0) { values.add(null); } columnValues.add(values); } } for (int i = 0; i < row.length; i++) { columnValues.get(i).add(row[i]); } //if we have more columns than what was parsed in the current row, we need to add nulls to the remaining columns. if (row.length < columnValues.size()) { for (int i = row.length; i < columnValues.size(); i++) { columnValues.get(i).add(null); } } rowCount++; } /** * Fills a given map associating each column name to its list o values * @param map the map to hold the values of each column * @throws IllegalArgumentException if a column does not have a name associated to it. In this case, use {@link #putColumnValuesInMapOfIndexes(Map)} instead. */ void putColumnValuesInMapOfNames(Map> map) { if (columnValues == null) { return; } for (int i = 0; i < columnValues.size(); i++) { String header = getHeader(i); if (header == null) { throw new DataProcessingException("Parsed input does not have header for column at index '" + i + "'. Parsed header names: " + Arrays.toString(getHeaders()), i); } map.put(header, columnValues.get(i)); } } /** * Returns the values of a given column. * @param columnIndex the position of the column in the input (0-based). * @param columnType the type of data in that column * @param the type of data in that column * @return a list with all data stored in the given column */ List getColumnValues(int columnIndex, Class columnType){ if(columnIndex < 0){ throw new IllegalArgumentException("Column index must be positive"); } if(columnIndex >= columnValues.size()){ throw new IllegalArgumentException("Column index must be less than " + columnValues.size() +". Got " + columnIndex); } return (List) columnValues.get(columnIndex); } /** * Returns the values of a given column. * @param columnName the name of the column in the input. * @param columnType the type of data in that column * @param the type of data in that column * @return a list with all data stored in the given column */ List getColumnValues(String columnName, Class columnType){ int index = ArgumentUtils.indexOf(headers, columnName); if(index == -1){ throw new IllegalArgumentException("No column named '" + columnName +"' has been found. Available column headers: " + Arrays.toString(headers)); } return getColumnValues(index, columnType); } /** * Fills a given map associating each column index to its list of values * @param map the map to hold the values of each column */ void putColumnValuesInMapOfIndexes(Map> map) { if (columnValues == null) { return; } for (int i = 0; i < columnValues.size(); i++) { map.put(i, columnValues.get(i)); } } /** * Returns a map of column names and their respective list of values parsed from the input. * @return a map of column names and their respective list of values. */ Map> getColumnValuesAsMapOfNames() { Map> map = new HashMap>(); putColumnValuesInMapOfNames(map); return map; } /** * Returns a map of column indexes and their respective list of values parsed from the input. * @return a map of column indexes and their respective list of values. */ Map> getColumnValuesAsMapOfIndexes() { Map> map = new HashMap>(); putColumnValuesInMapOfIndexes(map); return map; } } CompositeProcessor.java000077500000000000000000000070151475274123300371000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; /** * A utility {@link Processor} implementation that facilitates using multiple implementations of {@link Processor} at the * same time. * * @param the tye of the contextual object with information and controls over the current state of the parsing process */ public class CompositeProcessor implements Processor { private final Processor processors[]; /** * Creates a new {@code CompositeProcessor} with the list of {@link Processor} implementations to be used. * * @param processors the sequence of {@link Processor} implementations to be used. */ public CompositeProcessor(Processor... processors) { this.processors = processors; } /** * Initializes each {@link Processor} used by this class. This is invoked by the parser once, when it is ready to start processing the input. * * @param context A contextual object with information and controls over the current state of the parsing process */ @Override public void processStarted(C context) { for (int i = 0; i < processors.length; i++) { processors[i].processStarted(context); } } /** * Invoked by the parser after all values of a valid record have been processed. All {@link Processor} implementations * will have their corresponding {@link Processor#rowProcessed(String[], Context)} method called with the given row. * * @param row the data extracted by the parser for an individual record. Note that: *

    *
  • it will never by null.
  • *
  • it will never be empty unless explicitly configured using {@link CommonSettings#setSkipEmptyLines(boolean)}
  • *
  • it won't contain lines identified by the parser as comments. To disable comment processing set {@link Format#setComment(char)} to '\0'
  • *
* @param context A contextual object with information and controls over the current state of the parsing process */ @Override public void rowProcessed(String[] row, C context) { for (int i = 0; i < processors.length; i++) { processors[i].rowProcessed(row, context); } } /** * This method will by invoked by the parser once for each {@link Processor} used by this class, after the parsing process stopped and all resources were closed. *

It will always be called by the parser: in case of errors, if the end of the input us reached, or if the user stopped the process manually using {@link ParsingContext#stop()}. * * @param context A contextual object with information and controls over the state of the parsing process */ @Override public void processEnded(C context) { for (int i = 0; i < processors.length; i++) { processors[i].processEnded(context); } } }NoopProcessor.java000066400000000000000000000021341475274123300360430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; /** * A singleton instance of a {@link Processor} that does nothing. */ public final class NoopProcessor extends AbstractProcessor { /** * The singleton instance of the no-op {@link Processor} */ public static final Processor instance = new NoopProcessor(); private NoopProcessor() { } } Processor.java000077500000000000000000000112261475274123300352140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/processor/core/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor.core; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; /** * The essential callback interface to handle records parsed by any parser that extends {@link AbstractParser}. * *

When parsing an input, univocity-parsers will obtain the RowProcessor from {@link CommonParserSettings#getRowProcessor()}, and * delegate each parsed row to {@link Processor#rowProcessed(String[], Context)}. * *

Before parsing the first row, the parser will invoke the {@link Processor#processStarted(Context)} method. * By this time the input buffer will be already loaded and ready to be consumed. * *

After parsing the last row, all resources are closed and the processing stops. Only after the {@link Processor#processEnded(Context)} is called so you * can perform any additional housekeeping you might need. * *

More control and information over the parsing process are provided by the {@link Context} object. * *

univocity-parsers provides many useful default implementations of this interface in the package {@link com.univocity.parsers.common.processor}, namely: * *

    *
  • {@link RowListProcessor}: convenience class for storing the processed rows into a list.
  • *
  • {@link ObjectRowProcessor}: used for processing rows and executing conversions of parsed values to objects using instances of {@link Conversion}
  • *
  • {@link ObjectRowListProcessor}: convenience class for rows of converted objects using {@link ObjectRowProcessor} into a list.
  • *
  • {@link AbstractMasterDetailProcessor}: used for reading inputs where records are organized in a master-detail fashion (with a master element that contains a list of associated elements)
  • *
  • {@link AbstractMasterDetailListProcessor}: convenience class for storing {@link MasterDetailRecord} created by instances created by {@link AbstractMasterDetailProcessor} into a list
  • *
  • {@link AbstractBeanProcessor}: used for automatically create and populate javabeans annotated with the annotations provided in package {@link com.univocity.parsers.annotations}
  • *
  • {@link AbstractBeanListProcessor}: convenience class for storing all javabeans created by {@link AbstractBeanProcessor} into a list
  • *
* * @see AbstractParser * @see CommonParserSettings * @see ParsingContext * @see Context * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public interface Processor { /** * This method will by invoked by the parser once, when it is ready to start processing the input. * * @param context A contextual object with information and controls over the current state of the parsing process */ void processStarted(T context); /** * Invoked by the parser after all values of a valid record have been processed. * * @param row the data extracted by the parser for an individual record. Note that: *
    *
  • it will never by null.
  • *
  • it will never be empty unless explicitly configured using {@link CommonSettings#setSkipEmptyLines(boolean)}
  • *
  • it won't contain lines identified by the parser as comments. To disable comment processing set {@link Format#setComment(char)} to '\0'
  • *
* @param context A contextual object with information and controls over the current state of the parsing process */ void rowProcessed(String[] row, T context); /** * This method will by invoked by the parser once, after the parsing process stopped and all resources were closed. *

It will always be called by the parser: in case of errors, if the end of the input us reached, or if the user stopped the process manually using {@link ParsingContext#stop()}. * * @param context A contextual object with information and controls over the state of the parsing process */ void processEnded(T context); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/000077500000000000000000000000001475274123300307535ustar00rootroot00000000000000AbstractRecordFactory.java000066400000000000000000000022351475274123300357730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/recordpackage com.univocity.parsers.common.record; import com.univocity.parsers.common.*; /** * An abstract factory class which allows subclasses to provide implementations of {@link Record} * * @param the specific type of {@link Record} that is provided */ public abstract class AbstractRecordFactory { protected final M metaData; /** * Creates a new factory of {@link Record} based the state of a parser * * @param context the parser context */ public AbstractRecordFactory(Context context) { this.metaData = createMetaData(context); } /** * Creates a new {@link Record} with a row parsed from the input * * @param data the row parsed from the input * * @return a {@link Record} that provides many utility methods for consuming the data collected for a record parsed from the input. */ public abstract R newRecord(String[] data); public abstract M createMetaData(Context context); /** * Returns the metadata information associated with the records generated by this factory class * * @return the record metadata. */ public final M getRecordMetaData() { return metaData; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/MetaData.java000066400000000000000000000030101475274123300332700ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.record; import com.univocity.parsers.conversions.*; class MetaData { MetaData(int index) { this.index = index; } public final int index; public Class type = String.class; public Object defaultValue = null; @SuppressWarnings("rawtypes") private Conversion[] conversions = null; @SuppressWarnings("rawtypes") public Conversion[] getConversions(){ return conversions; } @SuppressWarnings("rawtypes") public void setDefaultConversions(Conversion[] conversions){ this.conversions = conversions; } @SuppressWarnings("unchecked") public Object convert(Object out){ if(conversions == null){ return out; } for (int i = 0; i < conversions.length; i++) { out = conversions[i].execute(out); } return out; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/Record.java000066400000000000000000001730231475274123300330420ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.record; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import java.math.*; import java.util.*; /** * A record parsed from the input, with convenience methods for easier data manipulation. * Records are obtained from {@link com.univocity.parsers.common.AbstractParser} methods such as *

    *
  • {@link AbstractParser#parseAllRecords(java.io.Reader)}
  • *
  • {@link AbstractParser#parseNextRecord()}
  • *
  • {@link AbstractParser#parseRecord(String)}
  • *
*/ public interface Record { /** * Returns the {@link RecordMetaData} associated with all records parsed from the input. * The metadata allows associating types, conversions and default values to any column, which * will be used when performing operations that can convert plain input strings into object instances. * Methods such as {@link #toFieldMap(String...)}, {@link #fillFieldMap(Map, String...)} and any other * method that returns Objects will use the metadata information to perform data conversions. * * @return the metadata object that provides information and basic data conversion controls * over all records parsed from the input. */ RecordMetaData getMetaData(); /** * Returns the plain values obtained from a record parsed from the input. * * @return a {@code String} array with all values parsed from the input for this record. */ String[] getValues(); /** * Returns a selection of plain values obtained from a record parsed from the input. * * @param fieldNames sequence of field names whose values will be returned. * * @return a {@code String} array with the selected values parsed from the input for this record. */ String[] getValues(String... fieldNames); /** * Returns a selection of plain values obtained from a record parsed from the input. * * @param fieldIndexes sequence of field indexes whose values will be returned. * * @return a {@code String} array with the selected values parsed from the input for this record. */ String[] getValues(int... fieldIndexes); /** * Returns a selection of plain values obtained from a record parsed from the input. * * @param fields sequence of fields whose values will be returned. * * @return a {@code String} array with the selected values parsed from the input for this record. */ String[] getValues(Enum... fields); /** * Returns the value contained in the given column. * * @param headerName the name of the column whose value will be returned * @param expectedType the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * * @return the value this record holds at the given column */ T getValue(String headerName, Class expectedType); /** * Returns the value contained in the given column. * * @param column the column whose value will be returned * @param expectedType the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * * @return the value this record holds at the given column */ T getValue(Enum column, Class expectedType); /** * Returns the value contained in the given column. * * @param columnIndex the position of the column whose value will be returned * @param expectedType the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * * @return the value this record holds at the given column */ T getValue(int columnIndex, Class expectedType); /** * Returns the value contained in the given column, after applying a sequence of conversion over it. * * @param headerName the name of the column whose value will be returned * @param expectedType the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * @param conversions the sequence of {@link Conversion}s to apply over the column value. * * @return the value this record holds at the given column */ @SuppressWarnings("rawtypes") T getValue(String headerName, Class expectedType, Conversion... conversions); /** * Returns the value contained in the given column, after applying a sequence of conversion over it. * * @param column the column whose value will be returned * @param expectedType the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * @param conversions the sequence of {@link Conversion}s to apply over the column value. * * @return the value this record holds at the given column */ @SuppressWarnings("rawtypes") T getValue(Enum column, Class expectedType, Conversion... conversions); /** * Returns the value contained in the given column, after applying a sequence of conversion over it. * * @param columnIndex the index of the column whose value will be returned * @param expectedType the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * @param conversions the sequence of {@link Conversion}s to apply over the column value. * * @return the value this record holds at the given column */ @SuppressWarnings("rawtypes") T getValue(int columnIndex, Class expectedType, Conversion... conversions); /** * Returns the value contained in the given column, or a default value if the column contains {@code null} * * @param headerName the name of the column whose value will be returned * @param defaultValue The default value to use if the column contains {@code null}. Its type will be used to derive * the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * * @return the value this record holds at the given column, or the default value in case the columns is {@code null} */ T getValue(String headerName, T defaultValue); /** * Returns the value contained in the given column, or a default value if the column contains {@code null} * * @param column the column whose value will be returned * @param defaultValue The default value to use if the column contains {@code null}. Its type will be used to derive * the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * * @return the value this record holds at the given column, or the default value in case the columns is {@code null} */ T getValue(Enum column, T defaultValue); /** * Returns the value contained in the given column, or a default value if the column contains {@code null} * * @param columnIndex index of the column whose value will be returned * @param defaultValue The default value to use if the column contains {@code null}. Its type will be used to derive * the expected type of the value. A conversion will be executed against the value * to produce a result with the expected type. * @param the expected value type * * @return the value this record holds at the given column, or the default value in case the column is {@code null} */ T getValue(int columnIndex, T defaultValue); /** * Returns the value contained in a given column, after applying a sequence of conversions over it. * * @param headerName the name of the column whose value will be returned * @param defaultValue The default value to use if the column contains {@code null}. * @param conversions the sequence of {@link Conversion}s to apply over the column value. * @param the expected value type * * @return the value this record holds at the given column */ @SuppressWarnings("rawtypes") T getValue(String headerName, T defaultValue, Conversion... conversions); /** * Returns the value contained in a given column, after applying a sequence of conversions over it. * * @param column the column whose value will be returned * @param defaultValue The default value to use if the column contains {@code null}. * @param conversions the sequence of {@link Conversion}s to apply over the column value. * @param the expected value type * * @return the value this record holds at the given column */ @SuppressWarnings("rawtypes") T getValue(Enum column, T defaultValue, Conversion... conversions); /** * Returns the value contained in a given column, after applying a sequence of conversions over it. * * @param columnIndex the index of the column whose value will be returned * @param defaultValue The default value to use if the column contains {@code null}. * @param conversions the sequence of {@link Conversion}s to apply over the column value. * @param the expected value type * * @return the value this record holds at the given column */ @SuppressWarnings("rawtypes") T getValue(int columnIndex, T defaultValue, Conversion... conversions); /** * Returns the {@code String} value in the given column * * @param headerName the name of the column * * @return the value stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ String getString(String headerName); /** * Returns the {@code String} value in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} * * @param column the column * * @return the value stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ String getString(Enum column); /** * Returns the {@code String} value in the given column, truncating it to a given maximum length * * @param columnIndex the index of the column * @param maxLength the maximum number of characters to be returned. * * @return the value stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ String getString(int columnIndex, int maxLength); /** * Returns the {@code String} value in the given column, truncating it to a given maximum length * * @param headerName the name of the column * @param maxLength the maximum number of characters to be returned. * * @return the value stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ String getString(String headerName, int maxLength); /** * Returns the {@code String} value in the given column, truncating it to a given maximum length * * @param column the column * @param maxLength the maximum number of characters to be returned. * * @return the value stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ String getString(Enum column, int maxLength); /** * Returns the {@code String} value in the given column * * @param columnIndex the index of the column * * @return the value stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ String getString(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Byte} and returns the result. * The {@link ByteConversion} conversion will be used perform the transformation. * * @param headerName the name of the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Byte} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Byte getByte(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Byte} and returns the result. * The {@link ByteConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Byte} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Byte getByte(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Byte} and returns the result. * The {@link ByteConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Byte} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Byte getByte(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Short} and returns the result. * The {@link ShortConversion} conversion will be used perform the transformation. * * @param headerName the name of the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Short} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Short getShort(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Short} and returns the result. * The {@link ShortConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Short} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Short getShort(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Short} and returns the result. * The {@link ShortConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Short} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Short getShort(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Integer} and returns the result. * The {@link IntegerConversion} conversion will be used perform the transformation. * * @param headerName the name of the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Integer} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Integer getInt(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Integer} and returns the result. * The {@link IntegerConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Integer} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Integer getInt(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Integer} and returns the result. * The {@link IntegerConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Integer} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Integer getInt(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link LongConversion} conversion will be used perform the transformation. * * @param headerName the name of the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Long getLong(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link LongConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Long getLong(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link LongConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Long getLong(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link FloatConversion} conversion will be used perform the transformation. * * @param headerName the name of the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Float getFloat(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Float} and returns the result. * The {@link FloatConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Float} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Float getFloat(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Float} and returns the result. * The {@link FloatConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Float} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Float getFloat(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Double} and returns the result. * The {@link DoubleConversion} conversion will be used perform the transformation. * * @param headerName the name of the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Double} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Double getDouble(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Double} and returns the result. * The {@link DoubleConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Double} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Double getDouble(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Double} and returns the result. * The {@link DoubleConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code Double} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Double getDouble(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Byte} and returns the result. * The {@link ByteConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Byte} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Byte getByte(String headerName); /** * Converts the {@code String} value in the given column to a {@code Byte} and returns the result. * The {@link ByteConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Byte} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Byte getByte(Enum column); /** * Converts the {@code String} value in the given column to a {@code Byte} and returns the result. * The {@link ByteConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code Byte} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Byte getByte(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Short} and returns the result. * The {@link ShortConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Short} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Short getShort(String headerName); /** * Converts the {@code String} value in the given column to a {@code Short} and returns the result. * The {@link ShortConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Short} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Short getShort(Enum column); /** * Converts the {@code String} value in the given column to a {@code Short} and returns the result. * The {@link ShortConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code Short} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Short getShort(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Integer} and returns the result. * The {@link IntegerConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Integer} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Integer getInt(String headerName); /** * Converts the {@code String} value in the given column to a {@code Integer} and returns the result. * The {@link IntegerConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Integer} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Integer getInt(Enum column); /** * Converts the {@code String} value in the given column to a {@code Integer} and returns the result. * The {@link IntegerConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code Integer} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Integer getInt(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link LongConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Long getLong(String headerName); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link LongConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Long getLong(Enum column); /** * Converts the {@code String} value in the given column to a {@code Long} and returns the result. * The {@link LongConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code Long} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Long getLong(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Float} and returns the result. * The {@link FloatConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Float} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Float getFloat(String headerName); /** * Converts the {@code String} value in the given column to a {@code Float} and returns the result. * The {@link FloatConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Float} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Float getFloat(Enum column); /** * Converts the {@code String} value in the given column to a {@code Float} and returns the result. * The {@link FloatConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code Float} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Float getFloat(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Double} and returns the result. * The {@link DoubleConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Double} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Double getDouble(String headerName); /** * Converts the {@code String} value in the given column to a {@code Double} and returns the result. * The {@link DoubleConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Double} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Double getDouble(Enum column); /** * Converts the {@code String} value in the given column to a {@code Double} and returns the result. * The {@link DoubleConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code Double} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Double getDouble(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Character} and returns the result. * The {@link CharacterConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Character} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Character getChar(String headerName); /** * Converts the {@code String} value in the given column to a {@code Character} and returns the result. * The {@link CharacterConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Character} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Character getChar(Enum column); /** * Converts the {@code String} value in the given column to a {@code Character} and returns the result. * The {@link CharacterConversion} conversion will be used perform the transformation. * * @param columnIndex the column index * * @return the {@code Character} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Character getChar(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Boolean} and returns the result. * The {@link BooleanConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code Boolean} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Boolean getBoolean(String headerName); /** * Converts the {@code String} value in the given column to a {@code Boolean} and returns the result. * The {@link BooleanConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code Boolean} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Boolean getBoolean(Enum column); /** * Converts the {@code String} value in the given column to a {@code Boolean} and returns the result. * The {@link BooleanConversion} conversion will be used perform the transformation. * * @param columnIndex the column index * * @return the {@code Boolean} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Boolean getBoolean(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Boolean} and returns the result. * The {@link BooleanConversion} conversion will be used perform the transformation. * * @param headerName the column name * @param trueString a {@code String} that represents the {@code Boolean} value {@code true} * @param falseString a {@code String} that represents the {@code Boolean} value {@code false} * * @return the {@code Boolean} stored in the given column if its original {@code String} value matches * either the trueString or falseString, otherwise {@code null} or the default specified in {@link RecordMetaData#defaultValueOf(String)} */ Boolean getBoolean(String headerName, String trueString, String falseString); /** * Converts the {@code String} value in the given column to a {@code Boolean} and returns the result. * The {@link BooleanConversion} conversion will be used perform the transformation. * * @param column the column * @param trueString a {@code String} that represents the {@code Boolean} value {@code true} * @param falseString a {@code String} that represents the {@code Boolean} value {@code false} * * @return the {@code Boolean} stored in the given column if its original {@code String} value matches * either the trueString or falseString, otherwise {@code null} or the default specified in {@link RecordMetaData#defaultValueOf(String)} */ Boolean getBoolean(Enum column, String trueString, String falseString); /** * Converts the {@code String} value in the given column to a {@code Boolean} and returns the result. * The {@link BooleanConversion} conversion will be used perform the transformation. * * @param columnIndex the column index * @param trueString a {@code String} that represents the {@code Boolean} value {@code true} * @param falseString a {@code String} that represents the {@code Boolean} value {@code false} * * @return the {@code Boolean} stored in the given column if its original {@code String} value matches * either the trueString or falseString, otherwise {@code null} or the default specified in {@link RecordMetaData#defaultValueOf(String)} */ Boolean getBoolean(int columnIndex, String trueString, String falseString); /** * Converts the {@code String} value in the given column to a {@code BigInteger} and returns the result. * The {@link BigIntegerConversion} conversion will be used perform the transformation. * * @param headerName the column name * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code BigInteger} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigInteger getBigInteger(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code BigInteger} and returns the result. * The {@link BigIntegerConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code BigInteger} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigInteger getBigInteger(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code BigInteger} and returns the result. * The {@link BigIntegerConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code BigInteger} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigInteger getBigInteger(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code BigDecimal} and returns the result. * The {@link BigDecimalConversion} conversion will be used perform the transformation. * * @param headerName the column name * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code BigDecimal} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigDecimal getBigDecimal(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code BigDecimal} and returns the result. * The {@link BigDecimalConversion} conversion will be used perform the transformation. * * @param column the column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code BigDecimal} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigDecimal getBigDecimal(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code BigDecimal} and returns the result. * The {@link BigDecimalConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} * * @return the {@code BigDecimal} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigDecimal getBigDecimal(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code BigInteger} and returns the result. * The {@link BigIntegerConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code BigInteger} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigInteger getBigInteger(String headerName); /** * Converts the {@code String} value in the given column to a {@code BigInteger} and returns the result. * The {@link BigIntegerConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code BigInteger} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigInteger getBigInteger(Enum column); /** * Converts the {@code String} value in the given column to a {@code BigInteger} and returns the result. * The {@link BigIntegerConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code BigInteger} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigInteger getBigInteger(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code BigDecimal} and returns the result. * The {@link BigDecimalConversion} conversion will be used perform the transformation. * * @param headerName the column name * * @return the {@code BigDecimal} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigDecimal getBigDecimal(String headerName); /** * Converts the {@code String} value in the given column to a {@code BigDecimal} and returns the result. * The {@link BigDecimalConversion} conversion will be used perform the transformation. * * @param column the column * * @return the {@code BigDecimal} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigDecimal getBigDecimal(Enum column); /** * Converts the {@code String} value in the given column to a {@code BigDecimal} and returns the result. * The {@link BigDecimalConversion} conversion will be used perform the transformation. * * @param columnIndex the columnIndex * * @return the {@code BigDecimal} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ BigDecimal getBigDecimal(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Date} and returns the result. * The {@link DateConversion} conversion will be used perform the transformation. * * @param headerName the column name * @param format the numeric mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"lenient=true"} * * @return the {@code Date} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Date getDate(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Date} and returns the result. * The {@link DateConversion} conversion will be used perform the transformation. * * @param column the column * @param format the date mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"lenient=true"} * * @return the {@code Date} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Date getDate(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Date} and returns the result. * The {@link DateConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the date mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"lenient=true"} * * @return the {@code Date} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Date getDate(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Calendar} and returns the result. * The {@link CalendarConversion} conversion will be used perform the transformation. * * @param headerName the column name * @param format the date mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"lenient=true"} * * @return the {@code Calendar} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Calendar getCalendar(String headerName, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Calendar} and returns the result. * The {@link CalendarConversion} conversion will be used perform the transformation. * * @param column the column * @param format the date mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"lenient=true"} * * @return the {@code Calendar} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Calendar getCalendar(Enum column, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Calendar} and returns the result. * The {@link CalendarConversion} conversion will be used perform the transformation. * * @param columnIndex the index of column * @param format the date mask to apply over the parsed content * @param formatOptions a sequence of key-value pairs with options to configure the underlying formatter. * Each element must be specified as {@code property_name=property_value}, * e.g. options={"lenient=true"} * * @return the {@code Calendar} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Calendar getCalendar(int columnIndex, String format, String... formatOptions); /** * Converts the {@code String} value in the given column to a {@code Date} and returns the result. * The {@link DateConversion} conversion sequence registered using * {@link RecordMetaData#convertFields(Conversion[])} will be used perform the transformation. * * @param headerName the column name * * @return the {@code Date} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Date getDate(String headerName); /** * Converts the {@code String} value in the given column to a {@code Date} and returns the result. * The {@link DateConversion} conversion sequence registered using * {@link RecordMetaData#convertFields(Conversion[])} will be used perform the transformation. * * @param column the column * * @return the {@code Date} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Date getDate(Enum column); /** * Converts the {@code String} value in the given column to a {@code Date} and returns the result. * The {@link DateConversion} conversion sequence registered using * {@link RecordMetaData#convertFields(Conversion[])} will be used perform the transformation. * * @param columnIndex the column index * * @return the {@code Date} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Date getDate(int columnIndex); /** * Converts the {@code String} value in the given column to a {@code Calendar} and returns the result. * The {@link CalendarConversion} conversion sequence registered using * {@link RecordMetaData#convertFields(Conversion[])} will be used perform the transformation. * * @param headerName the column name * * @return the {@code Calendar} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Calendar getCalendar(String headerName); /** * Converts the {@code String} value in the given column to a {@code Calendar} and returns the result. * The {@link CalendarConversion} conversion sequence registered using * {@link RecordMetaData#convertFields(Conversion[])} will be used perform the transformation. * * @param column the column * * @return the {@code Calendar} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Calendar getCalendar(Enum column); /** * Converts the {@code String} value in the given column to a {@code Calendar} and returns the result. * The {@link CalendarConversion} conversion sequence registered using * {@link RecordMetaData#convertFields(Conversion[])} will be used perform the transformation. * * @param columnIndex the column index * * @return the {@code Calendar} stored in the given column, {@code null} or the * default value specified in {@link RecordMetaData#defaultValueOf(String)} */ Calendar getCalendar(int columnIndex); /** * Converts the record into a map of {@code String} values. * * @param selectedFields the header names to use as keys of the map. If no selection then all headers will be used. * * @return a map containing the selected (or all) header names as the keys, and their respective values. */ Map toFieldMap(String... selectedFields); /** * Converts the record into a map of {@code String} values. * * @param selectedIndexes the column indexes to use as keys of the map. If no selection then all indexes will be used. * * @return a map containing the selected (or all) column indexes as the keys, and their respective values. */ Map toIndexMap(int... selectedIndexes); /** * Converts the record into a map of {@code String} values. * * @param enumType the enumeration type. * @param selectedColumns the columns to use as keys of the map. If no selection then all values of the enumeration type will be used. * @param the enumeration type * * @return a map containing the selected (or all) columns as the keys, and their respective values. */ > Map toEnumMap(Class enumType, T... selectedColumns); /** * Fills a map with the {@code String} values of this record. * * @param map the map that will receive the values * @param selectedFields the header names to use as keys of the map * * @return the input map, containing the selected header names as the keys, and their respective values. */ Map fillFieldMap(Map map, String... selectedFields); /** * Fills a map with the {@code String} values of this record. * * @param map the map that will receive the values * @param selectedIndexes the column indexes to use as keys of the map * * @return the input map, containing the selected column indexes as the keys, and their respective values. */ Map fillIndexMap(Map map, int... selectedIndexes); /** * Fills a map with the {@code String} values of this record. * * @param map the map that will receive the values * @param selectedColumns the column to use as keys of the map * @param the enumeration type * * @return the input map, containing the selected header names as the keys, and their respective values. */ > Map fillEnumMap(Map map, T... selectedColumns); /** * Converts the record into a map of {@code Object} values. Conversions must be registered using * {@link RecordMetaData#convertFields(Conversion[])} or {@link RecordMetaData#convertIndexes(Conversion[])} (Conversion[])}. * Columns without a known conversion will have their values put into the map as plain {@code String}s. * * @param selectedFields the column names to use as keys of the map * * @return a map containing the selected column names as the keys, and their respective values. */ Map toFieldObjectMap(String... selectedFields); /** * Converts the record into a map of {@code Object} values. Conversions must be registered using * {@link RecordMetaData#convertFields(Conversion[])} or {@link RecordMetaData#convertIndexes(Conversion[])} (Conversion[])}. * Columns without a known conversion will have their values put into the map as plain {@code String}s. * * @param selectedIndexes the column indexes to use as keys of the map * * @return a map containing the selected column indexes as the keys, and their respective values. */ Map toIndexObjectMap(int... selectedIndexes); /** * Converts the record into a map of {@code Object} values. Conversions must be registered using * {@link RecordMetaData#convertFields(Conversion[])} or {@link RecordMetaData#convertIndexes(Conversion[])} (Conversion[])}. * Columns without a known conversion will have their values put into the map as plain {@code String}s. * * @param enumType the enumeration type. * @param selectedColumns the column to use as keys of the map * @param the enumeration type * * @return a map containing the selected columns as the keys, and their respective values. */ > Map toEnumObjectMap(Class enumType, T... selectedColumns); /** * Fills a map with the converted {@code Object} values of this record. Conversions must be registered using * {@link RecordMetaData#convertFields(Conversion[])} or {@link RecordMetaData#convertIndexes(Conversion[])} (Conversion[])}. * Columns without a known conversion will have their values put into the map as plain {@code String}s. * * @param map the map that will receive the values * @param selectedFields the column names to use as keys of the map * * @return the input map, containing the selected columns as the keys, and their respective values. */ Map fillFieldObjectMap(Map map, String... selectedFields); /** * Fills a map with the converted {@code Object} values of this record. Conversions must be registered using * {@link RecordMetaData#convertFields(Conversion[])} or {@link RecordMetaData#convertIndexes(Conversion[])} (Conversion[])}. * Columns without a known conversion will have their values put into the map as plain {@code String}s. * * @param map the map that will receive the values * @param selectedIndexes the column indexes to use as keys of the map * * @return the input map, containing the selected columns as the keys, and their respective values. */ Map fillIndexObjectMap(Map map, int... selectedIndexes); /** * Fills a map with the converted {@code Object} values of this record. Conversions must be registered using * {@link RecordMetaData#convertFields(Conversion[])} or {@link RecordMetaData#convertIndexes(Conversion[])} (Conversion[])}. * Columns without a known conversion will have their values put into the map as plain {@code String}s. * * @param map the map that will receive the values * @param selectedColumns the column to use as keys of the map * @param the enumeration type * * @return the input map, containing the selected columns as the keys, and their respective values. */ > Map fillEnumObjectMap(Map map, T... selectedColumns); } RecordFactory.java000066400000000000000000000031611475274123300343060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.record; import com.univocity.parsers.common.*; /** * A factory class that provides implementations of {@link Record} based on the current state * of an {@link AbstractParser}(via its {@link ParsingContext}), and raw input records. */ public class RecordFactory extends AbstractRecordFactory { /** * Creates a new factory of {@link Record} based the state of a parser * * @param context the parser context */ public RecordFactory(Context context) { super(context); } /** * Creates a new {@link Record} with a row parsed from the input * * @param data the row parsed from the input * * @return a {@link Record} that provides many utility methods for consuming the data collected for a record parsed from the input. */ @Override public Record newRecord(String[] data) { return new RecordImpl(data, metaData); } @Override public RecordMetaDataImpl createMetaData(Context context) { return new RecordMetaDataImpl(context); } } RecordImpl.java000066400000000000000000000477061475274123300336150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/* * Copyright 2015 Univocity Software Pty Ltd * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.record; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import java.math.*; import java.util.*; class RecordImpl implements Record { private final String[] data; private final RecordMetaDataImpl metaData; RecordImpl(String[] data, RecordMetaDataImpl metaData) { this.data = data; this.metaData = metaData; } @Override public RecordMetaData getMetaData() { return metaData; } @Override public String[] getValues() { return data; } @Override public T getValue(String headerName, Class expectedType) { return metaData.getObjectValue(data, headerName, expectedType, null); } @Override public T getValue(Enum column, Class expectedType) { return metaData.getObjectValue(data, column, expectedType, null); } @Override public T getValue(int columnIndex, Class expectedType) { return metaData.getObjectValue(data, columnIndex, expectedType, null); } @SuppressWarnings("rawtypes") @Override public T getValue(String headerName, Class expectedType, Conversion... conversions) { return metaData.getValue(data, headerName, expectedType, conversions); } @SuppressWarnings("rawtypes") @Override public T getValue(Enum column, Class expectedType, Conversion... conversions) { return metaData.getValue(data, column, expectedType, conversions); } @SuppressWarnings("rawtypes") @Override public T getValue(int columnIndex, Class expectedType, Conversion... conversions) { return metaData.getValue(data, columnIndex, expectedType, conversions); } @SuppressWarnings("unchecked") @Override public T getValue(String headerName, T defaultValue) { return metaData.getObjectValue(data, headerName, (Class) defaultValue.getClass(), defaultValue); } @SuppressWarnings("unchecked") @Override public T getValue(Enum column, T defaultValue) { return metaData.getObjectValue(data, column, (Class) defaultValue.getClass(), defaultValue); } @SuppressWarnings("unchecked") @Override public T getValue(int columnIndex, T defaultValue) { return metaData.getObjectValue(data, columnIndex, (Class) defaultValue.getClass(), defaultValue); } @SuppressWarnings("rawtypes") @Override public T getValue(String headerName, T defaultValue, Conversion... conversions) { return metaData.getValue(data, headerName, defaultValue, conversions); } @SuppressWarnings("rawtypes") @Override public T getValue(Enum column, T defaultValue, Conversion... conversions) { return metaData.getValue(data, column, defaultValue, conversions); } @SuppressWarnings("rawtypes") @Override public T getValue(int columnIndex, T defaultValue, Conversion... conversions) { return metaData.getValue(data, columnIndex, defaultValue, conversions); } @Override public String getString(String headerName) { return metaData.getObjectValue(data, headerName, String.class, null); } @Override public String getString(Enum column) { return metaData.getObjectValue(data, column, String.class, null); } @Override public String getString(int columnIndex) { return metaData.getObjectValue(data, columnIndex, String.class, null); } @Override public String getString(String headerName, int maxLength) { return truncate(metaData.getValue(data, headerName), maxLength); } @Override public String getString(Enum column, int maxLength) { return truncate(metaData.getValue(data, column), maxLength); } @Override public String getString(int columnIndex, int maxLength) { return truncate(metaData.getValue(data, columnIndex), maxLength); } private String truncate(String string, int maxLength) { if (string == null) { return null; } if (maxLength < 0) { throw new IllegalArgumentException("Maximum length can't be negative"); } if (string.length() > maxLength) { return string.substring(0, maxLength); } return string; } @Override public Byte getByte(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Byte.class, null, format, formatOptions); } @Override public Byte getByte(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Byte.class, null, format, formatOptions); } @Override public Byte getByte(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Byte.class, null, format, formatOptions); } @Override public Short getShort(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Short.class, null, format, formatOptions); } @Override public Short getShort(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Short.class, null, format, formatOptions); } @Override public Short getShort(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Short.class, null, format, formatOptions); } @Override public Integer getInt(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Integer.class, null, format, formatOptions); } @Override public Integer getInt(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Integer.class, null, format, formatOptions); } @Override public Integer getInt(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Integer.class, null, format, formatOptions); } @Override public Long getLong(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Long.class, null, format, formatOptions); } @Override public Long getLong(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Long.class, null, format, formatOptions); } @Override public Long getLong(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Long.class, null, format, formatOptions); } @Override public Float getFloat(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Float.class, null, format, formatOptions); } @Override public Float getFloat(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Float.class, null, format, formatOptions); } @Override public Float getFloat(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Float.class, null, format, formatOptions); } @Override public Double getDouble(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Double.class, null, format, formatOptions); } @Override public Double getDouble(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Double.class, null, format, formatOptions); } @Override public Double getDouble(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Double.class, null, format, formatOptions); } @Override public Character getChar(String headerName) { return metaData.getObjectValue(data, headerName, Character.class, null); } @Override public Character getChar(Enum column) { return metaData.getObjectValue(data, column, Character.class, null); } @Override public Character getChar(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Character.class, null); } @Override public Boolean getBoolean(String headerName) { return metaData.getObjectValue(data, headerName, Boolean.class, null); } @Override public Boolean getBoolean(Enum column) { return metaData.getObjectValue(data, column, Boolean.class, null); } @Override public Boolean getBoolean(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Boolean.class, null); } @Override public Boolean getBoolean(String headerName, String trueString, String falseString) { return metaData.getObjectValue(data, headerName, Boolean.class, false, trueString, falseString); } @Override public Boolean getBoolean(Enum column, String trueString, String falseString) { return metaData.getObjectValue(data, column, Boolean.class, false, trueString, falseString); } @Override public Boolean getBoolean(int columnIndex, String trueString, String falseString) { return metaData.getObjectValue(data, columnIndex, Boolean.class, false, trueString, falseString); } @Override public BigInteger getBigInteger(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, BigInteger.class, null, format, formatOptions); } @Override public BigInteger getBigInteger(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, BigInteger.class, null, format, formatOptions); } @Override public BigInteger getBigInteger(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, BigInteger.class, null, format, formatOptions); } @Override public BigDecimal getBigDecimal(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, BigDecimal.class, null, format, formatOptions); } @Override public BigDecimal getBigDecimal(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, BigDecimal.class, null, format, formatOptions); } @Override public BigDecimal getBigDecimal(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, BigDecimal.class, null, format, formatOptions); } @Override public Date getDate(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Date.class, null, format, formatOptions); } @Override public Date getDate(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Date.class, null, format, formatOptions); } @Override public Date getDate(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Date.class, null, format, formatOptions); } @Override public Calendar getCalendar(String headerName, String format, String... formatOptions) { return metaData.getObjectValue(data, headerName, Calendar.class, null, format, formatOptions); } @Override public Calendar getCalendar(Enum column, String format, String... formatOptions) { return metaData.getObjectValue(data, column, Calendar.class, null, format, formatOptions); } @Override public Calendar getCalendar(int columnIndex, String format, String... formatOptions) { return metaData.getObjectValue(data, columnIndex, Calendar.class, null, format, formatOptions); } private String[] buildSelection(String[] selectedFields) { if (selectedFields.length == 0) { selectedFields = metaData.headers(); } return selectedFields; } private int[] buildSelection(int[] selectedIndexes) { if (selectedIndexes.length == 0) { selectedIndexes = new int[data.length]; for (int i = 0; i < data.length; i++) { selectedIndexes[i] = i; } } return selectedIndexes; } public > T[] buildSelection(Class enumType, T... selectedColumns) { if (selectedColumns.length == 0) { selectedColumns = enumType.getEnumConstants(); } return selectedColumns; } @Override public Map toIndexMap(int... selectedIndexes) { return fillIndexMap(new HashMap(selectedIndexes.length), selectedIndexes); } @Override public Map toFieldMap(String... selectedFields) { return fillFieldMap(new HashMap(selectedFields.length), selectedFields); } @Override public > Map toEnumMap(Class enumType, T... selectedColumns) { return fillEnumMap(new EnumMap(enumType), selectedColumns); } @Override public Map fillFieldMap(Map map, String... selectedFields) { selectedFields = buildSelection(selectedFields); for (int i = 0; i < selectedFields.length; i++) { map.put(selectedFields[i], getString(selectedFields[i])); } return map; } @Override public Map fillIndexMap(Map map, int... selectedIndexes) { selectedIndexes = buildSelection(selectedIndexes); for (int i = 0; i < selectedIndexes.length; i++) { map.put(selectedIndexes[i], getString(selectedIndexes[i])); } return map; } @Override public > Map fillEnumMap(Map map, T... selectedColumns) { for (int i = 0; i < selectedColumns.length; i++) { map.put(selectedColumns[i], getString(selectedColumns[i])); } return map; } @Override public Map toFieldObjectMap(String... selectedFields) { return fillFieldObjectMap(new HashMap(selectedFields.length), selectedFields); } @Override public Map toIndexObjectMap(int... selectedIndex) { return fillIndexObjectMap(new HashMap(selectedIndex.length), selectedIndex); } @Override public > Map toEnumObjectMap(Class enumType, T... selectedColumns) { return fillEnumObjectMap(new EnumMap(enumType), selectedColumns); } @Override public Map fillFieldObjectMap(Map map, String... selectedFields) { selectedFields = buildSelection(selectedFields); for (int i = 0; i < selectedFields.length; i++) { map.put(selectedFields[i], metaData.getObjectValue(data, selectedFields[i], null, null)); } return map; } @Override public Map fillIndexObjectMap(Map map, int... selectedIndexes) { selectedIndexes = buildSelection(selectedIndexes); for (int i = 0; i < selectedIndexes.length; i++) { map.put(selectedIndexes[i], metaData.getObjectValue(data, selectedIndexes[i], null, null)); } return map; } @Override public > Map fillEnumObjectMap(Map map, T... selectedColumns) { selectedColumns = buildSelection((Class) selectedColumns.getClass().getComponentType(), selectedColumns); for (int i = 0; i < selectedColumns.length; i++) { map.put(selectedColumns[i], metaData.getObjectValue(data, selectedColumns[i], null, null)); } return map; } @Override public BigInteger getBigInteger(String headerName) { return metaData.getObjectValue(data, headerName, BigInteger.class, null); } @Override public BigInteger getBigInteger(Enum column) { return metaData.getObjectValue(data, column, BigInteger.class, null); } @Override public BigInteger getBigInteger(int columnIndex) { return metaData.getObjectValue(data, columnIndex, BigInteger.class, null); } @Override public BigDecimal getBigDecimal(String headerName) { return metaData.getObjectValue(data, headerName, BigDecimal.class, null); } @Override public BigDecimal getBigDecimal(Enum column) { return metaData.getObjectValue(data, column, BigDecimal.class, null); } @Override public BigDecimal getBigDecimal(int columnIndex) { return metaData.getObjectValue(data, columnIndex, BigDecimal.class, null); } @Override public Byte getByte(String headerName) { return metaData.getObjectValue(data, headerName, Byte.class, null); } @Override public Byte getByte(Enum column) { return metaData.getObjectValue(data, column, Byte.class, null); } @Override public Byte getByte(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Byte.class, null); } @Override public Short getShort(String headerName) { return metaData.getObjectValue(data, headerName, Short.class, null); } @Override public Short getShort(Enum column) { return metaData.getObjectValue(data, column, Short.class, null); } @Override public Short getShort(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Short.class, null); } @Override public Integer getInt(String headerName) { return metaData.getObjectValue(data, headerName, Integer.class, null); } @Override public Integer getInt(Enum column) { return metaData.getObjectValue(data, column, Integer.class, null); } @Override public Integer getInt(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Integer.class, null); } @Override public Long getLong(String headerName) { return metaData.getObjectValue(data, headerName, Long.class, null); } @Override public Long getLong(Enum column) { return metaData.getObjectValue(data, column, Long.class, null); } @Override public Long getLong(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Long.class, null); } @Override public Float getFloat(String headerName) { return metaData.getObjectValue(data, headerName, Float.class, null); } @Override public Float getFloat(Enum column) { return metaData.getObjectValue(data, column, Float.class, null); } @Override public Float getFloat(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Float.class, null); } @Override public Double getDouble(String headerName) { return metaData.getObjectValue(data, headerName, Double.class, null); } @Override public Double getDouble(Enum column) { return metaData.getObjectValue(data, column, Double.class, null); } @Override public Double getDouble(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Double.class, null); } @Override public Date getDate(String headerName) { return metaData.getObjectValue(data, headerName, Date.class, null); } @Override public Date getDate(Enum column) { return metaData.getObjectValue(data, column, Date.class, null); } @Override public Date getDate(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Date.class, null); } @Override public Calendar getCalendar(String headerName) { return metaData.getObjectValue(data, headerName, Calendar.class, null); } @Override public Calendar getCalendar(Enum column) { return metaData.getObjectValue(data, column, Calendar.class, null); } @Override public Calendar getCalendar(int columnIndex) { return metaData.getObjectValue(data, columnIndex, Calendar.class, null); } public String toString() { if (data == null) { return "null"; } if (data.length == 0) { return "[]"; } StringBuilder out = new StringBuilder(); for (int i = 0; i < data.length; i++) { if (out.length() != 0) { out.append(',').append(' '); } out.append(data[i]); } return out.toString(); } @Override public boolean equals(Object o) { return o == this; } @Override public int hashCode() { return Arrays.hashCode(data); } @Override public String[] getValues(String... fieldNames) { String[] out = new String[fieldNames.length]; for(int i = 0; i < out.length;i++){ out[i] = getString(fieldNames[i]); } return out; } @Override public String[] getValues(int... fieldIndexes) { String[] out = new String[fieldIndexes.length]; for(int i = 0; i < out.length;i++){ out[i] = getString(fieldIndexes[i]); } return out; } @Override public String[] getValues(Enum ... fields) { String[] out = new String[fields.length]; for(int i = 0; i < out.length;i++){ out[i] = getString(fields[i]); } return out; } } RecordMetaData.java000066400000000000000000000210221475274123300343530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.record; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.conversions.*; /** * Metadata with information about {@link Record}s parsed from the input. */ public interface RecordMetaData { /** * Returns the index of a given column * * @param column the column whose index will be returned * * @return index of the given column */ int indexOf(Enum column); /** * Returns the index of a given column * * @param headerName name of the column whose index will be returned * * @return index of the given column */ int indexOf(String headerName); /** * Returns the type associated with a given column, defined with the method {@code setTypeOfColumns(type, columns)} * * @param column the column whose type will be returned * * @return the type of the given column */ Class typeOf(Enum column); /** * Returns the type associated with a given column name, defined with the method {@code setTypeOfColumns(type, columns)} * * @param headerName name of the column whose type will be returned * * @return the type of the given column */ Class typeOf(String headerName); /** * Returns the type associated with a given column, defined with the method {@code setTypeOfColumns(type, columns)} * * @param columnIndex the position of the column whose type will be returned * * @return the type of the given column */ Class typeOf(int columnIndex); /** * Associates a type with one or more column. This allows the parsed data to be converted automatically * to the given type when reading data from a {@link Record}, e.g. {@link Record#toFieldObjectMap(String...)} will * convert the selected field values to their respective types, and then set the result as the values in the map. * * @param type the type to associate with a list of column * @param columns the columns that will be associated with the given type. */ @SuppressWarnings("rawtypes") void setTypeOfColumns(Class type, Enum... columns); /** * Associates a type with one or more column. This allows the parsed data to be converted automatically * to the given type when reading data from a {@link Record}, e.g. {@link Record#toFieldObjectMap(String...)} will * convert the selected field values to their respective types, and then set the result as the values in the map. * * @param type the type to associate with a list of column * @param headerNames the columns that will be associated with the given type. */ void setTypeOfColumns(Class type, String... headerNames); /** * Associates a type with one or more column. This allows the parsed data to be converted automatically * to the given type when reading data from a {@link Record}, e.g. {@link Record#toFieldObjectMap(String...)} will * convert the selected field values to their respective types, and then set the result as the values in the map. * * @param type the type to associate with a list of column * @param columnIndexes the columns that will be associated with the given type. */ void setTypeOfColumns(Class type, int... columnIndexes); /** * Associates a default value with one or more columns, in case the values contained are {@code null} * * @param defaultValue the value to be used for the given column when the parsed result is {@code null} * @param columns the columns to be associated with a default value. * @param type of the default value. */ void setDefaultValueOfColumns(T defaultValue, Enum... columns); /** * Associates a default value with one or more columns, in case the values contained are {@code null} * * @param defaultValue the value to be used for the given column when the parsed result is {@code null} * @param headerNames the column names to be associated with a default value. * @param type of the default value. */ void setDefaultValueOfColumns(T defaultValue, String... headerNames); /** * Associates a default value with one or more columns, in case the values contained are {@code null} * * @param defaultValue the value to be used for the given column when the parsed result is {@code null} * @param columnIndexes the column indexes to be associated with a default value. * @param type of the default value. */ void setDefaultValueOfColumns(T defaultValue, int... columnIndexes); /** * Returns the default value associated with a column (defined using {@code setDefaultValueOf(Column, Object)}) * * @param column the column whose default value will be returned * * @return the default value associated with the given column or {@code null}. */ Object defaultValueOf(Enum column); /** * Returns the default value associated with a column (defined using {@code setDefaultValueOf(Column, Object)}) * * @param headerName the column name whose default value will be returned * * @return the default value associated with the given column or {@code null}. */ Object defaultValueOf(String headerName); /** * Returns the default value associated with a column (defined using {@code setDefaultValueOf(Column, Object)}) * * @param columnIndex the column index whose default value will be returned * * @return the default value associated with the given column or {@code null}. */ Object defaultValueOf(int columnIndex); /** * Associates a sequence of {@link Conversion}s to fields of a given set of fields * * @param enumType the type of the enumeration whose values represent headers in the input {@code Record}s * @param conversions the sequence of conversions to apply * @param the enumeration type * * @return (modifiable) set of fields to be selected and against which the given conversion sequence will be applied. */ @SuppressWarnings("rawtypes") > FieldSet convertFields(Class enumType, Conversion... conversions); /** * Associates a sequence of {@link Conversion}s to fields of a given set of field names * * @param conversions the sequence of conversions to apply * * @return (modifiable) set of fields names to be selected and against which the given conversion sequence will be applied. */ @SuppressWarnings("rawtypes") FieldSet convertFields(Conversion... conversions); /** * Associates a sequence of {@link Conversion}s to fields of a given set of column indexes * * @param conversions the sequence of conversions to apply * * @return (modifiable) set of column indexes to be selected and against which the given conversion sequence will be applied. */ @SuppressWarnings("rawtypes") FieldSet convertIndexes(Conversion... conversions); /** * Returns the column names of the {@link Record}s parsed from the input. * *

If the headers are extracted from the input (i.e. {@link CommonParserSettings#isHeaderExtractionEnabled()} == true), then these values will be returned. *

If no headers are extracted from the input, then the configured headers in {@link CommonSettings#getHeaders()} will be returned. * * @return the headers associated with the {@link Record}s parsed from the input */ String[] headers(); /** * Returns the sequence of headers that have been selected. If no selection has been made, all available headers * will be returned, producing the same output as a call to method {@link #headers()}. * * @return the sequence of selected headers, or all headers if no selection has been made. */ String[] selectedHeaders(); /** * Queries whether a given header name exists in the {@link Record}s parsed from the input * * @param headerName name of the header * * @return {@code true} if the given header name exists in the input records, otherwise {@code false} */ boolean containsColumn(String headerName); } RecordMetaDataImpl.java000066400000000000000000000352121475274123300352030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/record/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.record; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.conversions.*; import java.lang.annotation.*; import java.util.*; class RecordMetaDataImpl implements RecordMetaData { final C context; @SuppressWarnings("rawtypes") private Map conversionByType = new HashMap(); @SuppressWarnings("rawtypes") private Map> conversionsByAnnotation = new HashMap>(); private Map annotationHashes = new HashMap(); private MetaData[] indexMap; private FieldConversionMapping conversions = null; RecordMetaDataImpl(C context) { this.context = context; } private MetaData getMetaData(String name) { int index = context.indexOf(name); if (index == -1) { getValidatedHeaders(); throw new IllegalArgumentException("Header name '" + name + "' not found. Available columns are: " + Arrays.asList(selectedHeaders())); } return getMetaData(index); } private NormalizedString[] getValidatedHeaders() { NormalizedString[] headers = NormalizedString.toIdentifierGroupArray(context.headers()); if (headers == null || headers.length == 0) { throw new IllegalStateException("No headers parsed from input nor provided in the user settings. Only index-based operations are available."); } return headers; } private MetaData getMetaData(Enum column) { NormalizedString[] headers = NormalizedString.toIdentifierGroupArray(context.headers()); if (headers == null || headers.length == 0) { throw new IllegalStateException("No headers parsed from input nor provided in the user settings. Only index-based operations are available."); } return getMetaData(context.indexOf(column)); } public MetaData getMetaData(int index) { if (indexMap == null || indexMap.length < index + 1 || indexMap[index] == null) { synchronized (this) { if (indexMap == null || indexMap.length < index + 1 || indexMap[index] == null) { int startFrom = 0; int lastIndex = index; if (indexMap != null) { startFrom = indexMap.length; indexMap = Arrays.copyOf(indexMap, index + 1); } else { String[] headers = context.headers(); if (headers != null && lastIndex < headers.length) { lastIndex = headers.length; } int[] indexes = context.extractedFieldIndexes(); if (indexes != null) { for (int i = 0; i < indexes.length; i++) { if (lastIndex < indexes[i]) { lastIndex = indexes[i]; } } } indexMap = new MetaData[lastIndex + 1]; } for (int i = startFrom; i < lastIndex + 1; i++) { indexMap[i] = new MetaData(i); } } } } return indexMap[index]; } @Override public int indexOf(Enum column) { return getMetaData(column).index; } MetaData metadataOf(String headerName) { return getMetaData(headerName); } MetaData metadataOf(Enum column) { return getMetaData(column); } MetaData metadataOf(int columnIndex) { return getMetaData(columnIndex); } @Override public int indexOf(String headerName) { return getMetaData(headerName).index; } @Override public Class typeOf(Enum column) { return getMetaData(column).type; } @Override public Class typeOf(String headerName) { return getMetaData(headerName).type; } @Override public Class typeOf(int columnIndex) { return getMetaData(columnIndex).type; } @Override public void setDefaultValueOfColumns(T defaultValue, Enum... columns) { for (Enum column : columns) { getMetaData(column).defaultValue = defaultValue; } } @Override public void setDefaultValueOfColumns(T defaultValue, String... headerNames) { for (String headerName : headerNames) { getMetaData(headerName).defaultValue = defaultValue; } } @Override public void setDefaultValueOfColumns(T defaultValue, int... columnIndexes) { for (int columnIndex : columnIndexes) { getMetaData(columnIndex).defaultValue = defaultValue; } } @Override public Object defaultValueOf(Enum column) { return getMetaData(column).defaultValue; } @Override public Object defaultValueOf(String headerName) { return getMetaData(headerName).defaultValue; } @Override public Object defaultValueOf(int columnIndex) { return getMetaData(columnIndex).defaultValue; } private FieldConversionMapping getConversions() { if (conversions == null) { conversions = new FieldConversionMapping(); } return conversions; } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public > FieldSet convertFields(Class enumType, Conversion... conversions) { return (FieldSet) getConversions().applyConversionsOnFieldEnums(conversions); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public FieldSet convertFields(Conversion... conversions) { return getConversions().applyConversionsOnFieldNames(conversions); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public FieldSet convertIndexes(Conversion... conversions) { return getConversions().applyConversionsOnFieldIndexes(conversions); } @Override public String[] headers() { return context.headers(); } @Override public String[] selectedHeaders() { return context.selectedHeaders(); } String getValue(String[] data, String headerName) { MetaData md = metadataOf(headerName); if (md.index >= data.length) { return null; } return data[md.index]; } String getValue(String[] data, int columnIndex) { MetaData md = metadataOf(columnIndex); return data[md.index]; } String getValue(String[] data, Enum column) { MetaData md = metadataOf(column); return data[md.index]; } @SuppressWarnings("rawtypes") private T convert(MetaData md, String[] data, Class expectedType, Conversion[] conversions) { return expectedType.cast(convert(md, data, conversions)); } @SuppressWarnings("rawtypes") private Object convert(MetaData md, String[] data, Object defaultValue, Conversion[] conversions) { Object out = convert(md, data, conversions); return out == null ? defaultValue : out; } @SuppressWarnings({"rawtypes", "unchecked"}) private static Object convert(MetaData md, String[] data, Conversion[] conversions) { Object out = data[md.index]; for (int i = 0; i < conversions.length; i++) { out = conversions[i].execute(out); } return out; } @SuppressWarnings({"rawtypes", "unchecked"}) T getValue(String[] data, String headerName, T defaultValue, Conversion[] conversions) { return (T) convert(metadataOf(headerName), data, defaultValue, conversions); } @SuppressWarnings({"rawtypes", "unchecked"}) T getValue(String[] data, int columnIndex, T defaultValue, Conversion[] conversions) { return (T) convert(metadataOf(columnIndex), data, defaultValue, conversions); } @SuppressWarnings({"rawtypes", "unchecked"}) T getValue(String[] data, Enum column, T defaultValue, Conversion[] conversions) { return (T) convert(metadataOf(column), data, defaultValue, conversions); } @SuppressWarnings("rawtypes") T getValue(String[] data, String headerName, Class expectedType, Conversion[] conversions) { return convert(metadataOf(headerName), data, expectedType, conversions); } @SuppressWarnings("rawtypes") T getValue(String[] data, int columnIndex, Class expectedType, Conversion[] conversions) { return convert(metadataOf(columnIndex), data, expectedType, conversions); } @SuppressWarnings("rawtypes") T getValue(String[] data, Enum column, Class expectedType, Conversion[] conversions) { return convert(metadataOf(column), data, expectedType, conversions); } @SuppressWarnings({"rawtypes", "unchecked"}) private T convert(MetaData md, String[] data, Class type, T defaultValue, Annotation annotation) { Object out = md.index < data.length ? data[md.index] : null; if (out == null) { out = defaultValue == null ? md.defaultValue : defaultValue; } if (annotation == null) { initializeMetadataConversions(data, md); out = md.convert(out); if (out == null) { out = defaultValue == null ? md.defaultValue : defaultValue; } } if (type != null) { if (out != null && type.isAssignableFrom(out.getClass())) { return (T) out; } Conversion conversion; if (annotation == null) { conversion = conversionByType.get(type); if (conversion == null) { conversion = AnnotationHelper.getDefaultConversion(type, null, null); conversionByType.put(type, conversion); } } else { Map m = conversionsByAnnotation.get(type); if (m == null) { m = new HashMap(); conversionsByAnnotation.put(type, m); } conversion = m.get(annotation); if (conversion == null) { conversion = AnnotationHelper.getConversion(type, annotation); m.put(annotation, conversion); } } if (conversion == null) { if(type == String.class){ if(out == null){ return null; } return (T) (md.index < data.length ? data[md.index] : null); } String message = ""; if (type == Date.class || type == Calendar.class) { message = ". Need to specify format for date"; } DataProcessingException exception = new DataProcessingException("Cannot convert '{value}' to " + type.getName() + message); exception.setValue(out); exception.setErrorContentLength(context.errorContentLength()); throw exception; } out = conversion.execute(out); } if (type == null) { return (T) out; } try { return type.cast(out); } catch (ClassCastException e) { DataProcessingException exception = new DataProcessingException("Cannot cast value '{value}' of type " + out.getClass().toString() + " to " + type.getName()); exception.setValue(out); exception.setErrorContentLength(context.errorContentLength()); throw exception; } } private void initializeMetadataConversions(String[] data, MetaData md) { if (conversions != null) { synchronized (this) { String[] headers = headers(); if (headers == null) { headers = data; } conversions.prepareExecution(false, headers); md.setDefaultConversions(conversions.getConversions(md.index, md.type)); } } } T getObjectValue(String[] data, String headerName, Class type, T defaultValue) { return convert(metadataOf(headerName), data, type, defaultValue, null); } T getObjectValue(String[] data, int columnIndex, Class type, T defaultValue) { return convert(metadataOf(columnIndex), data, type, defaultValue, null); } T getObjectValue(String[] data, Enum column, Class type, T defaultValue) { return convert(metadataOf(column), data, type, defaultValue, null); } T getObjectValue(String[] data, String headerName, Class type, T defaultValue, String format, String... formatOptions) { if (format == null) { return getObjectValue(data, headerName, type, defaultValue); } return convert(metadataOf(headerName), data, type, defaultValue, buildAnnotation(type, format, formatOptions)); } T getObjectValue(String[] data, int columnIndex, Class type, T defaultValue, String format, String... formatOptions) { if (format == null) { return getObjectValue(data, columnIndex, type, defaultValue); } return convert(metadataOf(columnIndex), data, type, defaultValue, buildAnnotation(type, format, formatOptions)); } T getObjectValue(String[] data, Enum column, Class type, T defaultValue, String format, String... formatOptions) { if (format == null) { return getObjectValue(data, column, type, defaultValue); } return convert(metadataOf(column), data, type, defaultValue, buildAnnotation(type, format, formatOptions)); } static Annotation buildBooleanStringAnnotation(final String[] trueStrings, final String[] falseStrings) { return new com.univocity.parsers.annotations.BooleanString() { @Override public String[] trueStrings() { return trueStrings == null ? ArgumentUtils.EMPTY_STRING_ARRAY : trueStrings; } @Override public String[] falseStrings() { return falseStrings == null ? ArgumentUtils.EMPTY_STRING_ARRAY : falseStrings; } @Override public Class annotationType() { return com.univocity.parsers.annotations.BooleanString.class; } }; } private static Annotation newFormatAnnotation(final String format, final String... formatOptions) { return new com.univocity.parsers.annotations.Format() { @Override public String[] formats() { return new String[]{format}; } @Override public String[] options() { return formatOptions; } @Override public Class annotationType() { return com.univocity.parsers.annotations.Format.class; } }; } Annotation buildAnnotation(Class type, final String args1, final String... args2) { Integer hash = (type.hashCode() * 31) + String.valueOf(args1).hashCode() + (31 * Arrays.toString(args2).hashCode()); Annotation out = annotationHashes.get(hash); if (out == null) { if (type == Boolean.class || type == boolean.class) { out = buildBooleanStringAnnotation(args1 == null ? null : new String[]{args1}, args2); } else { out = newFormatAnnotation(args1, args2); } annotationHashes.put(hash, out); } return out; } @SuppressWarnings("rawtypes") @Override public void setTypeOfColumns(Class type, Enum... columns) { for (int i = 0; i < columns.length; i++) { getMetaData(columns[i]).type = type; } } @Override public void setTypeOfColumns(Class type, String... headerNames) { for (int i = 0; i < headerNames.length; i++) { getMetaData(headerNames[i]).type = type; } } @Override public void setTypeOfColumns(Class type, int... columnIndexes) { for (int i = 0; i < columnIndexes.length; i++) { getMetaData(columnIndexes[i]).type = type; } } @Override public boolean containsColumn(String headerName) { if (headerName == null) { return false; } return context.indexOf(headerName) != -1; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/routine/000077500000000000000000000000001475274123300311625ustar00rootroot00000000000000AbstractRoutines.java000066400000000000000000001114041475274123300352430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/routine/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.routine; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import com.univocity.parsers.common.processor.*; import java.io.*; import java.nio.charset.*; import java.sql.*; import java.util.*; /** * Basic implementation of commonly used routines around parsing/writing of data that can be reused and extended * by parsers/writers of any supported format. * * @param

parser configuration class * @param writer configuration class */ public abstract class AbstractRoutines

, W extends CommonWriterSettings> { private boolean keepResourcesOpen = false; private Writer previousOutput; private ColumnMapping columnMapper = new ColumnMapping(); /** * Creates a new parser implementation using the given parser configuration * * @param parserSettings the configuration for new parser * * @return a parser implementation configured according to the given settings object. */ protected abstract AbstractParser

createParser(P parserSettings); /** * Creates a new writer implementation using the given writer configuration * * @param output target output of the routine. * @param writerSettings the configuration for new writer * * @return a writer implementation configured according to the given settings object. */ protected abstract AbstractWriter createWriter(Writer output, W writerSettings); /** * Creates a default parser settings configuration * * @return a new instance of a usable parser configuration. */ protected abstract P createDefaultParserSettings(); /** * Creates a default writer settings configuration * * @return a new instance of a usable writer configuration. */ protected abstract W createDefaultWriterSettings(); private final String routineDescription; private P parserSettings; private W writerSettings; /** * Creates a new instance of this routine class. * * @param routineDescription description of the routines for a given format */ public AbstractRoutines(String routineDescription) { this(routineDescription, null, null); } /** * Creates a new instance of this routine class. * * @param routineDescription description of the routines for a given format * @param parserSettings configuration to use for parsing */ public AbstractRoutines(String routineDescription, P parserSettings) { this(routineDescription, parserSettings, null); } /** * Creates a new instance of this routine class. * * @param routineDescription description of the routines for a given format * @param writerSettings configuration to use for writing */ public AbstractRoutines(String routineDescription, W writerSettings) { this(routineDescription, null, writerSettings); } /** * Creates a new instance of this routine class. * * @param routineDescription description of the routines for a given format * @param parserSettings configuration to use for parsing * @param writerSettings configuration to use for writing */ public AbstractRoutines(String routineDescription, P parserSettings, W writerSettings) { this.routineDescription = routineDescription; this.parserSettings = parserSettings; this.writerSettings = writerSettings; } private void validateWriterSettings() { if (writerSettings == null) { writerSettings = createDefaultWriterSettings(); } } private void validateParserSettings() { if (parserSettings == null) { parserSettings = createDefaultParserSettings(); parserSettings.setLineSeparatorDetectionEnabled(true); } } /** * Returns the parser configuration (if any) used by the routines of this utility class. * * @return the parser configuration. */ public final P getParserSettings() { validateParserSettings(); return parserSettings; } /** * Defines the parser configuration to be used by the routines of this utility class. * * @param parserSettings the parser configuration. */ public final void setParserSettings(P parserSettings) { this.parserSettings = parserSettings; } /** * Returns the writer configuration (if any) used by the routines of this utility class. * * @return the writer configuration. */ public final W getWriterSettings() { validateWriterSettings(); return writerSettings; } /** * Defines the writer configuration to be used by the routines of this utility class. * * @param writerSettings the parser configuration. */ public final void setWriterSettings(W writerSettings) { this.writerSettings = writerSettings; } /** * Allows writers of any given format to adjust its settings to take into account column headers and lengths * prior to writing data in any routine. * * @param headers headers to be written * @param lengths the corresponding lengths of each header */ protected void adjustColumnLengths(String[] headers, int[] lengths) { } /** * Dumps the content of a {@link java.sql.ResultSet} into a file. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output file that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. */ public final void write(ResultSet rs, File output) { write(rs, output, (Charset) null); } /** * Dumps the content of a {@link java.sql.ResultSet} into a file. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output file that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. * @param encoding the output encoding of the file */ public final void write(ResultSet rs, File output, String encoding) { write(rs, output, Charset.forName(encoding)); } /** * Dumps the content of a {@link java.sql.ResultSet} into a file. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output file that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. * @param encoding the output encoding of the file */ public final void write(ResultSet rs, File output, Charset encoding) { Writer writer = ArgumentUtils.newWriter(output, encoding); try { write(rs, writer); } finally { try { writer.close(); } catch (Exception e) { throw new IllegalStateException("Error closing file: '" + output.getAbsolutePath() + "'", e); } } } /** * Dumps the content of a {@link java.sql.ResultSet} into an output stream. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output stream that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. */ public final void write(ResultSet rs, OutputStream output) { write(rs, ArgumentUtils.newWriter(output)); } /** * Dumps the content of a {@link java.sql.ResultSet} into an output stream. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output file that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. * @param encoding the output encoding of the output stream */ public final void write(ResultSet rs, OutputStream output, String encoding) { write(rs, ArgumentUtils.newWriter(output, encoding)); } /** * Dumps the content of a {@link java.sql.ResultSet} into an output stream. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output file that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. * @param encoding the output encoding of the output stream */ public final void write(ResultSet rs, OutputStream output, Charset encoding) { write(rs, ArgumentUtils.newWriter(output, encoding)); } /** * Dumps the content of a {@link java.sql.ResultSet}. * * @param rs the {@link java.sql.ResultSet} whose contents should be read and written to a given output * @param output the output that will store the data in the given {@link java.sql.ResultSet} * in the format specified by concrete implementations of this class. */ public final void write(ResultSet rs, Writer output) { validateWriterSettings(); boolean hasWriterProcessor = writerSettings.getRowWriterProcessor() != null; AbstractWriter writer = null; long rowCount = 0L; Object[] row = null; try { try { ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); String[] headers = new String[columns]; int[] lengths = new int[columns]; for (int i = 1; i <= columns; i++) { headers[i - 1] = md.getColumnLabel(i); int precision = md.getPrecision(i); int scale = md.getScale(i); int length; if (precision != 0 && scale != 0) { length = precision + scale + 2; //+2 to account for decimal point (non-integer numbers) and minus characters (negative numbers). } else { length = precision + scale; } lengths[i - 1] = length; } String[] userProvidedHeaders = writerSettings.getHeaders(); if (userProvidedHeaders == null) { writerSettings.setHeaders(headers); } else { headers = userProvidedHeaders; } adjustColumnLengths(headers, lengths); writer = createWriter(output, writerSettings); if (writerSettings.isHeaderWritingEnabled()) { writer.writeHeaders(); } row = new Object[columns]; while (rs.next()) { for (int i = 1; i <= columns; i++) { row[i - 1] = rs.getObject(i); } if (hasWriterProcessor) { writer.processRecord(row); } else { writer.writeRow(row); } rowCount++; } } finally { if (!keepResourcesOpen) { rs.close(); } } } catch (Exception e) { throw new TextWritingException("Error writing data from result set", rowCount, row, e); } finally { close(writer); } } /** * Reads all data from a given input and writes it to an output. * * @param input the input data to be parsed using the settings provided in {@link #getParserSettings()} * @param output the output into where the input data should be written, using the format provided in {@link #getWriterSettings()} */ public final void parseAndWrite(Reader input, Writer output) { setRowWriterProcessor(null); setRowProcessor(createWritingRowProcessor(output)); try { AbstractParser

parser = createParser(parserSettings); parser.parse(input); } finally { parserSettings.setRowProcessor(null); } } private void setRowWriterProcessor(RowWriterProcessor rowWriterProcessor) { validateWriterSettings(); writerSettings.setRowWriterProcessor(rowWriterProcessor); } private void setRowProcessor(RowProcessor rowProcessor) { validateParserSettings(); parserSettings.setRowProcessor(rowProcessor); } private RowProcessor createWritingRowProcessor(final Writer output) { return new RowProcessor() { private AbstractWriter writer; @Override public void processStarted(ParsingContext context) { writer = createWriter(output, writerSettings); } @Override public void rowProcessed(String[] row, ParsingContext context) { writer.writeRow(row); } @Override public void processEnded(ParsingContext context) { close(writer); } }; } private void close(AbstractWriter writer) { if (writer != null) { if (!keepResourcesOpen) { writer.close(); } else { writer.flush(); } } } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, File output, String... headers) { writeAll(elements, beanType, ArgumentUtils.newWriter(output), headers); } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param encoding the output encoding to use for writing * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, File output, String encoding, String[] headers) { writeAll(elements, beanType, ArgumentUtils.newWriter(output, encoding), headers); } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param encoding the output encoding to use for writing * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, File output, Charset encoding, String... headers) { writeAll(elements, beanType, ArgumentUtils.newWriter(output, encoding), headers); } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, OutputStream output, String... headers) { writeAll(elements, beanType, ArgumentUtils.newWriter(output), headers); } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param encoding the output encoding to use for writing * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, OutputStream output, String encoding, String[] headers) { writeAll(elements, beanType, ArgumentUtils.newWriter(output, encoding), headers); } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param encoding the output encoding to use for writing * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, OutputStream output, Charset encoding, String... headers) { writeAll(elements, beanType, ArgumentUtils.newWriter(output, encoding), headers); } /** * Writes a collection of annotated java beans to a given output. * * @param elements the elements to write to the output * @param beanType the type of element in the given collection * @param output the output into which the given elements will be written * @param headers headers to use in the first row of the written result. * @param the type of element in the given collection */ public void writeAll(Iterable elements, Class beanType, Writer output, String... headers) { BeanWriterProcessor processor = new BeanWriterProcessor(beanType); processor.setColumnMapper(columnMapper); setRowWriterProcessor(processor); try { if (headers.length > 0) { writerSettings.setHeaders(headers); writerSettings.setHeaderWritingEnabled(true); } if (keepResourcesOpen && previousOutput == output) { writerSettings.setHeaderWritingEnabled(false); } AbstractWriter writer = createWriter(output, writerSettings); if (keepResourcesOpen) { writer.processRecords(elements); previousOutput = output; } else { writer.processRecordsAndClose(elements); } } finally { writerSettings.setRowWriterProcessor(null); } } /** * Parses a file into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public List parseAll(final Class beanType, final File input, int expectedBeanCount) { return parseAll(beanType, ArgumentUtils.newReader(input), expectedBeanCount); } /** * Parses a file into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param encoding encoding of the given file * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public List parseAll(final Class beanType, final File input, String encoding, int expectedBeanCount) { return parseAll(beanType, ArgumentUtils.newReader(input, encoding), expectedBeanCount); } /** * Parses a file into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param encoding encoding of the given file * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final File input, Charset encoding, int expectedBeanCount) { return parseAll(beanType, ArgumentUtils.newReader(input, encoding), expectedBeanCount); } /** * Parses an input stream into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final InputStream input, int expectedBeanCount) { return parseAll(beanType, ArgumentUtils.newReader(input), expectedBeanCount); } /** * Parses an input stream into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param encoding encoding of the given input stream * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final InputStream input, String encoding, int expectedBeanCount) { return parseAll(beanType, ArgumentUtils.newReader(input, encoding), expectedBeanCount); } /** * Parses an input stream into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param encoding encoding of the given input stream * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final InputStream input, Charset encoding, int expectedBeanCount) { return parseAll(beanType, ArgumentUtils.newReader(input, encoding), expectedBeanCount); } /** * Parses the input into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input to be parsed * @param expectedBeanCount expected number of rows to be parsed from the input which will be converted into java beans. * Used to pre-allocate the size of the output {@link List} * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(Class beanType, Reader input, int expectedBeanCount) { BeanListProcessor processor = new BeanListProcessor(beanType, expectedBeanCount); processor.setColumnMapper(columnMapper); setRowProcessor(processor); try { createParser(parserSettings).parse(input); return processor.getBeans(); } finally { parserSettings.setRowProcessor(null); } } /** * Parses a file into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public List parseAll(final Class beanType, final File input) { return parseAll(beanType, input, 0); } /** * Parses a file into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param encoding encoding of the given file * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public List parseAll(final Class beanType, final File input, String encoding) { return parseAll(beanType, input, encoding, 0); } /** * Parses a file into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param encoding encoding of the given file * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final File input, Charset encoding) { return parseAll(beanType, input, encoding, 0); } /** * Parses an input stream into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final InputStream input) { return parseAll(beanType, input, 0); } /** * Parses an input stream into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param encoding encoding of the given input stream * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final InputStream input, String encoding) { return parseAll(beanType, input, encoding, 0); } /** * Parses an input stream into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param encoding encoding of the given input stream * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(final Class beanType, final InputStream input, Charset encoding) { return parseAll(beanType, input, encoding, 0); } /** * Parses the input into a list of annotated java beans * * @param beanType the type of java beans to be instantiated. * @param input the input to be parsed * @param the type of java beans to be instantiated. * * @return a list containing all java beans read from the input. */ public List parseAll(Class beanType, Reader input) { return parseAll(beanType, input, 0); } /** * Iterates over a file to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final File input) { return iterate(beanType, ArgumentUtils.newReader(input)); } /** * Iterates over a file to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param encoding encoding of the given file * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final File input, String encoding) { return iterate(beanType, ArgumentUtils.newReader(input, encoding)); } /** * Iterates over a file to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the file to be parsed * @param encoding encoding of the given file * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final File input, Charset encoding) { return iterate(beanType, ArgumentUtils.newReader(input, encoding)); } /** * Iterates over an input stream to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final InputStream input) { return iterate(beanType, ArgumentUtils.newReader(input)); } /** * Iterates over an input stream to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param encoding encoding of the given input stream * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final InputStream input, String encoding) { return iterate(beanType, ArgumentUtils.newReader(input, encoding)); } /** * Iterates over an input stream to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the input stream to be parsed * @param encoding encoding of the given input stream * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final InputStream input, Charset encoding) { return iterate(beanType, ArgumentUtils.newReader(input, encoding)); } /** * Iterates over an input to produce instances of annotated java beans on demand. * * @param beanType the type of java beans to be instantiated. * @param input the input to be parsed * @param the type of java beans to be instantiated. * * @return an {@link Iterable} that allows iterating over the input and producing instances of java beans on demand. */ public IterableResult iterate(final Class beanType, final Reader input) { final Object[] beanHolder = new Object[1]; BeanProcessor processor = new BeanProcessor(beanType) { @Override public void beanProcessed(T bean, ParsingContext context) { beanHolder[0] = bean; } @Override public void processEnded(ParsingContext context) { super.processEnded(context); parserSettings.setRowProcessor(null); } }; processor.setColumnMapper(columnMapper); setRowProcessor(processor); return new IterableResult() { private ParsingContext context; @Override public ParsingContext getContext() { return context; } @Override public ResultIterator iterator() { final AbstractParser

parser = createParser(parserSettings); parser.beginParsing(input); context = parser.getContext(); return new ResultIterator() { String[] row; @Override public boolean hasNext() { return beanHolder[0] != null || row != null || (row = parser.parseNext()) != null; } @Override public T next() { T out = (T) beanHolder[0]; if (out == null && hasNext()) { out = (T) beanHolder[0]; } beanHolder[0] = null; row = null; return out; } @Override public void remove() { throw new UnsupportedOperationException("Can't remove beans"); } @Override public ParsingContext getContext() { return context; } }; } }; } @Override public String toString() { return routineDescription; } /** * Calculates the dimensions of a file (row and column count). * * @param input the file to be parsed * * @return a {@link InputDimension} with information about the dimensions of the given input. */ public InputDimension getInputDimension(final File input) { return getInputDimension(ArgumentUtils.newReader(input)); } /** * Calculates the dimensions of a file (row and column count). * * @param input the file to be parsed * @param encoding encoding of the given file * * @return a {@link InputDimension} with information about the dimensions of the given input. */ public InputDimension getInputDimension(final File input, String encoding) { return getInputDimension(ArgumentUtils.newReader(input, encoding)); } /** * Calculates the dimensions of a given input (row and column count). * * @param input the input to be parsed * * @return a {@link InputDimension} with information about the dimensions of the given input. */ public InputDimension getInputDimension(final InputStream input) { return getInputDimension(ArgumentUtils.newReader(input)); } /** * Calculates the dimensions of a given input (row and column count). * * @param input the input to be parsed * @param encoding encoding of the given input * * @return a {@link InputDimension} with information about the dimensions of the given input. */ public InputDimension getInputDimension(final InputStream input, String encoding) { return getInputDimension(ArgumentUtils.newReader(input, encoding)); } /** * Calculates the dimensions of a given input (row and column count). * * @param input the input to be parsed * * @return a {@link InputDimension} with information about the dimensions of the given input. */ public InputDimension getInputDimension(Reader input) { final InputDimension out = new InputDimension(); setRowProcessor(new AbstractRowProcessor() { int lastColumn; @Override public void rowProcessed(String[] row, ParsingContext context) { if (lastColumn < row.length) { lastColumn = row.length; } } @Override public void processEnded(ParsingContext context) { out.rows = context.currentRecord() + 1; out.columns = lastColumn; } }); P settings = getParserSettings(); settings.setMaxCharsPerColumn(-1); if (settings.getMaxColumns() < 1000000) { //one million columns should be more than enough. settings.setMaxColumns(1000000); } //The parser will return values for the columns selected. //By selecting no indexes here, no String objects will be created settings.selectIndexes(/*nothing here*/); //By disabling column reordering, we get the original row, with nulls in the columns as nothing was selected. settings.setColumnReorderingEnabled(false); createParser(settings).parse(input); return out; } /** * Returns a flag indicating whether resources used for writing should be kept open after being * used by the routines available from this object, when applicable. * * @return flag indicating whether to call the {@code close()} (or any other cleanup method) * after a routine executes. */ public boolean getKeepResourcesOpen() { return keepResourcesOpen; } /** * Allows preventing resources used for writing from being closed after being * used by the routines available from this object, when applicable. * * @param keepResourcesOpen flag indicating whether to call the {@code close()} (or any other cleanup method) * after a routine executes. */ public void setKeepResourcesOpen(boolean keepResourcesOpen) { this.keepResourcesOpen = keepResourcesOpen; } /** * Returns a mapper that allows users to manually define mappings from * attributes/methods of a given class to columns to be parsed or written * in routines that manipulate java beans. * * This allows users to use instances of classes that are not annotated with {@link Parsed} nor * {@link Nested}. Any mappings defined with the column mapper will take * precedence over these annotations. * * @return the column mapper */ public ColumnMapper getColumnMapper() { return columnMapper; } /** * Copies the given column mappings over to this processor. Further changes * to the given object won't be reflected on the copy stored internally. * * @param columnMapper the column mappings to use */ public void setColumnMapper(ColumnMapper columnMapper) { this.columnMapper = columnMapper == null ? new ColumnMapping() : (ColumnMapping) columnMapper.clone(); } } InputDimension.java000066400000000000000000000030041475274123300347100ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/common/routine/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.routine; import java.io.*; /** * A simple class to hold information about the dimensions of a given input, which are calculated using * {@link AbstractRoutines#getInputDimension(File)} * * @author Univocity Software Pty Ltd - dev@univocity.com */ public final class InputDimension { long rows; int columns; InputDimension() { } /** * Returns the total number of rows the input contains. * * @return the number of rows found in the input. */ public final long rowCount() { return rows; } /** * Returns the maximum number of column the input contains. * * @return the number of columns found in the input. */ public final int columnCount() { return columns; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/000077500000000000000000000000001475274123300305555ustar00rootroot00000000000000BigDecimalConversion.java000066400000000000000000000037771475274123300354050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import java.math.*; /** * Converts Strings to BigDecimals and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class BigDecimalConversion extends ObjectConversion { /** * Creates a Conversion from String to BigDecimal with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public BigDecimalConversion() { super(); } /** * Creates a Conversion from String to BigDecimal with default values to return when the input is null. * @param valueIfStringIsNull default BigDecimal value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a BigDecimal input is null. Used when {@code revert(BigDecimal)} is invoked. */ public BigDecimalConversion(BigDecimal valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to BigDecimal. */ @Override protected BigDecimal fromString(String input) { return new BigDecimal(input); } } BigIntegerConversion.java000066400000000000000000000037771475274123300354440ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import java.math.*; /** * Converts Strings to BigIntegers and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class BigIntegerConversion extends ObjectConversion { /** * Creates a Conversion from String to BigInteger with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public BigIntegerConversion() { super(); } /** * Creates a Conversion from String to BigInteger with default values to return when the input is null. * @param valueIfStringIsNull default BigInteger value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a BigInteger input is null. Used when {@code revert(BigInteger)} is invoked. */ public BigIntegerConversion(BigInteger valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to BigInteger. */ @Override protected BigInteger fromString(String input) { return new BigInteger(input); } } BooleanConversion.java000066400000000000000000000175251475274123300350000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; import java.util.*; /** * Converts Strings to Booleans and vice versa * *

This class supports multiple representations of boolean values. For example, you can define conversions from different Strings such as "Yes, Y, 1" to true, and * "No, N, 0" to false. * *

The reverse conversion from a Boolean to String (in {@link BooleanConversion#revert(Boolean)} will return the first String provided in this class constructor *

Using the previous example, a call to {@code revert(true)} will produce "Yes" and a call {@code revert(false)} will produce "No". * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class BooleanConversion extends ObjectConversion { private String defaultForTrue; private String defaultForFalse; private final Set falseValues = new LinkedHashSet(); private final Set trueValues = new LinkedHashSet(); /** * Creates conversions from String to Boolean. * This default constructor assumes the output of a conversion should be null when input is null *

The list of Strings that identify "true" the list of Strings that identify "false" are mandatory. * * @param valuesForTrue Strings that identify the boolean value true. The first element will be returned when executing {@code revert(true)} * @param valuesForFalse Strings that identify the boolean value false. The first element will be returned when executing {@code #revert(false)} */ public BooleanConversion(String[] valuesForTrue, String[] valuesForFalse) { this(null, null, valuesForTrue, valuesForFalse); } /** * Creates a Conversion from String to Boolean with default values to return when the input is null. *

The list of Strings that identify "true" the list of Strings that identify "false" are mandatory. * * @param valueIfStringIsNull default Boolean value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Boolean input is null. Used when {@link BooleanConversion#revert(Boolean)} is invoked. * @param valuesForTrue Strings that identify the boolean value true. The first element will be returned when executing {@code revert(true)} * @param valuesForFalse Strings that identify the boolean value false. The first element will be returned when executing {@code #revert(false)} */ public BooleanConversion(Boolean valueIfStringIsNull, String valueIfObjectIsNull, String[] valuesForTrue, String[] valuesForFalse) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.notEmpty("Values for true", valuesForTrue); ArgumentUtils.notEmpty("Values for false", valuesForFalse); Collections.addAll(falseValues, valuesForFalse); Collections.addAll(trueValues, valuesForTrue); normalize(falseValues); normalize(trueValues); for (String falseValue : falseValues) { if (trueValues.contains(falseValue)) { throw new DataProcessingException("Ambiguous string representation for both false and true values: '" + falseValue + '\''); } } defaultForTrue = valuesForTrue[0]; defaultForFalse = valuesForFalse[0]; } /** * Converts a Boolean back to a String *

The return value depends on the list of values for true/false provided in the constructor of this class. * * @param input the Boolean to be converted to a String * * @return a String representation for this boolean value, or the value of {@link BooleanConversion#getValueIfObjectIsNull()} if the Boolean input is null. */ @Override public String revert(Boolean input) { if (input != null) { if (Boolean.FALSE.equals(input)) { return defaultForFalse; } if (Boolean.TRUE.equals(input)) { return defaultForTrue; } } return getValueIfObjectIsNull(); } /** * Converts a String to a Boolean * * @param input a String to be converted into a Boolean value. * * @return true if the input String is part of {@link BooleanConversion#trueValues}, false if the input String is part of {@link BooleanConversion#falseValues}, or {@link BooleanConversion#getValueIfStringIsNull()} if the input String is null. */ @Override protected Boolean fromString(String input) { if (input != null) { return getBoolean(input, trueValues, falseValues); } return super.getValueIfStringIsNull(); } /** * Returns the {@code Boolean} value represented by a {@code String}, as defined by sets of Strings that represent {@code true} and {@code false} values. * @param booleanString the value that represents either {@code true} or {@code false} * @param trueValues a set of possible string values that represent {@code true}. If empty, then "true" will be assumed as the only acceptable representation. * @param falseValues a set of possible string values that represent {@code false}. If empty, then "false" will be assumed as the only acceptable representation. * @return the boolean value that the input string represents * @throws DataProcessingException if the input string does not match any value provided in neither set of possible values. */ public static Boolean getBoolean(String booleanString, String[] trueValues, String[] falseValues) { trueValues = trueValues == null || trueValues.length == 0 ? new String[]{"true"} : trueValues; falseValues = falseValues == null || falseValues.length == 0 ? new String[]{"false"} : falseValues; BooleanConversion tmp = new BooleanConversion(trueValues, falseValues); return getBoolean(booleanString, tmp.trueValues, tmp.falseValues); } private static Boolean getBoolean(String defaultString, Set trueValues, Set falseValues) { String normalized = normalize(defaultString); if (falseValues.contains(normalized)) { return Boolean.FALSE; } if (trueValues.contains(normalized)) { return Boolean.TRUE; } DataProcessingException exception = new DataProcessingException("Unable to convert '{value}' to Boolean. Allowed Strings are: " + trueValues + " for true; and " + falseValues + " for false."); exception.setValue(defaultString); throw exception; } /** * Normalizes a given String by trimming whitespaces and converting it to lower case. * * @param string a String to be normalized. * * @return the normalized version of the original String. */ private static String normalize(String string) { if (string == null) { return null; } return string.trim().toLowerCase(); } /** * Normalizes the Strings in a given collection by trimming all elements and converting them to lower case. * * @param strings a String collection with elements to be normalized. The original contents of the collection will be modified. */ private static void normalize(Collection strings) { LinkedHashSet normalized = new LinkedHashSet(strings.size()); for (String string : strings) { if (string == null) { normalized.add(null); } else { normalized.add(string.trim().toLowerCase()); } } strings.clear(); strings.addAll(normalized); } } ByteConversion.java000066400000000000000000000036321475274123300343160ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts Strings to Bytes and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ByteConversion extends ObjectConversion { /** * Creates a Conversion from String to Byte with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public ByteConversion() { super(); } /** * Creates a Conversion from String to Byte with default values to return when the input is null. * @param valueIfStringIsNull default Byte value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Byte input is null. Used when {@code revert(Byte)} is invoked. */ public ByteConversion(Byte valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to Byte. */ @Override protected Byte fromString(String input) { return Byte.valueOf(input); } } CalendarConversion.java000066400000000000000000000170541475274123300351270ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; import java.text.*; import java.util.*; /** * Converts Strings to instances of {@link java.util.Calendar} and vice versa. * *

This class supports multiple date formats. For example, you can define conversions from dates represented by different Strings such as "2001/05/02 and Dec/2013". * *

The reverse conversion from a Calendar to String (in {@link CalendarConversion#revert(Calendar)} will return a formatted String using the date pattern provided in this class constructor *

The date patterns must follows the pattern rules of {@link java.text.SimpleDateFormat} * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see java.text.SimpleDateFormat */ public class CalendarConversion extends ObjectConversion implements FormattedConversion { private final DateConversion dateConversion; /** * Defines a conversion from String to {@link java.util.Calendar} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param timeZone the {@link TimeZone} of the given calendar date * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param valueIfStringIsNull default Calendar value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Calendar input is null. Used when {@link CalendarConversion#revert(Calendar)} is invoked. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. */ public CalendarConversion(TimeZone timeZone, Locale locale, Calendar valueIfStringIsNull, String valueIfObjectIsNull, String... dateFormats) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.noNulls("Date formats", dateFormats); dateConversion = new DateConversion(locale, dateFormats); } /** * Defines a conversion from String to {@link java.util.Calendar} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param valueIfStringIsNull default Calendar value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Calendar input is null. Used when {@link CalendarConversion#revert(Calendar)} is invoked. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. */ public CalendarConversion(Locale locale, Calendar valueIfStringIsNull, String valueIfObjectIsNull, String... dateFormats) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.noNulls("Date formats", dateFormats); dateConversion = new DateConversion(locale, dateFormats); } /** * Defines a conversion from String to {@link java.util.Calendar} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param valueIfStringIsNull default Calendar value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Calendar input is null. Used when {@link CalendarConversion#revert(Calendar)} is invoked. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. */ public CalendarConversion(Calendar valueIfStringIsNull, String valueIfObjectIsNull, String... dateFormats) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.noNulls("Date formats", dateFormats); dateConversion = new DateConversion(Locale.getDefault(), dateFormats); } /** * Defines a conversion from String to {@link java.util.Calendar} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. */ public CalendarConversion(Locale locale, String... dateFormats) { this(locale, null, null, dateFormats); } /** * Defines a conversion from String to {@link java.util.Calendar} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. */ public CalendarConversion(String... dateFormats) { this(Locale.getDefault(), null, null, dateFormats); } /** * Converts Calendar to a formatted date String. *

The pattern used to generate the formatted date is the first date pattern provided in the constructor of this class * * @param input the Calendar to be converted to a String * * @return a formatted date String representing the date provided by the given Calendar, or the value of {@link CalendarConversion#getValueIfObjectIsNull()} if the Calendar parameter is null. */ @Override public String revert(Calendar input) { if (input == null) { return super.revert(null); } return dateConversion.revert(input.getTime()); } /** * Converts a formatted date String to an instance of Calendar. *

The pattern in the formatted date must match one of the date patterns provided in the constructor of this class. * * @param input the String containing a formatted date which must be converted to a Calendar * * @return the Calendar instance containing the date information represented by the given String, or the value of {@link CalendarConversion#getValueIfStringIsNull()} if the String input is null. */ @Override protected Calendar fromString(String input) { Date date = dateConversion.execute(input); Calendar out = Calendar.getInstance(); out.setTime(date); out.setTimeZone(dateConversion.getTimeZone()); return out; } @Override public SimpleDateFormat[] getFormatterObjects() { return dateConversion.getFormatterObjects(); } } CharacterConversion.java000066400000000000000000000044661475274123300353150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; /** * Converts Strings to Characters and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class CharacterConversion extends ObjectConversion { /** * Creates a Conversion from String to Character with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public CharacterConversion() { super(); } /** * Creates a Conversion from String to Character with default values to return when the input is null. * @param valueIfStringIsNull default Character value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Character input is null. Used when {@code revert(Character)} is invoked. */ public CharacterConversion(Character valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to a Character. * @throws IllegalArgumentException if the input String length is not equal to 1, then an IllegalArgumentException is thrown. */ @Override protected Character fromString(String input) { if (input.length() != 1) { DataProcessingException exception = new DataProcessingException("'{value}' is not a character"); exception.setValue(input); throw exception; } return input.charAt(0); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/Conversion.java000066400000000000000000000062131475274123300335470ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.processor.*; /** * The interface that defines the conversion from one type of value to another, and vice versa. * * univocity-parsers provides a set of default conversions for usage with * {@link ObjectRowProcessor} and {@link ObjectRowWriterProcessor}. * * Annotations in package {@link com.univocity.parsers.annotations} are associated with different Conversion * implementations in {@link com.univocity.parsers.conversions}. * * @param The input type to be converted to the output type O * @param The type of outputs produced by a conversion applied to the an input I. * * When used in conjunction with the {@link com.univocity.parsers.annotations.Convert} annotation, * O should be compatible with the type of the annotated field. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.processor.ObjectRowProcessor * @see com.univocity.parsers.common.processor.ObjectRowWriterProcessor */ public interface Conversion { /** * Converts a value of type I to a value of type O. * * When used in conjunction with the {@link com.univocity.parsers.annotations.Convert} annotation, this method will perform * the conversion from a parsed input {@code String} (if no other conversion has been applied before) * to a value of the desired type, and the result will be assigned to the annotated field. Note that conversions can be * chained so you need to make sure the input type of any previous conversion is compatible with I * * @param input the input of type I to be converted to an object of type O * * @return the conversion result. */ O execute(I input); /** * Converts a value of type O to a value of type I. * * When used in conjunction with the {@link com.univocity.parsers.annotations.Convert} annotation, this method will * convert the value of the annotated field so it can be written to the output (usually a {@code String}). Note that conversions can be * chained so you need to make sure the type of any previous conversion is compatible with O * * @param input the input of type O to be converted to an object of type I * * @return the conversion result. */ I revert(O input); } Conversions.java000066400000000000000000001023141475274123300336520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import java.math.*; import java.text.*; import java.util.*; /** * This class provides default instances of common implementations if {@code com.univocity.parsers.conversions.Conversion}, as well as useful methods for obtaining new instances of these. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class Conversions { private Conversions() { } private static final UpperCaseConversion upperCase = new UpperCaseConversion(); private static final LowerCaseConversion lowerCase = new LowerCaseConversion(); private static final TrimConversion trim = new TrimConversion(); private static final ToStringConversion toString = new ToStringConversion(); /** * Returns a singleton instance of {@link ToStringConversion} * * @return a singleton instance of {@link ToStringConversion} */ public static ToStringConversion string() { return toString; } /** * Returns a singleton instance of {@link UpperCaseConversion} * * @return a singleton instance of {@link UpperCaseConversion} */ public static UpperCaseConversion toUpperCase() { return upperCase; } /** * Returns a singleton instance of {@link LowerCaseConversion} * * @return a singleton instance of {@link LowerCaseConversion} */ public static LowerCaseConversion toLowerCase() { return lowerCase; } /** * Returns a singleton instance of {@link TrimConversion} * * @return a singleton instance of {@link TrimConversion} */ public static TrimConversion trim() { return trim; } /** * Returns a {@link TrimConversion} that limits the output to a fixed length * * @param length the maximum length a value can contain. Characters after this limit will * be discarded. * * @return a trim-to-length conversion */ public static TrimConversion trim(int length) { return new TrimConversion(length); } /** * Returns a new instance of {@link RegexConversion} * * @param replaceRegex the regular expression used to match contents of a given input String * @param replacement the replacement content to replace any contents matched by the given regular expression * * @return the new instance of {@link RegexConversion} created with the given parameters. */ public static RegexConversion replace(String replaceRegex, String replacement) { return new RegexConversion(replaceRegex, replacement); } /** * Returns a new instance of {@link NullStringConversion} * * @param nullRepresentations the sequence of Strings that represent a null value. * * @return the new instance of {@link NullStringConversion} created with the given parameters. */ public static NullStringConversion toNull(String... nullRepresentations) { return new NullStringConversion(nullRepresentations); } /** * Returns a new instance of {@link DateConversion} * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(Locale locale, String... dateFormats) { return new DateConversion(locale, dateFormats); } /** * Returns a new instance of {@link DateConversion} * * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(String... dateFormats) { return new DateConversion(Locale.getDefault(), dateFormats); } /** * Returns a new instance of {@link DateConversion} * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateIfNull default Date value to be returned when the input String is null. Used when {@link DateConversion#execute(String)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(Locale locale, Date dateIfNull, String... dateFormats) { return new DateConversion(locale, dateIfNull, null, dateFormats); } /** * Returns a new instance of {@link DateConversion} * * @param dateIfNull default Date value to be returned when the input String is null. Used when {@link DateConversion#execute(String)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(Date dateIfNull, String... dateFormats) { return new DateConversion(Locale.getDefault(), dateIfNull, null, dateFormats); } /** * Returns a new instance of {@link DateConversion} * * @param timeZone the {@link TimeZone} of the date to be formatted * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateIfNull default Date value to be returned when the input String is null. Used when {@link DateConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a Date input is null. Used when {@link DateConversion#revert(Date)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(TimeZone timeZone, Locale locale, Date dateIfNull, String stringIfNull, String... dateFormats) { return new DateConversion(timeZone, locale, dateIfNull, stringIfNull, dateFormats); } /** * Returns a new instance of {@link DateConversion} * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateIfNull default Date value to be returned when the input String is null. Used when {@link DateConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a Date input is null. Used when {@link DateConversion#revert(Date)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(Locale locale, Date dateIfNull, String stringIfNull, String... dateFormats) { return new DateConversion(locale, dateIfNull, stringIfNull, dateFormats); } /** * Returns a new instance of {@link DateConversion} * * @param dateIfNull default Date value to be returned when the input String is null. Used when {@link DateConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a Date input is null. Used when {@link DateConversion#revert(Date)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. * * @return the new instance of {@link DateConversion} created with the given parameters. */ public static DateConversion toDate(Date dateIfNull, String stringIfNull, String... dateFormats) { return new DateConversion(Locale.getDefault(), dateIfNull, stringIfNull, dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(Locale locale, String... dateFormats) { return new CalendarConversion(locale, dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(String... dateFormats) { return new CalendarConversion(Locale.getDefault(), dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateIfNull default Calendar value to be returned when the input String is null. Used when {@link CalendarConversion#execute(String)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(Locale locale, Calendar dateIfNull, String... dateFormats) { return new CalendarConversion(locale, dateIfNull, null, dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param dateIfNull default Calendar value to be returned when the input String is null. Used when {@link CalendarConversion#execute(String)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(Calendar dateIfNull, String... dateFormats) { return new CalendarConversion(Locale.getDefault(), dateIfNull, null, dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateIfNull default Calendar value to be returned when the input String is null. Used when {@link CalendarConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a Date input is null. Used when {@link CalendarConversion#revert(Calendar)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(Locale locale, Calendar dateIfNull, String stringIfNull, String... dateFormats) { return new CalendarConversion(TimeZone.getDefault(), locale, dateIfNull, stringIfNull, dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param timeZone the {@link TimeZone} to be considered * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateIfNull default Calendar value to be returned when the input String is null. Used when {@link CalendarConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a Date input is null. Used when {@link CalendarConversion#revert(Calendar)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(TimeZone timeZone, Locale locale, Calendar dateIfNull, String stringIfNull, String... dateFormats) { return new CalendarConversion(timeZone, locale, dateIfNull, stringIfNull, dateFormats); } /** * Returns a new instance of {@link CalendarConversion} * * @param dateIfNull default Calendar value to be returned when the input String is null. Used when {@link CalendarConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a Date input is null. Used when {@link CalendarConversion#revert(Calendar)} is invoked. * @param dateFormats list of acceptable date patterns. The first pattern in this sequence will be used to convert a Calendar into a String in {@link CalendarConversion#revert(Calendar)}. * * @return the new instance of {@link CalendarConversion} created with the given parameters. */ public static CalendarConversion toCalendar(Calendar dateIfNull, String stringIfNull, String... dateFormats) { return new CalendarConversion(Locale.getDefault(), dateIfNull, stringIfNull, dateFormats); } /** * Returns a new instance of {@link ByteConversion} * * @return a new instance of {@link ByteConversion} */ public static ByteConversion toByte() { return new ByteConversion(); } /** * Returns a new instance of {@link ShortConversion} * * @return a new instance of {@link ShortConversion} */ public static ShortConversion toShort() { return new ShortConversion(); } /** * Returns a new instance of {@link IntegerConversion} * * @return a new instance of {@link IntegerConversion} */ public static IntegerConversion toInteger() { return new IntegerConversion(); } /** * Returns a new instance of {@link LongConversion} * * @return a new instance of {@link LongConversion} */ public static LongConversion toLong() { return new LongConversion(); } /** * Returns a new instance of {@link BigIntegerConversion} * * @return a new instance of {@link BigIntegerConversion} */ public static BigIntegerConversion toBigInteger() { return new BigIntegerConversion(); } /** * Returns a new instance of {@link FloatConversion} * * @return a new instance of {@link FloatConversion} */ public static FloatConversion toFloat() { return new FloatConversion(); } /** * Returns a new instance of {@link DoubleConversion} * * @return a new instance of {@link DoubleConversion} */ public static DoubleConversion toDouble() { return new DoubleConversion(); } /** * Returns a new instance of {@link BigDecimalConversion} * * @return a new instance of {@link BigDecimalConversion} */ public static BigDecimalConversion toBigDecimal() { return new BigDecimalConversion(); } /** * Returns a new instance of {@link NumericConversion} * * @param numberFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. * * @return a new instance of {@link NumericConversion} that supports the given number formats */ public static NumericConversion formatToNumber(String... numberFormats) { return new NumericConversion(numberFormats) { @Override protected void configureFormatter(DecimalFormat formatter) { } }; } /** * Returns a new instance of {@link NumericConversion} * * @param numberType type of number to be returned. The resulting instance of {@code Number} will be cast to the expected type. * @param numberFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. * @param type of number * * @return a new instance of {@link NumericConversion} that supports the given number formats */ public static NumericConversion formatToNumber(Class numberType, String... numberFormats) { return new NumericConversion(numberFormats) { @Override protected void configureFormatter(DecimalFormat formatter) { } }; } /** * Returns a new instance of {@link FormattedBigDecimalConversion} * * @param numberFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a BigDecimal into a String in {@link NumericConversion#revert(Number)}. * * @return a new instance of {@link FormattedBigDecimalConversion} that supports the given number formats */ public static FormattedBigDecimalConversion formatToBigDecimal(String... numberFormats) { return new FormattedBigDecimalConversion(numberFormats); } /** * Returns a new instance of {@link FormattedBigDecimalConversion} * * @param defaultValueForNullString default BigDecimal to be returned when the input String is null. Used when {@link FormattedBigDecimalConversion#execute(String)} is invoked. * @param numberFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a BigDecimal into a String in {@link NumericConversion#revert(Number)}. * * @return a new instance of {@link FormattedBigDecimalConversion} that supports the given number formats */ public static FormattedBigDecimalConversion formatToBigDecimal(BigDecimal defaultValueForNullString, String... numberFormats) { return new FormattedBigDecimalConversion(defaultValueForNullString, null, numberFormats); } /** * Returns a new instance of {@link FormattedBigDecimalConversion} * * @param defaultValueForNullString default BigDecimal to be returned when the input String is null. Used when {@link FormattedBigDecimalConversion#execute(String)} is invoked. * @param stringIfNull default String value to be returned when a BigDecimal input is null. Used when {@code FormattedBigDecimalConversion#revert(BigDecimal)} is invoked. * @param numberFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a BigDecimal into a String in {@link NumericConversion#revert(Number)}. * * @return a new instance of {@link FormattedBigDecimalConversion} that supports the given number formats */ public static FormattedBigDecimalConversion formatToBigDecimal(BigDecimal defaultValueForNullString, String stringIfNull, String... numberFormats) { return new FormattedBigDecimalConversion(defaultValueForNullString, stringIfNull, numberFormats); } /** * Returns a new instance of {@link BooleanConversion} * * @param defaultValueForNullString default Boolean value to be returned when the input String is null. Used when {@link BooleanConversion#execute(String)} is invoked. * @param defaultValueForNullBoolean default String value to be returned when a Boolean input is null. Used when {@link BooleanConversion#revert(Boolean)} is invoked. * @param valuesForTrue Strings that identify the boolean value true. The first element will be returned when executing {@code BooleanConversion.revert(true)} * @param valuesForFalse Strings that identify the boolean value false. The first element will be returned when executing {@code BooleanConversion.revert(false)} * * @return a new instance of {@link BooleanConversion} with support for multiple representations of true and false */ public static BooleanConversion toBoolean(Boolean defaultValueForNullString, String defaultValueForNullBoolean, String[] valuesForTrue, String[] valuesForFalse) { return new BooleanConversion(defaultValueForNullString, defaultValueForNullBoolean, valuesForTrue, valuesForFalse); } /** * Returns a new instance of {@link BooleanConversion} * * @param defaultValueForNullString default Boolean value to be returned when the input String is null. Used when {@link BooleanConversion#execute(String)} is invoked. * @param defaultValueForNullBoolean default String value to be returned when a Boolean input is null. Used when {@link BooleanConversion#revert(Boolean)} is invoked. * @param valueForTrue String that identify the boolean value true. * @param valueForFalse String that identify the boolean value false. * * @return a new instance of {@link BooleanConversion} with support for multiple representations of true and false */ public static BooleanConversion toBoolean(Boolean defaultValueForNullString, String defaultValueForNullBoolean, String valueForTrue, String valueForFalse) { return new BooleanConversion(defaultValueForNullString, defaultValueForNullBoolean, new String[]{valueForTrue}, new String[]{valueForFalse}); } /** * Returns a new instance of {@link BooleanConversion} * * @param valuesForTrue Strings that identify the boolean value true. The first element will be returned when executing {@code BooleanConversion.revert(true)} * @param valuesForFalse Strings that identify the boolean value false. The first element will be returned when executing {@code BooleanConversion.revert(false)} * * @return a new instance of {@link BooleanConversion} with support for multiple representations of true and false */ public static BooleanConversion toBoolean(String[] valuesForTrue, String[] valuesForFalse) { return new BooleanConversion(valuesForTrue, valuesForFalse); } /** * Returns a new instance of {@link BooleanConversion} that converts the string "true" to true, and the String "false" to false. * * @return a new instance of {@link BooleanConversion} with support for multiple representations of true and false */ public static BooleanConversion toBoolean() { return toBoolean("true", "false"); } /** * Returns a new instance of {@link BooleanConversion} * * @param valueForTrue String that identifies the boolean value true. * @param valueForFalse String that identifies the boolean value false. * * @return a new instance of {@link BooleanConversion} with support for multiple representations of true and false */ public static BooleanConversion toBoolean(String valueForTrue, String valueForFalse) { return new BooleanConversion(new String[]{valueForTrue}, new String[]{valueForFalse}); } /** * Returns a new instance of {@link CharacterConversion} * * @return a new instance of {@link CharacterConversion} */ public static CharacterConversion toChar() { return new CharacterConversion(); } /** * Returns a new instance of {@link CharacterConversion} * * @param defaultValueForNullString default Character value to be returned when the input String is null. Used when {@link CharacterConversion#execute(String)} is invoked. * @param defaultValueForNullChar default String value to be returned when a Character input is null. Used when {@code CharacterConversion#revert(Character)} is invoked. * * @return a new instance of {@link CharacterConversion} */ public static CharacterConversion toChar(Character defaultValueForNullString, String defaultValueForNullChar) { return new CharacterConversion(defaultValueForNullString, defaultValueForNullChar); } /** * Returns a new instance of {@link CharacterConversion} * * @param defaultValueForNullString default Character value to be returned when the input String is null. Used when {@link CharacterConversion#execute(String)} is invoked. * * @return a new instance of {@link CharacterConversion} */ public static CharacterConversion toChar(Character defaultValueForNullString) { return new CharacterConversion(defaultValueForNullString, null); } /** * Returns a new instance of {@link EnumConversion} * * @param the {@code enum} type * @param enumType the enumeration type to be converted from/to {@code String} * * @return new instance of {@link EnumConversion} */ public static > EnumConversion toEnum(Class enumType) { return new EnumConversion(enumType); } /** * Returns a new instance of {@link EnumConversion} * * @param the {@code enum} type * @param enumType the enumeration type to be converted from/to {@code String} * @param selectors the selection elements of the enumeration to use for matching {@code String}s. * * @return new instance of {@link EnumConversion} */ public static > EnumConversion toEnum(Class enumType, EnumSelector... selectors) { return toEnum(enumType, null, null, null, selectors); } /** * Returns a new instance of {@link EnumConversion} * * @param the {@code enum} type * @param enumType the enumeration type to be converted from/to {@code String} * @param customEnumElement name of custom element of the enumeration (attribute or method) whose values should be used to match equivalent {@code String}s. * @param selectors the selection elements of the enumeration to use for matching {@code String}s. * * @return new instance of {@link EnumConversion} */ public static > EnumConversion toEnum(Class enumType, String customEnumElement, EnumSelector... selectors) { return toEnum(enumType, null, null, customEnumElement); } /** * Returns a new instance of {@link EnumConversion} * * @param the {@code enum} type * @param enumType the enumeration type to be converted from/to {@code String} * @param valueIfStringIsNull the default enumeration constant to use if the input {@code String} is {@code null} * @param valueIfEnumIsNull the default {@code String} value to use if the input {@code enum} constant is {@code null} * @param customEnumElement name of custom element of the enumeration (attribute or method) whose values should be used to match equivalent {@code String}s. * @param selectors the selection elements of the enumeration to use for matching {@code String}s. * * @return new instance of {@link EnumConversion} */ public static > EnumConversion toEnum(Class enumType, T valueIfStringIsNull, String valueIfEnumIsNull, String customEnumElement, EnumSelector... selectors) { return new EnumConversion(enumType, valueIfStringIsNull, valueIfEnumIsNull, customEnumElement, selectors); } /** * Returns a new instance of {@link FormattedDateConversion} * * @param pattern Date mask to be be used to convert a date object (i.e. {@link Date} or {@link Calendar}) into a String. * * @return new instance of {@link FormattedDateConversion} configured with the given parameters */ public static FormattedDateConversion toFormattedDate(String pattern) { return toFormattedDate(pattern, null, null); } /** * Returns a new instance of {@link FormattedDateConversion} * * @param pattern Date mask to be be used to convert a date object (i.e. {@link Date} or {@link Calendar}) into a String. * @param valueIfObjectIsNull Default string value to be returned when the input object is null. * * @return new instance of {@link FormattedDateConversion} configured with the given parameters */ public static FormattedDateConversion toFormattedDate(String pattern, String valueIfObjectIsNull) { return toFormattedDate(pattern, null, valueIfObjectIsNull); } /** * Returns a new instance of {@link FormattedDateConversion} * * @param pattern Date mask to be be used to convert a date object (i.e. {@link Date} or {@link Calendar}) into a String. * @param locale The {@link Locale} that determines how the date pattern should be formatted. * * @return new instance of {@link FormattedDateConversion} configured with the given parameters */ public static FormattedDateConversion toFormattedDate(String pattern, Locale locale) { return toFormattedDate(pattern, locale, null); } /** * Returns a new instance of {@link FormattedDateConversion} * * @param pattern Date mask to be be used to convert a date object (i.e. {@link Date} or {@link Calendar}) into a String. * @param locale The {@link Locale} that determines how the date pattern should be formatted. * @param valueIfObjectIsNull Default string value to be returned when the input object is null. * * @return new instance of {@link FormattedDateConversion} configured with the given parameters */ public static FormattedDateConversion toFormattedDate(String pattern, Locale locale, String valueIfObjectIsNull) { return new FormattedDateConversion(pattern, locale, valueIfObjectIsNull); } /** * Returns a {@link ValidatedConversion} that doesn't allow null values * @return a not-null validator */ public static ValidatedConversion notNull() { return validate(false, true, null, null); } /** * Returns a {@link ValidatedConversion} that doesn't allow null or blank values * @return a not-blank validator */ public static ValidatedConversion notBlank() { return validate(false, false, null, null); } /** * Returns a {@link ValidatedConversion} that verifies the format of a given value * * @param regexToMatch regular expression to match and ensure the value has a given format * * @return a value format validator */ public static ValidatedConversion notBlank(String regexToMatch) { return validate(false, false, null, null, regexToMatch); } /** * Returns a {@link ValidatedConversion} that checks for nulls or blank values. * * @param nullable flag to indicate whether values can be null * @param allowBlanks flag to indicate whether values can be blank * * @return new instance of {@link ValidatedConversion} configured with the given parameters */ public static ValidatedConversion validate(boolean nullable, boolean allowBlanks) { return new ValidatedConversion(nullable, allowBlanks, null, null, null); } /** * Returns a new instance of {@link ValidatedConversion} to validate values of a record * * @param nullable flag to indicate whether values can be null * @param allowBlanks flag to indicate whether values can be blank * @param oneOf list of accepted values. * @param noneOf list of unacceptable values * * @return new instance of {@link ValidatedConversion} configured with the given parameters */ public static ValidatedConversion validate(boolean nullable, boolean allowBlanks, String[] oneOf, String[] noneOf) { return new ValidatedConversion(nullable, allowBlanks, oneOf, noneOf, null); } /** * Returns a {@link ValidatedConversion} that checks for nulls or blank values. * * @param nullable flag to indicate whether values can be null * @param allowBlanks flag to indicate whether values can be blank * @param regexToMatch regular expression to match and ensure the value has a given format * * @return new instance of {@link ValidatedConversion} configured with the given parameters */ public static ValidatedConversion validate(boolean nullable, boolean allowBlanks, String regexToMatch) { return new ValidatedConversion(nullable, allowBlanks, null, null, regexToMatch); } /** * Returns a new instance of {@link ValidatedConversion} to validate values of a record * * @param nullable flag to indicate whether values can be null * @param allowBlanks flag to indicate whether values can be blank * @param oneOf list of accepted values. * @param noneOf list of unacceptable values * @param regexToMatch regular expression to match and ensure the value has a given format * * @return new instance of {@link ValidatedConversion} configured with the given parameters */ public static ValidatedConversion validate(boolean nullable, boolean allowBlanks, String[] oneOf, String[] noneOf, String regexToMatch) { return new ValidatedConversion(nullable, allowBlanks, oneOf, noneOf, regexToMatch); } /** * Returns a new instance of {@link ValidatedConversion} to validate values of a record * * Nulls and blanks are not be allowed by default. * * @param oneOf list of accepted values. * * @return new instance of {@link ValidatedConversion} configured with the given parameters */ public static ValidatedConversion oneOf(String... oneOf) { return new ValidatedConversion(false, false, oneOf, null, null); } /** * Returns a new instance of {@link ValidatedConversion} to validate values of a record * * Nulls and blanks are not be allowed by default. * * @param noneOf list of values that are not allowed. * * @return new instance of {@link ValidatedConversion} configured with the given parameters */ public static ValidatedConversion noneOf(String... noneOf) { return new ValidatedConversion(false, false, null, noneOf, null); } } DateConversion.java000066400000000000000000000175351475274123300342770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; import java.text.*; import java.util.*; /** * Converts Strings to instances of {@link java.util.Date} and vice versa. * *

This class supports multiple date formats. For example, you can define conversions from dates represented by different Strings such as "2001/05/02 and Dec/2013". * *

The reverse conversion from a Date to String (in {@link DateConversion#revert(Date)} will return a formatted String using the date pattern provided in this class constructor *

The date patterns must follows the pattern rules of {@link java.text.SimpleDateFormat} * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see java.text.SimpleDateFormat */ public class DateConversion extends ObjectConversion implements FormattedConversion { private final Locale locale; private final TimeZone timeZone; private final SimpleDateFormat[] parsers; private final String[] formats; /** * Defines a conversion from String to {@link java.util.Date} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param timeZone the {@link TimeZone} of the date to be formatted * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param valueIfStringIsNull default Date value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Date input is null. Used when {@link DateConversion#revert(Date)} is invoked. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. */ public DateConversion(TimeZone timeZone, Locale locale, Date valueIfStringIsNull, String valueIfObjectIsNull, String... dateFormats) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.noNulls("Date formats", dateFormats); this.timeZone = timeZone == null ? TimeZone.getDefault() : timeZone; this.locale = locale == null ? Locale.getDefault() : locale; this.formats = dateFormats.clone(); this.parsers = new SimpleDateFormat[dateFormats.length]; for (int i = 0; i < dateFormats.length; i++) { String dateFormat = dateFormats[i]; parsers[i] = new SimpleDateFormat(dateFormat, this.locale); parsers[i].setTimeZone(this.timeZone); } } /** * Defines a conversion from String to {@link java.util.Date} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param valueIfStringIsNull default Date value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Date input is null. Used when {@link DateConversion#revert(Date)} is invoked. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. */ public DateConversion(Locale locale, Date valueIfStringIsNull, String valueIfObjectIsNull, String... dateFormats) { this(TimeZone.getDefault(), locale, valueIfStringIsNull, valueIfObjectIsNull, dateFormats); } /** * Defines a conversion from String to {@link java.util.Date} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param valueIfStringIsNull default Date value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Date input is null. Used when {@link DateConversion#revert(Date)} is invoked. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. */ public DateConversion(Date valueIfStringIsNull, String valueIfObjectIsNull, String... dateFormats) { this(Locale.getDefault(), valueIfStringIsNull, valueIfObjectIsNull, dateFormats); } /** * Defines a conversion from String to {@link java.util.Date} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. */ public DateConversion(Locale locale, String... dateFormats) { this(locale, null, null, dateFormats); } /** * Defines a conversion from String to {@link java.util.Date} using a sequence of acceptable date patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param dateFormats list of acceptable date patterns The first pattern in this sequence will be used to convert a Date into a String in {@link DateConversion#revert(Date)}. */ public DateConversion(String... dateFormats) { this(Locale.getDefault(), null, null, dateFormats); } /** * Converts Date to a formatted date String. *

The pattern used to generate the formatted date is the first date pattern provided in the constructor of this class * * @param input the Date to be converted to a String * * @return a formatted date String representing the date provided by the given Date, or the value of {@code valueIfObjectIsNull} if the Date parameter is null. */ @Override public String revert(Date input) { if (input == null) { return super.revert(null); } return parsers[0].format(input); } /** * Converts a formatted date String to an instance of Date. *

The pattern in the formatted date must match one of the date patterns provided in the constructor of this class. * * @param input the String containing a formatted date which must be converted to a Date * * @return the Date instance containing the date information represented by the given String, or the value of {@code valueIfObjectIsNull} if the String input is null. */ @Override protected Date fromString(String input) { for (SimpleDateFormat formatter : parsers) { try { synchronized (formatter) { return formatter.parse(input); } } catch (ParseException ex) { //ignore and continue } } DataProcessingException exception = new DataProcessingException("Cannot parse '{value}' as a valid date of locale '" + locale + "'. Supported formats are: " + Arrays.toString(formats)); exception.setValue(input); throw exception; } @Override public SimpleDateFormat[] getFormatterObjects() { return parsers; } public TimeZone getTimeZone(){ return timeZone; } } DoubleConversion.java000066400000000000000000000036661475274123300346340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts Strings to Doubles and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class DoubleConversion extends ObjectConversion { /** * Creates a Conversion from String to Double with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public DoubleConversion() { super(); } /** * Creates a Conversion from String to Double with default values to return when the input is null. * @param valueIfStringIsNull default Double value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Double input is null. Used when {@code revert(Double)} is invoked. */ public DoubleConversion(Double valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to Double. */ @Override protected Double fromString(String input) { return Double.valueOf(input); } } EnumConversion.java000066400000000000000000000261601475274123300343200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; import java.lang.reflect.*; import java.util.*; /** * Converts Strings to enumeration constants and vice versa. * *

This class supports multiple types of identification of enumeration constants. For example, you can match the literal ({@link Enum#name()} the ordinal ({@link Enum#ordinal()} or * the result of a method defined in your enumeration. * *

The reverse conversion from an enumeration to String (in {@link EnumConversion#revert(Enum)} will return a String using the first {@link EnumSelector} provided in the constructor of this class. * * @param the enumeration type whose constants will be converted from/to {@code String} * @see ObjectConversion * @see EnumSelector * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class EnumConversion> extends ObjectConversion { private final Class enumType; private final Field customEnumField; private final Method customEnumMethod; private final EnumSelector[] selectors; private final Map[] conversions; /** * Defines a conversion for an enumeration type that will attempt to match Strings against * the results of the output produced by ({@link Enum#name()}, ({@link Enum#ordinal()} and ({@link Enum#toString()} * of each constant of the given enumeration (@link {@link Class#getEnumConstants()}). * * @param enumType the enumeration type to be converted from/to {@code String} */ public EnumConversion(Class enumType) { this(enumType, EnumSelector.NAME, EnumSelector.ORDINAL, EnumSelector.STRING); } /** * Defines a conversion for an enumeration type that will attempt to match Strings the list of {@link EnumSelector}s, in the specified order. * Each {@link EnumSelector} identifies which element of each constant of the enumeration class (@link {@link Class#getEnumConstants()} * should be used to match equivalent {@code String}s. * * @param enumType the enumeration type to be converted from/to {@code String} * @param selectors the selection elements of the enumeration to use for matching {@code String}s. */ public EnumConversion(Class enumType, EnumSelector... selectors) { this(enumType, null, null, null, selectors); } /** * Defines a conversion for an enumeration type that will attempt to match Strings the list of {@link EnumSelector}s, in the specified order. * Each {@link EnumSelector} identifies which element of each constant of the enumeration class (@link {@link Class#getEnumConstants()} * should be used to match equivalent {@code String}s. * * @param enumType the enumeration type to be converted from/to {@code String} * @param customEnumElement name of custom element of the enumeration (attribute or method) whose values should be used to match equivalent {@code String}s. * @param selectors the selection elements of the enumeration to use for matching {@code String}s. */ public EnumConversion(Class enumType, String customEnumElement, EnumSelector... selectors) { this(enumType, null, null, customEnumElement); } /** * Defines a conversion for an enumeration type that will attempt to match Strings the list of {@link EnumSelector}s, in the specified order. * Each {@link EnumSelector} identifies which element of each constant of the enumeration class (@link {@link Class#getEnumConstants()} * should be used to match equivalent {@code String}s. * * @param enumType the enumeration type to be converted from/to {@code String} * @param valueIfStringIsNull the default enumeration constant to use if the input {@code String} is {@code null} * @param valueIfEnumIsNull the default {@code String} value to use if the input {@code enum} constant is {@code null} * @param customEnumElement name of custom element of the enumeration (attribute or method) whose values should be used to match equivalent {@code String}s. * @param selectors the selection elements of the enumeration to use for matching {@code String}s. */ @SuppressWarnings("unchecked") public EnumConversion(Class enumType, T valueIfStringIsNull, String valueIfEnumIsNull, String customEnumElement, EnumSelector... selectors) { super(valueIfStringIsNull, valueIfEnumIsNull); this.enumType = enumType; if (customEnumElement != null) { customEnumElement = customEnumElement.trim(); if (customEnumElement.isEmpty()) { customEnumElement = null; } } LinkedHashSet selectorSet = new LinkedHashSet(); Collections.addAll(selectorSet, selectors); if ((selectorSet.contains(EnumSelector.CUSTOM_FIELD) || selectorSet.contains(EnumSelector.CUSTOM_METHOD)) && customEnumElement == null) { throw new IllegalArgumentException("Cannot create custom enum conversion without a field name to use"); } Field field = null; Method method = null; if (customEnumElement != null) { IllegalStateException fieldError = null; IllegalStateException methodError = null; try { field = enumType.getDeclaredField(customEnumElement); if (!field.isAccessible()) { field.setAccessible(true); } } catch (Throwable e) { fieldError = new IllegalStateException("Unable to access custom field '" + customEnumElement + "' in enumeration type " + enumType.getName(), e); } if (field == null) { try { try { method = enumType.getDeclaredMethod(customEnumElement); } catch (NoSuchMethodException e) { method = enumType.getDeclaredMethod(customEnumElement, String.class); if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException("Custom method '" + customEnumElement + "' in enumeration type " + enumType.getName() + " must be static"); } if(method.getReturnType() != enumType){ throw new IllegalArgumentException("Custom method '" + customEnumElement + "' in enumeration type " + enumType.getName() + " must return " + enumType.getName()); } } if (!method.isAccessible()) { method.setAccessible(true); } } catch (Throwable e) { methodError = new IllegalStateException("Unable to access custom method '" + customEnumElement + "' in enumeration type " + enumType.getName(), e); } if (method != null) { if (method.getReturnType() == void.class) { throw new IllegalArgumentException("Custom method '" + customEnumElement + "' in enumeration type " + enumType.getName() + " must return a value"); } if (!selectorSet.contains(EnumSelector.CUSTOM_METHOD)) { selectorSet.add(EnumSelector.CUSTOM_METHOD); } } } else if (!selectorSet.contains(EnumSelector.CUSTOM_FIELD)) { selectorSet.add(EnumSelector.CUSTOM_FIELD); } if (selectorSet.contains(EnumSelector.CUSTOM_FIELD) && fieldError != null) { throw fieldError; } if (selectorSet.contains(EnumSelector.CUSTOM_METHOD) && methodError != null) { throw methodError; } if (field == null && method == null) { throw new IllegalStateException("No method/field named '" + customEnumElement + "' found in enumeration type " + enumType.getName()); } } if (selectorSet.contains(EnumSelector.CUSTOM_FIELD) && selectorSet.contains(EnumSelector.CUSTOM_METHOD)) { throw new IllegalArgumentException("Cannot create custom enum conversion using both method and field values"); } if (selectorSet.isEmpty()) { throw new IllegalArgumentException("Selection of enum conversion types cannot be empty."); } this.customEnumField = field; this.customEnumMethod = method; this.selectors = selectorSet.toArray(new EnumSelector[selectorSet.size()]); this.conversions = new Map[selectorSet.size()]; initializeMappings(selectorSet); } private void initializeMappings(Set conversionTypes) { T[] constants = enumType.getEnumConstants(); int i = 0; for (EnumSelector conversionType : conversionTypes) { Map map = new HashMap(constants.length); conversions[i++] = map; for (T constant : constants) { String key = getKey(constant, conversionType); if (key != null) { if (map.containsKey(key)) { throw new IllegalArgumentException("Enumeration element type " + conversionType + " does not uniquely identify elements of " + enumType.getName() + ". Got duplicate value '" + key + "' from constants '" + constant + "' and '" + map.get(key) + "'."); } map.put(key, constant); } } } } private String getKey(T constant, EnumSelector conversionType) { switch (conversionType) { case NAME: return constant.name(); case ORDINAL: return String.valueOf(constant.ordinal()); case STRING: return constant.toString(); case CUSTOM_FIELD: try { return String.valueOf(customEnumField.get(constant)); } catch (Throwable e) { throw new IllegalStateException("Error reading custom field '" + customEnumField.getName() + "' from enumeration constant '" + constant + "' of type " + enumType.getName(), e); } case CUSTOM_METHOD: try { if (customEnumMethod.getParameterTypes().length == 0) { return String.valueOf(customEnumMethod.invoke(constant)); } else { return null; } } catch (Throwable e) { throw new IllegalStateException("Error reading custom method '" + customEnumMethod.getName() + "' from enumeration constant '" + constant + "' of type " + enumType.getName(), e); } default: throw new IllegalStateException("Unsupported enumeration selector type " + conversionType); } } @Override public String revert(T input) { if (input == null) { return super.revert(null); } return getKey(input, selectors[0]); } @Override protected T fromString(String input) { for (Map conversion : conversions) { T value = conversion.get(input); if (value != null) { return value; } } DataProcessingException exception = null; if (customEnumMethod != null && customEnumMethod.getParameterTypes().length == 1) { try { T out = (T) customEnumMethod.invoke(null, input); return out; } catch (Exception e) { exception = new DataProcessingException("Cannot convert '{value}' to enumeration of type " + enumType.getName() + " using method " + customEnumMethod.getName(), e); } } if (exception == null) { exception = new DataProcessingException("Cannot convert '{value}' to enumeration of type " + enumType.getName()); } exception.setValue(input); exception.markAsNonFatal(); throw exception; } } EnumSelector.java000066400000000000000000000030751475274123300337530ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.annotations.EnumOptions; /** * Identifies a property of an enumeration that should be used by {@link EnumOptions} to identify an input value. * When parsing a given input, values will be compared against one of the properties and if there's a match, the * corresponding enumeration value will be used to set the field of an annotated class. */ public enum EnumSelector { /** * Matches the result of {@link Enum#ordinal()} */ ORDINAL, /** * Matches the result of {@link Enum#name()} */ NAME, /** * Matches the result of {@link Enum#toString()} ()} */ STRING, /** * Matches the value of a field of the annotated enumeration */ CUSTOM_FIELD, /** * Matches the value of a method of the annotated enumeration */ CUSTOM_METHOD } FloatConversion.java000066400000000000000000000036471475274123300344660ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts Strings to Floats and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class FloatConversion extends ObjectConversion { /** * Creates a Conversion from String to Float with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public FloatConversion() { super(); } /** * Creates a Conversion from String to Float with default values to return when the input is null. * @param valueIfStringIsNull default Float value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Float input is null. Used when {@code revert(Float)} is invoked. */ public FloatConversion(Float valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to Float. */ @Override protected Float fromString(String input) { return Float.valueOf(input); } } FormattedBigDecimalConversion.java000066400000000000000000000114621475274123300372410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import java.math.*; import java.text.*; /** * Converts formatted Strings to instances of {@link java.math.BigDecimal} and vice versa. * *

This class supports multiple numeric formats. For example, you can define conversions from numbers represented by different Strings such as "1,000,000.00 and $5.00". *

The reverse conversion from a BigDecimal to String (in {@code revert(BigDecimal)} will return a formatted String using the pattern provided in this class constructor *

The numeric patterns must follow the pattern rules of {@link java.text.DecimalFormat} * * @see java.text.DecimalFormat * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class FormattedBigDecimalConversion extends NumericConversion { /** * Defines a conversion from String to {@link java.math.BigDecimal} using a sequence of acceptable numeric patterns. * This constructor assumes the output of a conversion should be null when input is null * @param valueIfStringIsNull default BigDecimal to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a BigDecimal input is null. Used when {@code revert(BigDecimal)} is invoked. * @param numericFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a BigDecimal into a String in {@code revert(BigDecimal)}. */ public FormattedBigDecimalConversion(BigDecimal valueIfStringIsNull, String valueIfObjectIsNull, String... numericFormats) { super(valueIfStringIsNull, valueIfObjectIsNull, numericFormats); } /** * Defines a conversion from String to {@link java.math.BigDecimal} using a sequence of acceptable numeric patterns. The patterns * must be added to this conversion class through the {@link #addFormat(String, String...)} method. * * @param valueIfStringIsNull default BigDecimal to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a BigDecimal input is null. Used when {@link NumericConversion#revert(Number)} is invoked. */ public FormattedBigDecimalConversion(BigDecimal valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Defines a conversion from String to {@link java.math.BigDecimal} using a sequence of acceptable numeric patterns. * This constructor assumes the output of a conversion should be null when input is null * @param numericFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a BigDecimal into a String in {@link NumericConversion#revert(Number)}. */ public FormattedBigDecimalConversion(String... numericFormats) { super(null, null, numericFormats); } /** * Defines a conversion from String to{@link java.math.BigDecimal} using a sequence of acceptable numeric patterns. * This constructor assumes the output of a conversion should be null when input is null * @param numericFormatters list formatters of acceptable numeric patterns. The first formatter in this sequence will be used to convert a BigDecimal into a String in {@link NumericConversion#revert(Number)}. */ public FormattedBigDecimalConversion(DecimalFormat... numericFormatters) { super(numericFormatters); } /** * Defines a conversion from String to {@link java.math.BigDecimal} using a sequence of acceptable numeric patterns. The patterns * must be added to this conversion class through the {@link #addFormat(String, String...)} method. * * This constructor assumes the output of a conversion should be null when input is null * */ public FormattedBigDecimalConversion() { super(); } /** * Configures the Decimal format instance created by the parent class to parse BigDecimals. */ @Override protected void configureFormatter(DecimalFormat formatter) { formatter.setParseBigDecimal(true); } } FormattedConversion.java000066400000000000000000000030631475274123300353360ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.annotations.*; /** * This interface identifies conversions associated with the {@link Format} annotation. * It is used when {@link Format#options()} is defined to set any give properties of the underlying formatter. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @param The type of the formatter object (typically {@link java.text.DecimalFormat} for numeric values, and {@link java.text.SimpleDateFormat} for dates) * */ public interface FormattedConversion { /** * Returns the formatter objects * @return the formatter objects used to apply formatting to values to generate formatted Strings, and parsing formatted Strings into values */ T[] getFormatterObjects(); } FormattedDateConversion.java000066400000000000000000000054661475274123300361450ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; import java.text.*; import java.util.*; /** * Converts objects of different date types ({@code java.util.Date} and {@code java.util.Calendar}) to a formatted * date {@code String}. * *

The reverse conversion is not supported. * *

The date patterns must follow the pattern rules of {@link SimpleDateFormat} * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see SimpleDateFormat */ public class FormattedDateConversion implements Conversion { private final SimpleDateFormat dateFormat; private final String valueIfObjectIsNull; /** * * @param format The pattern to be used to convert an input date into a String in {@link FormattedDateConversion#execute(Object)}. * @param locale the {@link Locale} that determines how the date mask should be formatted. * @param valueIfObjectIsNull default String value to be returned when an input is {@code null} . Used when {@link FormattedDateConversion#execute(Object)} is invoked with a {@code null} parameter. */ public FormattedDateConversion(String format, Locale locale, String valueIfObjectIsNull) { this.valueIfObjectIsNull = valueIfObjectIsNull; locale = locale == null ? Locale.getDefault() : locale; this.dateFormat = new SimpleDateFormat(format, locale); } @Override public String execute(Object input) { if (input == null) { return valueIfObjectIsNull; } Date date = null; if (input instanceof Date) { date = ((Date) input); } else if (input instanceof Calendar) { date = ((Calendar) input).getTime(); } if (date != null) { return dateFormat.format(date); } DataProcessingException exception = new DataProcessingException("Cannot format '{value}' to a date. Not an instance of java.util.Date or java.util.Calendar"); exception.setValue(input); throw exception; } /** * Unsupported operation. * * @param input the input be converted. * * @return throws a {@code UnsupportedOperationException} */ @Override public Object revert(String input) { throw new UnsupportedOperationException("Can't convert an input string into date type"); } } IntegerConversion.java000066400000000000000000000037031475274123300350070ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts Strings to Integers and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class IntegerConversion extends ObjectConversion { /** * Creates a Conversion from String to Integer with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public IntegerConversion() { super(); } /** * Creates a Conversion from String to Integer with default values to return when the input is null. * @param valueIfStringIsNull default Integer value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Integer input is null. Used when {@code revert(Integer)} is invoked. */ public IntegerConversion(Integer valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to Integer. */ @Override protected Integer fromString(String input) { return Integer.valueOf(input); } } LongConversion.java000066400000000000000000000036311475274123300343110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts Strings to Longs and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class LongConversion extends ObjectConversion { /** * Creates a Conversion from String to Long with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public LongConversion() { super(); } /** * Creates a Conversion from String to Long with default values to return when the input is null. * @param valueIfStringIsNull default Long value to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Long input is null. Used when {@code revert(Long)} is invoked. */ public LongConversion(Long valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to Long. */ @Override protected Long fromString(String input) { return Long.valueOf(input); } } LowerCaseConversion.java000066400000000000000000000037471475274123300353060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts an input String to its lower case representation * * The {@link LowerCaseConversion#revert(String)} implements the same behavior of {@link LowerCaseConversion#execute(String)}. Null inputs produce null outputs. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class LowerCaseConversion implements Conversion { /** * Applies the toLowerCase operation in the input and returns the result. * Equivalent to {@link LowerCaseConversion#revert(String)} * @param input the String to be converted to lower case * @return the lower case representation of the given input, or null if the input is null. */ @Override public String execute(String input) { if (input == null) { return null; } return input.toLowerCase(); } /** * Applies the toLowerCase operation in the input and returns the result. * Equivalent to {@link LowerCaseConversion#execute(String)} * @param input the String to be converted to lower case * @return the lower case representation of the given input, or null if the input is null. */ @Override public String revert(String input) { return execute(input); } } NullConversion.java000066400000000000000000000121241475274123300343210ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Default implementation for conversions from input Objects of type I to output Objects of type O * *

Extending classes must implement a proper String to T conversion in {@link ObjectConversion#fromString(String)} *

This abstract class provides default results for conversions when the input is null. * * @author Univocity Software Pty Ltd - parsers@univocity.com * * @param The object type resulting from conversions of values of type O. * @param The object type resulting from conversions of values of type I. */ public abstract class NullConversion implements Conversion { private O valueOnNullInput; private I valueOnNullOutput; /** * Creates a Conversion from an object to another object of a different type, with default values to return when the input is null. * The default constructor assumes the output of a conversion should be null when input is null */ public NullConversion() { this(null, null); } /** * Creates a Conversion from an object to another object of a different type, with default values to return when the input is null. * * @param valueOnNullInput default value of type O to be returned when the input object I is null. Used when {@link NullConversion#execute(Object)} is invoked. * @param valueOnNullOutput default value of type I to be returned when an input of type I is null. Used when {@link NullConversion#revert(Object)} is invoked. */ public NullConversion(O valueOnNullInput, I valueOnNullOutput) { this.valueOnNullInput = valueOnNullInput; this.valueOnNullOutput = valueOnNullOutput; } /** * Converts the given instance of type I to an instance of O * * @param input the input value of type I to be converted to an object of type O * * @return the conversion result, or the value of {@link NullConversion#valueOnNullInput} if the input object is null. */ @Override public O execute(I input) { if (input == null) { return valueOnNullInput; } return fromInput(input); } /** * Creates an instance of O from a I object * * @param input The object of type I to be converted to O * * @return an instance of O, converted from the I input. */ protected abstract O fromInput(I input); /** * Converts a value of type O back to a value of type I * * @param input the input of type O to be converted to an output I * * @return the conversion result, or the value of {@link NullConversion#valueOnNullOutput} if the input object is null. */ @Override public I revert(O input) { if (input == null) { return valueOnNullOutput; } return undo(input); } /** * Converts a value of type O back to I. * @param input the input object to be converted to I * @return the conversion result */ protected abstract I undo(O input); /** * returns a default value of type O to be returned when the input of type I is null. Used when {@link NullConversion#execute(Object)} is invoked. * * @return the default value of type O used when converting from a null I */ public O getValueOnNullInput() { return valueOnNullInput; } /** * returns default instance of I to be returned when an input of type O is null. Used when {@link NullConversion#revert(Object)} is invoked. * * @return the default I instance used when converting from a null O */ public I getValueOnNullOutput() { return valueOnNullOutput; } /** * defines the default value of type O which should be returned when {@link NullConversion#execute(Object)} is invoked with a null I.. * * @param valueOnNullInput the default value of type T when converting from a null input */ public void setValueOnNullInput(O valueOnNullInput) { this.valueOnNullInput = valueOnNullInput; } /** * defines the default value of type I which should be returned when {@link NullConversion#revert(Object)} is invoked with a null O. * * @param valueOnNullOutput a default value of type I when converting from a null input */ public void setValueOnNullOutput(I valueOnNullOutput) { this.valueOnNullOutput = valueOnNullOutput; } } NullStringConversion.java000066400000000000000000000063151475274123300355150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.common.*; import java.util.*; /** * Converts Strings to null and vice versa * *

This class supports multiple representations of null values. For example, you can define conversions from different Strings such as "N/A, ?, -" to null. * *

The reverse conversion from a null to String (in {@link NullStringConversion#revert(Object)} will return the first String provided in this class constructor if the object is null. *

Using the previous example, a call to {@link NullStringConversion#revert(Object)} will produce "N/A". * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class NullStringConversion implements Conversion { private final Set nullStrings = new HashSet(); private final String defaultNullString; /** * Creates conversions from Strings to null. *

The list of Strings that identify nulls are mandatory. * @param nullRepresentations Strings that identify a true value. The first element will be returned when executing {@link NullStringConversion#revert(Object)} */ public NullStringConversion(String... nullRepresentations) { ArgumentUtils.noNulls("Null representation strings", nullRepresentations); Collections.addAll(nullStrings, nullRepresentations); this.defaultNullString = nullRepresentations[0]; } /** * Converts an Object to null. The string representation of the object will be used to match the string elements provided in the constructor. * @param input an Object to be converted to null. * @return null if the string representation of the object matches any one of the Strings provided in the constructor of this class. Otherwise, the original object will be returned. */ @Override public Object execute(Object input) { if (input == null) { return null; } if (nullStrings.contains(String.valueOf(input))) { return null; } return input; } /** * Converts a null input to a String representation. The String returned will be the first element provided in the constructor of this class. * @param input an Object that, if null, will be transformed to a String. * @return If the input is null, the string representation for null objects. Otherwise, the original object will be returned. */ @Override public Object revert(Object input) { if (input == null) { return defaultNullString; } else { return input; } } } NumericConversion.java000066400000000000000000000265661475274123300350300ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import java.math.BigDecimal; import java.math.BigInteger; import java.text.*; import java.util.*; /** * Converts Strings to instances of {@link java.lang.Number} and vice versa. * *

This class supports multiple Number formats. For example, you can define conversions from Numbers represented by different Strings such as "1,000,000.00 and $5.00". *

Extending classes must implement the {@link NumericConversion#configureFormatter(DecimalFormat)} method to provide specific configuration to the DecimalFormat instance. *

The reverse conversion from a Number to String (in {@link NumericConversion#revert(Number)} will return a formatted String using the pattern provided in this class constructor *

The numeric patterns must follows the pattern rules of {@link java.text.DecimalFormat} * * @param The type of numbers supported by this conversion class. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see java.text.DecimalFormat */ public abstract class NumericConversion extends ObjectConversion implements FormattedConversion { private DecimalFormat[] formatters = new DecimalFormat[0]; private String[] formats = new String[0]; private final ParsePosition position = new ParsePosition(0); private Class numberType = Number.class; /** * Defines a conversion from String to {@link java.lang.Number} using a sequence of acceptable numeric patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param valueIfStringIsNull default Number to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Number input is null. Used when {@link NumericConversion#revert(Number)} is invoked. * @param numericFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. */ public NumericConversion(T valueIfStringIsNull, String valueIfObjectIsNull, String... numericFormats) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.noNulls("Numeric formats", numericFormats); this.formats = numericFormats.clone(); this.formatters = new DecimalFormat[numericFormats.length]; for (int i = 0; i < numericFormats.length; i++) { String numericFormat = numericFormats[i]; formatters[i] = new DecimalFormat(numericFormat); configureFormatter(formatters[i]); } } /** * Defines a conversion from String to {@link java.lang.Number} using a sequence of acceptable numeric patterns. * * @param valueIfStringIsNull default Number to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Number input is null. Used when {@link NumericConversion#revert(Number)} is invoked. * @param numericFormatters list formatters of acceptable numeric patterns. The first formatter in this sequence will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. */ public NumericConversion(T valueIfStringIsNull, String valueIfObjectIsNull, DecimalFormat... numericFormatters) { super(valueIfStringIsNull, valueIfObjectIsNull); ArgumentUtils.noNulls("Numeric formatters", numericFormatters); this.formatters = numericFormatters.clone(); this.formats = new String[numericFormatters.length]; for (int i = 0; i < numericFormatters.length; i++) { formats[i] = numericFormatters[i].toPattern(); } } /** * Defines a conversion from String to {@link java.lang.Number} using a sequence of acceptable numeric patterns. The patterns * must be added to this conversion class through the {@link #addFormat(String, String...)} method. * * @param valueIfStringIsNull default Number to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Number input is null. Used when {@link NumericConversion#revert(Number)} is invoked. */ public NumericConversion(T valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Defines a conversion from String to {@link java.lang.Number} using a sequence of acceptable numeric patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param numericFormats list of acceptable numeric patterns. The first pattern in this sequence will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. */ public NumericConversion(String... numericFormats) { this(null, null, numericFormats); } /** * Defines a conversion from String to {@link java.lang.Number} using a sequence of acceptable numeric patterns. * This constructor assumes the output of a conversion should be null when input is null * * @param numericFormatters list formatters of acceptable numeric patterns. The first formatter in this sequence will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. */ public NumericConversion(DecimalFormat... numericFormatters) { this(null, null, numericFormatters); } /** * Defines a conversion from String to {@link java.lang.Number} using a sequence of acceptable numeric patterns. The patterns * must be added to this conversion class through the {@link #addFormat(String, String...)} method. * * This constructor assumes the output of a conversion should be null when input is null */ public NumericConversion() { super(); } /** * Returns the implementation of {@code Number} that should be used when converting numeric data. * * @return the implementation of {@code Number} that should be used when converting numeric data. */ public Class getNumberType() { return this.numberType; } /** * Defines a specific implementation of {@code Number} that should be used when converting numeric data. * * @param numberType the implementation of {@code Number} that should be used when converting numeric data. */ public void setNumberType(Class numberType) { this.numberType = numberType; } @Override public DecimalFormat[] getFormatterObjects() { return formatters; } /** * Method called by the constructor of this class to apply custom configurations to each formatter instantiated with the numeric formats provided. * * @param formatter a DecimalFormat instance initialized with one of the patterns provided in the constructor of this class. */ protected abstract void configureFormatter(DecimalFormat formatter); /** * Converts a formatted numeric String to an instance of Number. *

The pattern in the formatted input must match one of the numeric patterns provided in the constructor of this class. * * @param input the String containing a formatted number which must be converted to a number * * @return the Number instance containing the value represented by the given String, or the value of {@link ObjectConversion#getValueIfStringIsNull()} if the String input is null. */ @SuppressWarnings("unchecked") @Override protected T fromString(String input) { for (int i = 0; i < formatters.length; i++) { position.setIndex(0); T out = (T) formatters[i].parse(input, position); if (formatters.length == 1 || position.getIndex() == input.length()) { if (out == null || numberType == Number.class) { return out; } else if (numberType == Double.class) { return (T) Double.valueOf(out.doubleValue()); } else if (numberType == Float.class) { return (T) Float.valueOf(out.floatValue()); } else if (numberType == BigDecimal.class) { if (out instanceof BigDecimal) { return out; } return (T) new BigDecimal(String.valueOf(out)); } else if (numberType == BigInteger.class) { if (out instanceof BigInteger) { return out; } return (T) BigInteger.valueOf(out.longValue()); } else if (numberType == Long.class) { return (T) Long.valueOf(out.longValue()); } else if (numberType == Integer.class) { return (T) Integer.valueOf(out.intValue()); } else if (numberType == Short.class) { return (T) Short.valueOf(out.shortValue()); } else if (numberType == Byte.class) { return (T) Byte.valueOf(out.byteValue()); } return out; } } DataProcessingException exception = new DataProcessingException("Cannot parse '{value}' as a valid number. Supported formats are: " + Arrays.toString(formats)); exception.setValue(input); throw exception; } /** * Converts Number to a formatted numeric String. *

The pattern used to generate the formatted number is the first numeric pattern provided in the constructor of this class * * @param input the Number to be converted to a String * * @return a formatted numeric String representing the value provided by the given Number, or the value of {@link ObjectConversion#getValueIfObjectIsNull()} if the Number parameter is null. */ @Override public String revert(T input) { if (input == null) { return super.revert(null); } for (DecimalFormat formatter : formatters) { try { return formatter.format(input); } catch (Throwable ex) { //ignore and continue } } DataProcessingException exception = new DataProcessingException("Cannot format '{value}'. No valid formatters were defined."); exception.setValue(input); throw exception; } /** * Adds a new numeric pattern to be used to parse input Strings and convert them to numbers. * * @param format a numeric pattern. The first pattern added to this class will be used to convert a Number into a String in {@link NumericConversion#revert(Number)}. * @param formatOptions a sequence of properties and their values, used to configure the underlying formatter. Each element must be specified as {@code property_name=property_value}, * e.g. options={"decimalSeparator=,", "maximumFractionDigits=3"} */ public void addFormat(String format, String... formatOptions) { DecimalFormat formatter = new DecimalFormat(format); configureFormatter(formatter); AnnotationHelper.applyFormatSettings(formatter, formatOptions); this.formats = Arrays.copyOf(formats, formats.length + 1); this.formatters = Arrays.copyOf(formatters, formatters.length + 1); formats[formats.length - 1] = format; formatters[formatters.length - 1] = formatter; } } ObjectConversion.java000066400000000000000000000122231475274123300346150ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Default implementation for conversions from an input String to Objects of a given type T * *

Extending classes must implement a proper String to T conversion in {@link ObjectConversion#fromString(String)} *

This abstract class provides default results for conversions when the input is null. *

It also provides a default implementation of {@link ObjectConversion#revert(Object)} that returns the result of input.toString() * * @param The object type resulting from conversions of String values. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public abstract class ObjectConversion extends NullConversion { /** * Creates a Conversion from String to an Object with default values to return when the input is null. * The default constructor assumes the output of a conversion should be null when input is null */ public ObjectConversion() { super(null, null); } /** * Creates a Conversion from String to an Object with default values to return when the input is null. * * @param valueIfStringIsNull default value of type T to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when an input of type T is null. Used when {@link ObjectConversion#revert(Object)} is invoked. */ public ObjectConversion(T valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts the given String to an instance of T * * @param input the input String to be converted to an object of type T * * @return the conversion result, or the value of {@link ObjectConversion#getValueIfStringIsNull()} if the input String is null. */ @Override public T execute(String input) { return super.execute(input); } /** * Creates an instance of T from a String representation. * * @param input The String to be converted to T * * @return an instance of T, converted from the String input. */ protected final T fromInput(String input) { return fromString(input); } /** * Creates an instance of T from a String representation. * * @param input The String to be converted to T * * @return an instance of T, converted from the String input. */ protected abstract T fromString(String input); /** * Converts a value of type T back to a String *

This is a general implementation that simply returns the result of input.toString() * * @param input the input of type T to be converted to a String * * @return the conversion result, or the value of {@link ObjectConversion#getValueIfObjectIsNull()} if the input object is null. */ @Override public String revert(T input) { return super.revert(input); } @Override protected final String undo(T input) { return String.valueOf(input); } /** * returns a default value of type T to be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * * @return the default value of type T used when converting from a null input */ public T getValueIfStringIsNull() { return getValueOnNullInput(); } /** * returns default String value to be returned when an input of type T is null. Used when {@link ObjectConversion#revert(Object)} is invoked. * * @return the default String value used when converting from a null input */ public String getValueIfObjectIsNull() { return getValueOnNullOutput(); } /** * defines a default value of type T which should be returned when the input String is null. Used when {@link ObjectConversion#execute(String)} is invoked. * * @param valueIfStringIsNull the default value of type T when converting from a null input */ public void setValueIfStringIsNull(T valueIfStringIsNull) { setValueOnNullInput(valueIfStringIsNull); } /** * returns default value of type T which should be returned when the input String is null. Used when {@link ObjectConversion#revert(Object)} is invoked. * * @param valueIfObjectIsNull a default value of type T when converting from a null input */ public void setValueIfObjectIsNull(String valueIfObjectIsNull) { setValueOnNullOutput(valueIfObjectIsNull); } } RegexConversion.java000066400000000000000000000054011475274123300344610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Replaces contents of a given input String, identified by a regular expression, with a replacement String. * * The {@link RegexConversion#revert(String)} implements the same behavior of {@link RegexConversion#execute(String)}. Null inputs produce null outputs. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class RegexConversion implements Conversion { private final String replaceRegex; private final String replacement; /** * Creates a conversion that matches contents identified by the given regular expression and replaces them by the given replacement String. * @param replaceRegex the regular expression used to match contents of a given input String * @param replacement the replacement content to replace any contents matched by the given regular expression */ public RegexConversion(String replaceRegex, String replacement) { this.replaceRegex = replaceRegex; this.replacement = replacement; } /** * Executes the regular expression provided in the constructor of this class against the input and replaces any matched content with the replacement String. * Equivalent to {@link RegexConversion#revert(String)} * @param input The input to have contents matched by the regular expression and replaced * @return The String resulting from the content replacement */ @Override public String execute(String input) { if (input == null) { return null; } return input.replaceAll(replaceRegex, replacement); } /** * Executes the regular expression provided in the constructor of this class against the input and replaces any matched content with the replacement String. * Equivalent to {@link RegexConversion#execute(String)} * @param input The input to have contents matched by the regular expression and replaced * @return The String resulting from the content replacement */ @Override public String revert(String input) { return execute(input); } } ShortConversion.java000066400000000000000000000036461475274123300345170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts Strings to Shorts and vice versa * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class ShortConversion extends ObjectConversion { /** * Creates a Conversion from String to Short with default values to return when the input is null. * This default constructor assumes the output of a conversion should be null when input is null */ public ShortConversion() { super(); } /** * Creates a Conversion from String to Short with default values to return when the input is null. * @param valueIfStringIsNull default Short value to be returned when the input String is null. Used when {@link ShortConversion#execute(String)} is invoked. * @param valueIfObjectIsNull default String value to be returned when a Short input is null. Used when {@code revert(Short)} is invoked. */ public ShortConversion(Short valueIfStringIsNull, String valueIfObjectIsNull) { super(valueIfStringIsNull, valueIfObjectIsNull); } /** * Converts a String to Short. */ @Override protected Short fromString(String input) { return Short.valueOf(input); } } ToStringConversion.java000066400000000000000000000022451475274123300351630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.conversions; /** * Converts any non-null object to its String representation. */ public class ToStringConversion extends NullConversion { public ToStringConversion() { } public ToStringConversion(Object valueOnNullInput, Object valueOnNullOutput) { super(valueOnNullInput, valueOnNullOutput); } @Override protected Object fromInput(Object input) { if (input != null) { return input.toString(); } return null; } @Override protected Object undo(Object input) { return execute(input); } } TrimConversion.java000066400000000000000000000062001475274123300343200ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Removes leading and trailing white spaces from an input String * * The {@link TrimConversion#revert(String)} implements the same behavior of {@link TrimConversion#execute(String)}. Null inputs produce null outputs. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class TrimConversion implements Conversion { private final int length; /** * Creates a trim conversion that removes leading and trailing whitespaces of any input String. */ public TrimConversion() { this.length = -1; } /** * Creates a trim-to-length conversion that limits the length of any resulting String. Input Strings are trimmed, and * if the resulting String has more characters than the given limit, any characters over the given limit will be discarded. * * @param length the maximum number of characters of any String returned by this conversion. */ public TrimConversion(int length) { if (length < 0) { throw new IllegalArgumentException("Maximum trim length must be positive"); } this.length = length; } /** * Removes leading and trailing white spaces from the input and returns the result. * Equivalent to {@link TrimConversion#revert(String)} * * @param input the String to be trimmed * * @return the input String without leading and trailing white spaces, or null if the input is null. */ @Override public String execute(String input) { if (input == null) { return null; } if (input.length() == 0) { return input; } if (length != -1) { int begin = 0; while (begin < input.length() && input.charAt(begin) <= ' ') { begin++; } if (begin == input.length()) { return ""; } int end = begin + (length < input.length() ? length : input.length()) - 1; if (end >= input.length()) { end = input.length() - 1; } while (input.charAt(end) <= ' ') { end--; } return input.substring(begin, end + 1); } return input.trim(); } /** * Removes leading and trailing white spaces from the input and returns the result. * Equivalent to {@link TrimConversion#execute(String)} * * @param input the String to be trimmed * * @return the input String without leading and trailing white spaces, or null if the input is null. */ @Override public String revert(String input) { return execute(input); } } UpperCaseConversion.java000066400000000000000000000037471475274123300353110ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Converts an input String to its upper case representation * * The {@link UpperCaseConversion#revert(String)} implements the same behavior of {@link UpperCaseConversion#execute(String)}. Null inputs produce null outputs. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class UpperCaseConversion implements Conversion { /** * Applies the toUpperCase operation in the input and returns the result. * Equivalent to {@link UpperCaseConversion#revert(String)} * @param input the String to be converted to upper case * @return the upper case representation of the given input, or null if the input is null. */ @Override public String execute(String input) { if (input == null) { return null; } return input.toUpperCase(); } /** * Applies the toUpperCase operation in the input and returns the result. * Equivalent to {@link UpperCaseConversion#execute(String)} * @param input the String to be converted to upper case * @return the upper case representation of the given input, or null if the input is null. */ @Override public String revert(String input) { return execute(input); } } ValidatedConversion.java000066400000000000000000000111211475274123300353000ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/* * Copyright (c) 2018. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.conversions; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import java.util.*; import java.util.regex.*; /** * Performs one or more validations against the values of a given record. */ public class ValidatedConversion implements Conversion { private final String regexToMatch; private final boolean nullable; private final boolean allowBlanks; private final Set oneOf; private final Set noneOf; private final Matcher matcher; private final Validator[] validators; public ValidatedConversion() { this(false, false, null, null, null); } public ValidatedConversion(String regexToMatch) { this(false, false, null, null, regexToMatch); } public ValidatedConversion(boolean nullable, boolean allowBlanks) { this(nullable, allowBlanks, null, null, null); } public ValidatedConversion(boolean nullable, boolean allowBlanks, String[] oneOf, String[] noneOf, String regexToMatch) { this(nullable, allowBlanks, oneOf, noneOf, regexToMatch, null); } public ValidatedConversion(boolean nullable, boolean allowBlanks, String[] oneOf, String[] noneOf, String regexToMatch, Class[] validators) { this.regexToMatch = regexToMatch; this.matcher = regexToMatch == null || regexToMatch.isEmpty() ? null : Pattern.compile(regexToMatch).matcher(""); this.nullable = nullable; this.allowBlanks = allowBlanks; this.oneOf = oneOf == null || oneOf.length == 0 ? null : new HashSet(Arrays.asList(oneOf)); this.noneOf = noneOf == null || noneOf.length == 0 ? null : new HashSet(Arrays.asList(noneOf)); this.validators = validators == null || validators.length == 0 ? new Validator[0] : instantiateValidators(validators); } private Validator[] instantiateValidators(Class[] validators) { Validator[] out = new Validator[validators.length]; for (int i = 0; i < validators.length; i++) { out[i] = (Validator) AnnotationHelper.newInstance(Validator.class, validators[i], ArgumentUtils.EMPTY_STRING_ARRAY); } return out; } @Override public Object execute(Object input) { validate(input); return input; } @Override public Object revert(Object input) { validate(input); return input; } protected void validate(Object value) { DataValidationException e = null; String str = null; if (value == null) { if (nullable) { if (noneOf != null && noneOf.contains(null)) { e = new DataValidationException("Value '{value}' is not allowed."); } else { return; } } else { if (oneOf != null && oneOf.contains(null)) { return; } else { e = new DataValidationException("Null values not allowed."); } } } else { str = String.valueOf(value); if (str.trim().isEmpty()) { if (allowBlanks) { if (noneOf != null && noneOf.contains(str)) { e = new DataValidationException("Value '{value}' is not allowed."); } else { return; } } else { if (oneOf != null && oneOf.contains(str)) { return; } else { e = new DataValidationException("Blanks are not allowed. '{value}' is blank."); } } } if (matcher != null && e == null) { boolean match; synchronized (matcher) { match = matcher.reset(str).matches(); } if (!match) { e = new DataValidationException("Value '{value}' does not match expected pattern: '" + regexToMatch + "'"); } } } if (oneOf != null && !oneOf.contains(str)) { e = new DataValidationException("Value '{value}' is not allowed. Expecting one of: " + oneOf); } if (e == null && noneOf != null && noneOf.contains(str)) { e = new DataValidationException("Value '{value}' is not allowed."); } for (int i = 0; e == null && i < validators.length; i++) { String error = validators[i].validate(value); if (error != null && !error.trim().isEmpty()) { e = new DataValidationException("Value '{value}' didn't pass validation: " + error); } } if (e != null) { e.setValue(value); throw e; } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/conversions/Validator.java000066400000000000000000000030741475274123300333510ustar00rootroot00000000000000/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.conversions; /** * Defines a custom validation process to be executed when reading or writing * values into a field of a java bean that is annotated with {@link com.univocity.parsers.annotations.Validate} * * @param the expected type of the value to be validated */ public interface Validator { /** * Executes the required validations over a given value, returning * any validation error messages that are applicable. * * If no validation errors are found, returns a blank {@code String} or {@code null} * * @param value the value to be validated * @return a validation error message if the given value fails the validation process. * If the value is acceptable this method can return either a blank {@code String} or {@code null} */ String validate(T value); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/000077500000000000000000000000001475274123300270005ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/Csv.java000066400000000000000000000062611475274123300304030ustar00rootroot00000000000000/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; /** * This class provides default configurations using CSV formats commonly used for parsing/writing. */ public class Csv { /** * Provides a basic CSV configuration that allows parsing CSV files produced by Microsoft Excel. * * @return a pre-configured {@link CsvParserSettings} object with suggested settings * for parsing CSV files produced by Microsoft Excel. */ public static CsvParserSettings parseExcel() { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\r\n"); settings.getFormat().setComment('\0'); settings.setParseUnescapedQuotes(false); settings.setSkipEmptyLines(false); settings.trimValues(false); return settings; } /** * Provides a basic CSV configuration for parsing CSV files in accordance with the * rules established by RFC 4180 * * @return a pre-configured {@link CsvParserSettings} object with suggested settings for parsing * CSV using the RFC 4180 rules. */ public static CsvParserSettings parseRfc4180() { CsvParserSettings settings = parseExcel(); settings.setNormalizeLineEndingsWithinQuotes(false); return settings; } /** * Provides a basic CSV configuration that allows writing CSV files that can be read by Microsoft Excel. * * @return a pre-configured {@link CsvWriterSettings} object with suggested settings for generating * CSV files that can be read by Microsoft Excel. */ public static CsvWriterSettings writeExcel() { CsvWriterSettings settings = new CsvWriterSettings(); settings.getFormat().setLineSeparator("\r\n"); settings.getFormat().setComment('\0'); settings.setEmptyValue(null); settings.setSkipEmptyLines(false); settings.trimValues(false); return settings; } /** * Provides a basic CSV configuration for writing CSV files in accordance with the * rules established by RFC 4180 * * @return a pre-configured {@link CsvWriterSettings} object with the settings required to generate * CSV files in accordance with the rules established by RFC 4180 */ public static CsvWriterSettings writeRfc4180() { CsvWriterSettings settings = writeExcel(); settings.setNormalizeLineEndingsWithinQuotes(false); settings.setQuoteEscapingEnabled(true); return settings; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvFormat.java000077500000000000000000000211051475274123300315510ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; import java.util.*; /** * The CSV format configuration. In addition to the default configuration in {@link Format}, the CSV format defines: * *

    *
  • delimiter (defaults to ','): the field delimiter character. Used to separate individual fields in a CSV record (where the record is usually a line of text with multiple fields). *

    e.g. the value a , b is parsed as [ a ][ b ]

  • *
  • quote (defaults to '"'): character used for escaping values where the field delimiter is part of the value. *

    e.g. the value " a , b " is parsed as [ a , b ] (instead of [ a ][ b ]

  • *
  • quoteEscape (defaults to '"'): character used for escaping the quote character inside an already quoted value *

    e.g. the value " "" a , b "" " is parsed as [ " a , b " ] (instead of [ " a ][ b " ] or [ "" a , b "" ])

  • *
  • charToEscapeQuoteEscaping (defaults to '\0' - undefined): character used for escaping the escape for the quote character *

    e.g. if the quoteEscape and charToEscapeQuoteEscaping are set to '\', the value " \\\" a , b \\\" " is parsed as [ \" a , b \" ]

  • *
* * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.Format */ public class CsvFormat extends Format { private char quote = '"'; private char quoteEscape = '"'; private String delimiter = ","; private Character charToEscapeQuoteEscaping = null; /** * Returns the character used for escaping values where the field delimiter is part of the value. Defaults to '"' * * @return the quote character */ public char getQuote() { return quote; } /** * Defines the character used for escaping values where the field delimiter is part of the value. Defaults to '"' * * @param quote the quote character */ public void setQuote(char quote) { this.quote = quote; } /** * Identifies whether or not a given character is used for escaping values where the field delimiter is part of the value * * @param ch the character to be verified * * @return true if the given character is the character used for escaping values, false otherwise */ public boolean isQuote(char ch) { return this.quote == ch; } /** * Returns the character used for escaping quotes inside an already quoted value. Defaults to '"' * * @return the quote escape character */ public char getQuoteEscape() { return quoteEscape; } /** * Defines the character used for escaping quotes inside an already quoted value. Defaults to '"' * * @param quoteEscape the quote escape character */ public void setQuoteEscape(char quoteEscape) { this.quoteEscape = quoteEscape; } /** * Identifies whether or not a given character is used for escaping quotes inside an already quoted value. * * @param ch the character to be verified * * @return true if the given character is the quote escape character, false otherwise */ public boolean isQuoteEscape(char ch) { return this.quoteEscape == ch; } /** * Returns the field delimiter character. Defaults to ',' * * @return the field delimiter character */ public char getDelimiter() { if (delimiter.length() > 1) { throw new UnsupportedOperationException("Delimiter '" + delimiter + "' has more than one character. Use method getDelimiterString()"); } return delimiter.charAt(0); } /** * Returns the field delimiter sequence. * * @return the field delimiter as a {@code String}. */ public String getDelimiterString() { return delimiter; } /** * Defines the field delimiter character. Defaults to ',' * * @param delimiter the field delimiter character */ public void setDelimiter(char delimiter) { this.delimiter = String.valueOf(delimiter); } /** * Defines the field delimiter as a sequence of characters. Defaults to ',' * * @param delimiter the field delimiter sequence. */ public void setDelimiter(String delimiter) { if (delimiter == null) { throw new IllegalArgumentException("Delimiter cannot be null"); } if (delimiter.isEmpty()) { throw new IllegalArgumentException("Delimiter cannot be empty"); } this.delimiter = delimiter; } /** * Identifies whether or not a given character represents a field delimiter * * @param ch the character to be verified * * @return true if the given character is the field delimiter character, false otherwise */ public boolean isDelimiter(char ch) { if (delimiter.length() > 1) { throw new UnsupportedOperationException("Delimiter '" + delimiter + "' has more than one character. Use method isDelimiter(String)"); } return this.delimiter.charAt(0) == ch; } /** * Identifies whether or not a given character represents a field delimiter * * @param sequence the character sequence to be verified * * @return true if the given sequence is the field delimiter character sequence, false otherwise */ public boolean isDelimiter(String sequence) { return this.delimiter.equals(sequence); } /** * Returns the character used to escape the character used for escaping quotes defined by {@link #getQuoteEscape()}. * For example, if the quote escape is set to '\', and the quoted value ends with: \", as in the following example: * *

* [ " a\\", b ] *

* * Then: *
    *
  • If the character to escape the '\' is undefined, the record won't be parsed. The parser will read characters: [a],[\],["],[,],[ ],[b] and throw an error because it cannot find a closing quote
  • *
  • If the character to escape the '\' is defined as '\', the record will be read with 2 values: [a\] and [b]
  • *
* Defaults to '\0' (undefined) * * @return the character to escape the character used for escaping quotes defined */ public final char getCharToEscapeQuoteEscaping() { if (charToEscapeQuoteEscaping == null) { //not provided by the user if (quote == quoteEscape) { return '\0'; //not required } else { return quoteEscape; } } return charToEscapeQuoteEscaping; } /** * Defines the character used to escape the character used for escaping quotes defined by {@link #getQuoteEscape()}. * For example, if the quote escape is set to '\', and the quoted value ends with: \", as in the following example: * *

* [ " a\\", b ] *

* * Then: *
    *
  • If the character to escape the '\' is undefined, the record won't be parsed. The parser will read characters: [a],[\],["],[,],[ ],[b] and throw an error because it cannot find a closing quote
  • *
  • If the character to escape the '\' is defined as '\', the record will be read with 2 values: [a\] and [b]
  • *
* Defaults to '\0' (undefined) * * @param charToEscapeQuoteEscaping the character to escape the character used for escaping quotes defined */ public final void setCharToEscapeQuoteEscaping(char charToEscapeQuoteEscaping) { this.charToEscapeQuoteEscaping = charToEscapeQuoteEscaping; } /** * Identifies whether or not a given character is used to escape the character used for escaping quotes defined by {@link #getQuoteEscape()}. * * @param ch the character to be verified * * @return true if the given character is used to escape the quote escape character, false otherwise */ public final boolean isCharToEscapeQuoteEscaping(char ch) { char current = getCharToEscapeQuoteEscaping(); return current != '\0' && current == ch; } @Override protected TreeMap getConfiguration() { TreeMap out = new TreeMap(); out.put("Quote character", quote); out.put("Quote escape character", quoteEscape); out.put("Quote escape escape character", charToEscapeQuoteEscaping); out.put("Field delimiter", delimiter); return out; } @Override public final CsvFormat clone() { return (CsvFormat) super.clone(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvFormatDetector.java000066400000000000000000000334671475274123300332560ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.*; import java.util.*; import java.util.Map.*; /** * An {@link InputAnalysisProcess} to detect column delimiters, quotes and quote escapes in a CSV input. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public abstract class CsvFormatDetector implements InputAnalysisProcess { private final int MAX_ROW_SAMPLES; private final char comment; private final char suggestedDelimiter; private final char normalizedNewLine; private final int whitespaceRangeStart; private char[] allowedDelimiters; private char[] delimiterPreference; private final char suggestedQuote; private final char suggestedQuoteEscape; /** * Builds a new {@code CsvFormatDetector} * * @param maxRowSamples the number of row samples to collect before analyzing the statistics * @param settings the configuration provided by the user with potential defaults in case the detection is unable to discover the proper column * delimiter or quote character. * @param whitespaceRangeStart starting range of characters considered to be whitespace. */ public CsvFormatDetector(int maxRowSamples, CsvParserSettings settings, int whitespaceRangeStart) { this.MAX_ROW_SAMPLES = maxRowSamples; this.whitespaceRangeStart = whitespaceRangeStart; allowedDelimiters = settings.getDelimitersForDetection(); if (allowedDelimiters != null && allowedDelimiters.length > 0) { suggestedDelimiter = allowedDelimiters[0]; delimiterPreference = allowedDelimiters.clone(); Arrays.sort(allowedDelimiters); } else { String delimiter = settings.getFormat().getDelimiterString(); suggestedDelimiter = delimiter.length() > 1 ? ',' : settings.getFormat().getDelimiter(); allowedDelimiters = new char[0]; delimiterPreference = allowedDelimiters; } normalizedNewLine = settings.getFormat().getNormalizedNewline(); comment = settings.getFormat().getComment(); suggestedQuote = settings.getFormat().getQuote(); suggestedQuoteEscape = settings.getFormat().getQuoteEscape(); } protected Map calculateTotals(List> symbolsPerRow) { Map out = new HashMap(); for (Map rowStats : symbolsPerRow) { for (Map.Entry symbolStats : rowStats.entrySet()) { Character symbol = symbolStats.getKey(); Integer count = symbolStats.getValue(); Integer total = out.get(symbol); if (total == null) { total = 0; } out.put(symbol, total + count); } } return out; } @Override public void execute(char[] characters, int length) { Set allSymbols = new HashSet(); Map symbols = new HashMap(); Map escape = new HashMap(); List> symbolsPerRow = new ArrayList>(); int doubleQuoteCount = 0; int singleQuoteCount = 0; int i; char inQuote = '\0'; boolean afterNewLine = true; for (i = 0; i < length; i++) { char ch = characters[i]; if (afterNewLine && ch == comment) { while (++i < length) { ch = characters[i]; if (ch == '\r' || ch == '\n' || ch == normalizedNewLine) { if (ch == '\r' && i + 1 < characters.length && characters[i + 1] == '\n') { i++; } break; } } continue; } if (ch == '"' || ch == '\'') { if (inQuote == ch) { //closing quotes (potentially) if (ch == '"') { doubleQuoteCount++; } else { singleQuoteCount++; } if (i + 1 < length) { char next = characters[i + 1]; if (Character.isLetterOrDigit(next) || (next <= ' ' && whitespaceRangeStart < next && next != '\n' && next != '\r')) { //no special characters after quote, might be escaping //special character before (potentially) closing quote, might be an escape char prev = characters[i - 1]; if (!Character.isLetterOrDigit(prev) && prev != '\n' && prev != '\r') { increment(escape, prev); } } } inQuote = '\0'; } else if (inQuote == '\0') { char prev = '\0'; int j = i; while (prev <= ' ' && --j >= 0) { prev = characters[j]; } if (j < 0 || !Character.isLetterOrDigit(prev)) { inQuote = ch; } } continue; } if (inQuote != '\0') { //keep looping until the quote is closed. continue; } afterNewLine = false; if (isSymbol(ch)) { //counts all symbols. Skips letters and digits allSymbols.add(ch); increment(symbols, ch); } else if ((ch == '\r' || ch == '\n' || ch == normalizedNewLine) && symbols.size() > 0) { //got a newline and collected some symbols? Good! afterNewLine = true; symbolsPerRow.add(symbols); if (symbolsPerRow.size() == MAX_ROW_SAMPLES) { break; } symbols = new HashMap(); } } if (symbols.size() > 0 && length < characters.length) { symbolsPerRow.add(symbols); } if (length >= characters.length && i >= length && symbolsPerRow.size() > 1) { // if got to the end of the buffer, discard last row. It's probably incomplete anyway. symbolsPerRow.remove(symbolsPerRow.size() - 1); } Map totals = calculateTotals(symbolsPerRow); Map sums = new HashMap(); Set toRemove = new HashSet(); //combines the number of symbols found in each row and sums the difference. for (Map prev : symbolsPerRow) { for (Map current : symbolsPerRow) { for (Character symbol : allSymbols) { Integer previousCount = prev.get(symbol); Integer currentCount = current.get(symbol); if (previousCount == null && currentCount == null) { // got a symbol that does not appear in all rows? Discard it. toRemove.add(symbol); } if (previousCount == null || currentCount == null) { continue; } increment(sums, symbol, Math.abs(previousCount - currentCount)); // we expect to always get 0 or close to 0 here, so the symbol occurs in all rows } } } if (toRemove.size() == sums.size()) { //will discard all symbols. Stick with the symbols that showed up more consistently across all rows. Map lineCount = new HashMap(); for (i = 0; i < symbolsPerRow.size(); i++) { for (Character symbolInRow : symbolsPerRow.get(i).keySet()) { Integer count = lineCount.get(symbolInRow); if (count == null) { count = 0; } lineCount.put(symbolInRow, count + 1); } } Integer highestLineCount = null; for (Map.Entry e : lineCount.entrySet()) { if (highestLineCount == null || highestLineCount < e.getValue()) { highestLineCount = e.getValue(); } } Character bestCandidate = null; for (Map.Entry e : lineCount.entrySet()) { if (e.getValue().equals(highestLineCount)) { if (bestCandidate == null) { bestCandidate = e.getKey(); } else { // multiple characters can be the delimiter, unable to detect reliably. bestCandidate = null; break; } } } if (bestCandidate != null) { toRemove.remove(bestCandidate); } } sums.keySet().removeAll(toRemove); if (allowedDelimiters.length > 0) { Set toRetain = new HashSet(); for (char c : allowedDelimiters) { toRetain.add(c); } sums.keySet().retainAll(toRetain); } char delimiter = pickDelimiter(sums, totals); char quote; if (doubleQuoteCount == 0 && singleQuoteCount == 0) { quote = suggestedQuote; } else { quote = doubleQuoteCount >= singleQuoteCount ? '"' : '\''; } escape.remove(delimiter); char quoteEscape = doubleQuoteCount == 0 && singleQuoteCount == 0 ? suggestedQuoteEscape : max(escape, totals, quote); apply(delimiter, quote, quoteEscape); } protected char pickDelimiter(Map sums, Map totals) { char delimiterMax = max(sums, totals, suggestedDelimiter); char delimiterMin = min(sums, totals, suggestedDelimiter); if (delimiterMin == ' ' || delimiterMax == ' ') { boolean hasOtherDelimiters = false; for (Map.Entry e : sums.entrySet()) { if (e.getValue() == 0 && e.getKey() != ' ') { hasOtherDelimiters = true; break; } } if (hasOtherDelimiters) { totals.remove(' '); delimiterMax = max(sums, totals, suggestedDelimiter); delimiterMin = min(sums, totals, suggestedDelimiter); } } char delimiter; out: if (delimiterMax != delimiterMin) { if (sums.get(delimiterMin) == 0 && sums.get(delimiterMax) != 0) { delimiter = delimiterMin; break out; } for (char c : delimiterPreference) { if (c == delimiterMin) { delimiter = delimiterMin; break out; } else if (c == delimiterMax) { delimiter = delimiterMax; break out; } } if (totals.get(delimiterMin) > totals.get(delimiterMax)) { delimiter = delimiterMin; break out; } delimiter = delimiterMax; } else { delimiter = delimiterMax; } return delimiter; } /** * Increments the number associated with a character in a map by 1 * * @param map the map of characters and their numbers * @param symbol the character whose number should be increment */ protected void increment(Map map, char symbol) { increment(map, symbol, 1); } /** * Increments the number associated with a character in a map * * @param map the map of characters and their numbers * @param symbol the character whose number should be increment * @param incrementSize the size of the increment */ protected void increment(Map map, char symbol, int incrementSize) { Integer count = map.get(symbol); if (count == null) { count = 0; } map.put(symbol, count + incrementSize); } /** * Returns the character with the lowest associated number. * * @param map the map of characters and their numbers * @param defaultChar the default character to return in case the map is empty * * @return the character with the lowest number associated. */ protected char min(Map map, Map totals, char defaultChar) { return getChar(map, totals, defaultChar, true); } /** * Returns the character with the highest associated number. * * @param map the map of characters and their numbers * @param defaultChar the default character to return in case the map is empty * * @return the character with the highest number associated. */ protected char max(Map map, Map totals, char defaultChar) { return getChar(map, totals, defaultChar, false); } /** * Returns the character with the highest or lowest associated number. * * @param map the map of characters and their numbers * @param defaultChar the default character to return in case the map is empty * @param min a flag indicating whether to return the character associated with the lowest number in the map. * If {@code false} then the character associated with the highest number found will be returned. * * @return the character with the highest/lowest number associated. */ protected char getChar(Map map, Map totals, char defaultChar, boolean min) { int val = min ? Integer.MAX_VALUE : Integer.MIN_VALUE; for (Entry e : map.entrySet()) { int sum = e.getValue(); if ((min && sum <= val) || (!min && sum >= val)) { char newChar = e.getKey(); if (val == sum) { Integer currentTotal = totals.get(defaultChar); Integer newTotal = totals.get(newChar); if (currentTotal != null && newTotal != null) { if (currentTotal.equals(newTotal)) { int defIndex = ArgumentUtils.indexOf(delimiterPreference, defaultChar, 0); int newIndex = ArgumentUtils.indexOf(delimiterPreference, newChar, 0); if (defIndex != -1 && newIndex != -1) { defaultChar = defIndex < newIndex ? defaultChar : newChar; } } else if ((min && newTotal > currentTotal) || (!min && newTotal > currentTotal)) { defaultChar = newChar; } } else if (isSymbol(newChar)) { defaultChar = newChar; } } else { val = sum; defaultChar = newChar; } } } return defaultChar; } protected boolean isSymbol(char ch) { return isAllowedDelimiter(ch) || ch != comment && !Character.isLetterOrDigit(ch) && (ch == '\t' || ch >= ' '); } protected boolean isAllowedDelimiter(char ch) { return Arrays.binarySearch(allowedDelimiters, ch) >= 0; } /** * Applies the discovered CSV format elements to the {@link CsvParser} * * @param delimiter the discovered delimiter character * @param quote the discovered quote character * @param quoteEscape the discovered quote escape character. */ protected abstract void apply(char delimiter, char quote, char quoteEscape); } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvParser.java000077500000000000000000000554241475274123300315700ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.EOFException; import com.univocity.parsers.common.input.*; import java.io.*; import static com.univocity.parsers.csv.UnescapedQuoteHandling.*; /** * A very fast CSV parser implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see CsvFormat * @see CsvParserSettings * @see CsvWriter * @see AbstractParser */ public final class CsvParser extends AbstractParser { private boolean parseUnescapedQuotes; private boolean parseUnescapedQuotesUntilDelimiter; private boolean backToDelimiter; private final boolean doNotEscapeUnquotedValues; private final boolean keepEscape; private final boolean keepQuotes; private boolean unescaped; private char prev; private char delimiter; private char[] multiDelimiter; private char quote; private char quoteEscape; private char escapeEscape; private char newLine; private final DefaultCharAppender whitespaceAppender; private final boolean normalizeLineEndingsInQuotes; private UnescapedQuoteHandling quoteHandling; private final String nullValue; private final int maxColumnLength; private final String emptyValue; private final boolean trimQuotedLeading; private final boolean trimQuotedTrailing; private char[] delimiters; private int match = 0; private int formatDetectorRowSampleCount; /** * The CsvParser supports all settings provided by {@link CsvParserSettings}, and requires this configuration to be properly initialized. * * @param settings the parser configuration */ public CsvParser(CsvParserSettings settings) { super(settings); parseUnescapedQuotes = settings.isParseUnescapedQuotes(); parseUnescapedQuotesUntilDelimiter = settings.isParseUnescapedQuotesUntilDelimiter(); doNotEscapeUnquotedValues = !settings.isEscapeUnquotedValues(); keepEscape = settings.isKeepEscapeSequences(); keepQuotes = settings.getKeepQuotes(); normalizeLineEndingsInQuotes = settings.isNormalizeLineEndingsWithinQuotes(); nullValue = settings.getNullValue(); emptyValue = settings.getEmptyValue(); maxColumnLength = settings.getMaxCharsPerColumn(); trimQuotedTrailing = settings.getIgnoreTrailingWhitespacesInQuotes(); trimQuotedLeading = settings.getIgnoreLeadingWhitespacesInQuotes(); formatDetectorRowSampleCount = settings.getFormatDetectorRowSampleCount(); updateFormat(settings.getFormat()); whitespaceAppender = new ExpandingCharAppender(10, "", whitespaceRangeStart); this.quoteHandling = settings.getUnescapedQuoteHandling(); if (quoteHandling == null) { if (parseUnescapedQuotes) { if (parseUnescapedQuotesUntilDelimiter) { quoteHandling = STOP_AT_DELIMITER; } else { quoteHandling = STOP_AT_CLOSING_QUOTE; } } else { quoteHandling = RAISE_ERROR; } } else { backToDelimiter = quoteHandling == BACK_TO_DELIMITER; parseUnescapedQuotesUntilDelimiter = quoteHandling == STOP_AT_DELIMITER || quoteHandling == SKIP_VALUE || backToDelimiter; parseUnescapedQuotes = quoteHandling != RAISE_ERROR; } } @Override protected final void parseRecord() { if (multiDelimiter == null) { parseSingleDelimiterRecord(); } else { parseMultiDelimiterRecord(); } } private final void parseSingleDelimiterRecord() { if (ch <= ' ' && ignoreLeadingWhitespace && whitespaceRangeStart < ch) { ch = input.skipWhitespace(ch, delimiter, quote); } while (ch != newLine) { if (ch <= ' ' && ignoreLeadingWhitespace && whitespaceRangeStart < ch) { ch = input.skipWhitespace(ch, delimiter, quote); } if (ch == delimiter || ch == newLine) { output.emptyParsed(); } else { unescaped = false; prev = '\0'; if (ch == quote) { input.enableNormalizeLineEndings(normalizeLineEndingsInQuotes); int len = output.appender.length(); if (len == 0) { String value = input.getQuotedString(quote, quoteEscape, escapeEscape, maxColumnLength, delimiter, newLine, keepQuotes, keepEscape, trimQuotedLeading, trimQuotedTrailing); if (value != null) { output.valueParsed(value == "" ? emptyValue : value); input.enableNormalizeLineEndings(true); try { ch = input.nextChar(); if (ch == delimiter) { try { ch = input.nextChar(); if (ch == newLine) { output.emptyParsed(); } } catch (EOFException e) { output.emptyParsed(); return; } } } catch (EOFException e) { return; } continue; } } else if (len == -1 && input.skipQuotedString(quote, quoteEscape, delimiter, newLine)) { output.valueParsed(); try { ch = input.nextChar(); if (ch == delimiter) { try { ch = input.nextChar(); if (ch == newLine) { output.emptyParsed(); } } catch (EOFException e) { output.emptyParsed(); return; } } } catch (EOFException e) { return; } continue; } output.trim = trimQuotedTrailing; parseQuotedValue(); input.enableNormalizeLineEndings(true); if (!(unescaped && quoteHandling == BACK_TO_DELIMITER && output.appender.length() == 0)) { output.valueParsed(); } } else if (doNotEscapeUnquotedValues) { String value = null; int len = output.appender.length(); if (len == 0) { value = input.getString(ch, delimiter, ignoreTrailingWhitespace, nullValue, maxColumnLength); } if (value != null) { output.valueParsed(value); ch = input.getChar(); } else { if (len != -1) { output.trim = ignoreTrailingWhitespace; ch = output.appender.appendUntil(ch, input, delimiter, newLine); } else { if (input.skipString(ch, delimiter)) { ch = input.getChar(); } else { ch = output.appender.appendUntil(ch, input, delimiter, newLine); } } output.valueParsed(); } } else { output.trim = ignoreTrailingWhitespace; parseValueProcessingEscape(); output.valueParsed(); } } if (ch != newLine) { ch = input.nextChar(); if (ch == newLine) { output.emptyParsed(); } } } } private void skipValue() { output.appender.reset(); output.appender = NoopCharAppender.getInstance(); if (multiDelimiter == null) { ch = NoopCharAppender.getInstance().appendUntil(ch, input, delimiter, newLine); } else { for (; match < multiDelimiter.length && ch != newLine; ch = input.nextChar()) { if (multiDelimiter[match] == ch) { match++; } else { match = 0; } } } } private void handleValueSkipping(boolean quoted) { switch (quoteHandling) { case SKIP_VALUE: skipValue(); break; case RAISE_ERROR: throw new TextParsingException(context, "Unescaped quote character '" + quote + "' inside " + (quoted ? "quoted" : "") + " value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } private void handleUnescapedQuoteInValue() { switch (quoteHandling) { case BACK_TO_DELIMITER: case STOP_AT_CLOSING_QUOTE: case STOP_AT_DELIMITER: output.appender.append(quote); prev = ch; parseValueProcessingEscape(); break; default: handleValueSkipping(false); break; } } private int nextDelimiter() { if (multiDelimiter == null) { return output.appender.indexOfAny(delimiters, 0); } else { int lineEnd = output.appender.indexOf(newLine, 0); int delimiter = output.appender.indexOf(multiDelimiter, 0); return lineEnd != -1 && lineEnd < delimiter ? lineEnd : delimiter; } } private boolean handleUnescapedQuote() { unescaped = true; switch (quoteHandling) { case BACK_TO_DELIMITER: int pos; int lastPos = 0; while ((pos = nextDelimiter()) != -1) { lastPos = pos; String value = output.appender.substring(0, pos); if (keepQuotes && output.appender.charAt(pos - 1) == quote) { value += quote; } output.valueParsed(value); if (output.appender.charAt(pos) == newLine) { output.pendingRecords.add(output.rowParsed()); output.appender.remove(0, pos + 1); continue; } if (multiDelimiter == null) { output.appender.remove(0, pos + 1); } else { output.appender.remove(0, pos + multiDelimiter.length); } } if (keepQuotes && input.lastIndexOf(quote) > lastPos) { output.appender.append(quote); } output.appender.append(ch); prev = '\0'; if (multiDelimiter == null) { parseQuotedValue(); } else { parseQuotedValueMultiDelimiter(); } return true; case STOP_AT_CLOSING_QUOTE: case STOP_AT_DELIMITER: output.appender.append(quote); output.appender.append(ch); prev = ch; if (multiDelimiter == null) { parseQuotedValue(); } else { parseQuotedValueMultiDelimiter(); } return true; //continue; default: handleValueSkipping(true); return false; } } private void processQuoteEscape() { if (ch == quoteEscape && prev == escapeEscape && escapeEscape != '\0') { if (keepEscape) { output.appender.append(escapeEscape); } output.appender.append(quoteEscape); ch = '\0'; } else if (prev == quoteEscape) { if (ch == quote) { if (keepEscape) { output.appender.append(quoteEscape); } output.appender.append(quote); ch = '\0'; } else { output.appender.append(prev); } } else if (ch == quote && prev == quote) { output.appender.append(quote); } else if (prev == quote) { //unescaped quote detected handleUnescapedQuoteInValue(); } } private void parseValueProcessingEscape() { while (ch != delimiter && ch != newLine) { if (ch != quote && ch != quoteEscape) { if (prev == quote) { //unescaped quote detected handleUnescapedQuoteInValue(); return; } output.appender.append(ch); } else { processQuoteEscape(); } prev = ch; ch = input.nextChar(); } } private void parseQuotedValue() { if (prev != '\0' && parseUnescapedQuotesUntilDelimiter) { if (quoteHandling == SKIP_VALUE) { skipValue(); return; } if (!keepQuotes) { output.appender.prepend(quote); } ch = input.nextChar(); output.trim = ignoreTrailingWhitespace; ch = output.appender.appendUntil(ch, input, delimiter, newLine); } else { if (keepQuotes && prev == '\0') { output.appender.append(quote); } ch = input.nextChar(); if (trimQuotedLeading && ch <= ' ' && output.appender.length() == 0) { while ((ch = input.nextChar()) <= ' ') ; } while (true) { if (prev == quote && (ch <= ' ' && whitespaceRangeStart < ch || ch == delimiter || ch == newLine)) { break; } if (ch != quote && ch != quoteEscape) { if (prev == quote) { //unescaped quote detected if (handleUnescapedQuote()) { if (quoteHandling == SKIP_VALUE) { break; } else { return; } } else { return; } } if (prev == quoteEscape && quoteEscape != '\0') { output.appender.append(quoteEscape); } ch = output.appender.appendUntil(ch, input, quote, quoteEscape, escapeEscape); prev = ch; ch = input.nextChar(); } else { processQuoteEscape(); prev = ch; ch = input.nextChar(); if (unescaped && (ch == delimiter || ch == newLine)) { return; } } } // handles whitespaces after quoted value: whitespaces are ignored. Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != delimiter && ch != newLine && ch <= ' ' && whitespaceRangeStart < ch) { whitespaceAppender.reset(); do { //saves whitespaces after value whitespaceAppender.append(ch); ch = input.nextChar(); //found a new line, go to next record. if (ch == newLine) { if (keepQuotes) { output.appender.append(quote); } return; } } while (ch <= ' ' && whitespaceRangeStart < ch && ch != delimiter); //there's more stuff after the quoted value, not only empty spaces. if (ch != delimiter && parseUnescapedQuotes) { if (output.appender instanceof DefaultCharAppender) { //puts the quote before whitespaces back, then restores the whitespaces output.appender.append(quote); ((DefaultCharAppender) output.appender).append(whitespaceAppender); } //the next character is not the escape character, put it there if (parseUnescapedQuotesUntilDelimiter || ch != quote && ch != quoteEscape) { output.appender.append(ch); } //sets this character as the previous character (may be escaping) //calls recursively to keep parsing potentially quoted content prev = ch; parseQuotedValue(); } else if (keepQuotes) { output.appender.append(quote); } } else if (keepQuotes) { output.appender.append(quote); } if (ch != delimiter && ch != newLine) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } } @Override protected final InputAnalysisProcess getInputAnalysisProcess() { if (settings.isDelimiterDetectionEnabled() || settings.isQuoteDetectionEnabled()) { return new CsvFormatDetector(formatDetectorRowSampleCount, settings, whitespaceRangeStart) { @Override protected void apply(char delimiter, char quote, char quoteEscape) { if (settings.isDelimiterDetectionEnabled()) { CsvParser.this.delimiter = delimiter; CsvParser.this.delimiters[0] = delimiter; } if (settings.isQuoteDetectionEnabled()) { CsvParser.this.quote = quote; CsvParser.this.quoteEscape = quoteEscape; } } }; } return null; } /** * Returns the CSV format detected when one of the following settings is enabled: *
    *
  • {@link CommonParserSettings#isLineSeparatorDetectionEnabled()}
  • *
  • {@link CsvParserSettings#isDelimiterDetectionEnabled()}
  • *
  • {@link CsvParserSettings#isQuoteDetectionEnabled()}
  • *
* * The detected format will be available once the parsing process is initialized (i.e. when {@link AbstractParser#beginParsing(Reader) runs}. * * @return the detected CSV format, or {@code null} if no detection has been enabled or if the parsing process has not been started yet. */ public final CsvFormat getDetectedFormat() { CsvFormat out = null; if (settings.isDelimiterDetectionEnabled()) { out = settings.getFormat().clone(); out.setDelimiter(this.delimiter); } if (settings.isQuoteDetectionEnabled()) { out = out == null ? settings.getFormat().clone() : out; out.setQuote(quote); out.setQuoteEscape(quoteEscape); } if (settings.isLineSeparatorDetectionEnabled()) { out = out == null ? settings.getFormat().clone() : out; out.setLineSeparator(input.getLineSeparator()); } return out; } @Override protected final boolean consumeValueOnEOF() { if (ch == quote) { if (prev == quote) { if (keepQuotes) { output.appender.append(quote); } return true; } else { if (!unescaped) { output.appender.append(quote); } } } boolean out = prev != '\0' && ch != delimiter && ch != newLine && ch != comment; ch = prev = '\0'; if (match > 0) { saveMatchingCharacters(); return true; } return out; } /** * Allows changing the format of the input on the fly. * * @param format the new format to use. */ public final void updateFormat(CsvFormat format) { newLine = format.getNormalizedNewline(); multiDelimiter = format.getDelimiterString().toCharArray(); if (multiDelimiter.length == 1) { multiDelimiter = null; delimiter = format.getDelimiter(); delimiters = new char[]{delimiter, newLine}; } else { delimiters = new char[]{multiDelimiter[0], newLine}; } quote = format.getQuote(); quoteEscape = format.getQuoteEscape(); escapeEscape = format.getCharToEscapeQuoteEscaping(); } private void skipWhitespace() { while (ch <= ' ' && match < multiDelimiter.length && ch != newLine && ch != quote && whitespaceRangeStart < ch) { ch = input.nextChar(); if (multiDelimiter[match] == ch) { if (matchDelimiter()) { output.emptyParsed(); ch = input.nextChar(); } } } saveMatchingCharacters(); } private void saveMatchingCharacters() { if (match > 0) { if (match < multiDelimiter.length) { output.appender.append(multiDelimiter, 0, match); } match = 0; } } private boolean matchDelimiter() { while (ch == multiDelimiter[match]) { match++; if (match == multiDelimiter.length) { break; } ch = input.nextChar(); } if (multiDelimiter.length == match) { match = 0; return true; } if (match > 0) { saveMatchingCharacters(); } return false; } private boolean matchDelimiterAfterQuote() { while (ch == multiDelimiter[match]) { match++; if (match == multiDelimiter.length) { break; } ch = input.nextChar(); } if (multiDelimiter.length == match) { match = 0; return true; } return false; } private void parseMultiDelimiterRecord() { if (ch <= ' ' && ignoreLeadingWhitespace && whitespaceRangeStart < ch) { skipWhitespace(); } while (ch != newLine) { if (ch <= ' ' && ignoreLeadingWhitespace && whitespaceRangeStart < ch) { skipWhitespace(); } if (ch == newLine || matchDelimiter()) { output.emptyParsed(); } else { unescaped = false; prev = '\0'; if (ch == quote && output.appender.length() == 0) { input.enableNormalizeLineEndings(normalizeLineEndingsInQuotes); output.trim = trimQuotedTrailing; parseQuotedValueMultiDelimiter(); input.enableNormalizeLineEndings(true); if (!(unescaped && quoteHandling == BACK_TO_DELIMITER && output.appender.length() == 0)) { output.valueParsed(); } } else if (doNotEscapeUnquotedValues) { appendUntilMultiDelimiter(); if (ignoreTrailingWhitespace) { output.appender.updateWhitespace(); } output.valueParsed(); } else { output.trim = ignoreTrailingWhitespace; parseValueProcessingEscapeMultiDelimiter(); output.valueParsed(); } } if (ch != newLine) { ch = input.nextChar(); if (ch == newLine) { output.emptyParsed(); } } } } private void appendUntilMultiDelimiter() { while (match < multiDelimiter.length && ch != newLine) { if (multiDelimiter[match] == ch) { match++; if (match == multiDelimiter.length) { break; } } else { if (match > 0) { saveMatchingCharacters(); continue; } output.appender.append(ch); } ch = input.nextChar(); } saveMatchingCharacters(); } private void parseQuotedValueMultiDelimiter() { if (prev != '\0' && parseUnescapedQuotesUntilDelimiter) { if (quoteHandling == SKIP_VALUE) { skipValue(); return; } if (!keepQuotes) { output.appender.prepend(quote); } ch = input.nextChar(); output.trim = ignoreTrailingWhitespace; appendUntilMultiDelimiter(); } else { if (keepQuotes && prev == '\0') { output.appender.append(quote); } ch = input.nextChar(); if (trimQuotedLeading && ch <= ' ' && output.appender.length() == 0) { while ((ch = input.nextChar()) <= ' ') ; } while (true) { if (prev == quote && (ch <= ' ' && whitespaceRangeStart < ch || ch == newLine)) { break; } if (prev == quote && matchDelimiter()) { if (keepQuotes) { output.appender.append(quote); } return; } if (ch != quote && ch != quoteEscape) { if (prev == quote) { //unescaped quote detected if (handleUnescapedQuote()) { if (quoteHandling == SKIP_VALUE) { break; } else { return; } } else { return; } } if (prev == quoteEscape && quoteEscape != '\0') { output.appender.append(quoteEscape); } ch = output.appender.appendUntil(ch, input, quote, quoteEscape, escapeEscape); prev = ch; ch = input.nextChar(); } else { processQuoteEscape(); prev = ch; ch = input.nextChar(); if (unescaped && (ch == newLine || matchDelimiter())) { return; } } } } // handles whitespaces after quoted value: whitespaces are ignored. Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && whitespaceRangeStart < ch && !matchDelimiterAfterQuote()) { whitespaceAppender.reset(); do { //saves whitespaces after value whitespaceAppender.append(ch); ch = input.nextChar(); //found a new line, go to next record. if (ch == newLine) { if (keepQuotes) { output.appender.append(quote); } return; } if (matchDelimiterAfterQuote()) { return; } } while (ch <= ' ' && whitespaceRangeStart < ch); //there's more stuff after the quoted value, not only empty spaces. if (parseUnescapedQuotes && !matchDelimiterAfterQuote()) { if (output.appender instanceof DefaultCharAppender) { //puts the quote before whitespaces back, then restores the whitespaces output.appender.append(quote); ((DefaultCharAppender) output.appender).append(whitespaceAppender); } //the next character is not the escape character, put it there if (parseUnescapedQuotesUntilDelimiter || ch != quote && ch != quoteEscape) { output.appender.append(ch); } //sets this character as the previous character (may be escaping) //calls recursively to keep parsing potentially quoted content prev = ch; parseQuotedValue(); } else if (keepQuotes) { output.appender.append(quote); } } else if (keepQuotes && (!unescaped || quoteHandling == STOP_AT_CLOSING_QUOTE)) { output.appender.append(quote); } } private void parseValueProcessingEscapeMultiDelimiter() { while (ch != newLine && !matchDelimiter()) { if (ch != quote && ch != quoteEscape) { if (prev == quote) { //unescaped quote detected handleUnescapedQuoteInValue(); return; } output.appender.append(ch); } else { processQuoteEscape(); } prev = ch; ch = input.nextChar(); } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvParserSettings.java000077500000000000000000000560301475274123300333030ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.*; import java.util.*; /** * This is the configuration class used by the CSV parser ({@link CsvParser}) * *

In addition to the configuration options provided by {@link CommonParserSettings}, the CSVParserSettings include: * *

    *
  • emptyValue (defaults to null): Defines a replacement string to signify an empty value (which is not a null value) *

    When reading, if the parser does not read any character from the input, and the input is within quotes, the empty is used instead of an empty string

  • *
* * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.csv.CsvParser * @see com.univocity.parsers.csv.CsvFormat * @see com.univocity.parsers.common.CommonParserSettings */ public class CsvParserSettings extends CommonParserSettings { private String emptyValue = null; private boolean parseUnescapedQuotes = true; private boolean parseUnescapedQuotesUntilDelimiter = true; private boolean escapeUnquotedValues = false; private boolean keepEscapeSequences = false; private boolean keepQuotes = false; private boolean normalizeLineEndingsWithinQuotes = true; private boolean ignoreTrailingWhitespacesInQuotes = false; private boolean ignoreLeadingWhitespacesInQuotes = false; private boolean delimiterDetectionEnabled = false; private boolean quoteDetectionEnabled = false; private UnescapedQuoteHandling unescapedQuoteHandling = null; private char[] delimitersForDetection = null; private int formatDetectorRowSampleCount = 20; /** * Returns the String representation of an empty value (defaults to null) * *

When reading, if the parser does not read any character from the input, and the input is within quotes, the empty is used instead of an empty string * * @return the String representation of an empty value */ public String getEmptyValue() { return emptyValue; } /** * Sets the String representation of an empty value (defaults to null) * *

When reading, if the parser does not read any character from the input, and the input is within quotes, the empty is used instead of an empty string * * @param emptyValue the String representation of an empty value */ public void setEmptyValue(String emptyValue) { this.emptyValue = emptyValue; } /** * Returns an instance of CharAppender with the configured limit of maximum characters per column and the default value used to represent an empty value * (when the String parsed from the input, within quotes, is empty) * *

This overrides the parent's version because the CSV parser does not rely on the appender to identify null values, but on the other hand, the appender * is required to identify empty values. * * @return an instance of CharAppender with the configured limit of maximum characters per column and the default value used to represent an empty value * (when the String parsed from the input, within quotes, is empty) */ @Override protected CharAppender newCharAppender() { int chars = getMaxCharsPerColumn(); if (chars != -1) { return new DefaultCharAppender(chars, emptyValue, getWhitespaceRangeStart()); } else { return new ExpandingCharAppender(emptyValue, getWhitespaceRangeStart()); } } /** * Returns the default CsvFormat configured to handle CSV inputs compliant to the RFC4180 standard. * * @return and instance of CsvFormat configured to handle CSV inputs compliant to the RFC4180 standard. */ @Override protected CsvFormat createDefaultFormat() { return new CsvFormat(); } /** * Indicates whether the CSV parser should accept unescaped quotes inside quoted values and parse them normally. Defaults to {@code true}. * * @return a flag indicating whether or not the CSV parser should accept unescaped quotes inside quoted values. * * @deprecated use {@link #getUnescapedQuoteHandling()} instead. The configuration returned by {@link #getUnescapedQuoteHandling()} will override this * setting if not null. */ @Deprecated public boolean isParseUnescapedQuotes() { return parseUnescapedQuotes || (unescapedQuoteHandling != null && unescapedQuoteHandling != UnescapedQuoteHandling.RAISE_ERROR); } /** * Configures how to handle unescaped quotes inside quoted values. If set to {@code true}, the parser will parse the quote normally as part of the value. * If set the {@code false}, a {@link TextParsingException} will be thrown. Defaults to {@code true}. * * @param parseUnescapedQuotes indicates whether or not the CSV parser should accept unescaped quotes inside quoted values. * * @deprecated use {@link #setUnescapedQuoteHandling(UnescapedQuoteHandling)} instead. The configuration returned by {@link #getUnescapedQuoteHandling()} * will override this setting if not null. */ @Deprecated public void setParseUnescapedQuotes(boolean parseUnescapedQuotes) { this.parseUnescapedQuotes = parseUnescapedQuotes; } /** * Configures the parser to process values with unescaped quotes, and stop accumulating characters and consider the value parsed when a delimiter is found. * (defaults to {@code true}) * * @param parseUnescapedQuotesUntilDelimiter a flag indicating that the parser should stop accumulating values when a field delimiter character is * found when parsing unquoted and unescaped values. * * @deprecated use {@link #setUnescapedQuoteHandling(UnescapedQuoteHandling)} instead. The configuration returned by {@link #getUnescapedQuoteHandling()} * will override this setting if not null. */ @Deprecated public void setParseUnescapedQuotesUntilDelimiter(boolean parseUnescapedQuotesUntilDelimiter) { if (parseUnescapedQuotesUntilDelimiter) { parseUnescapedQuotes = true; } this.parseUnescapedQuotesUntilDelimiter = parseUnescapedQuotesUntilDelimiter; } /** * When parsing unescaped quotes, indicates the parser should stop accumulating characters and consider the value parsed when a delimiter is found. * (defaults to {@code true}) * * @return a flag indicating that the parser should stop accumulating values when a field delimiter character is * found when parsing unquoted and unescaped values. * * @deprecated use {@link #getUnescapedQuoteHandling()} instead. The configuration returned by {@link #getUnescapedQuoteHandling()} will override this * setting if not null. */ @Deprecated public boolean isParseUnescapedQuotesUntilDelimiter() { return (parseUnescapedQuotesUntilDelimiter && isParseUnescapedQuotes()) || (unescapedQuoteHandling == UnescapedQuoteHandling.STOP_AT_DELIMITER || unescapedQuoteHandling == UnescapedQuoteHandling.SKIP_VALUE); } /** * Indicates whether escape sequences should be processed in unquoted values. Defaults to {@code false}. * *

By default, this is disabled and if the input is {@code A""B,C}, the resulting value will be * {@code [A""B] and [C]} (i.e. the content is read as-is). However, if the parser is configured * to process escape sequences in unquoted values, the result will be {@code [A"B] and [C]}

* * @return true if escape sequences should be processed in unquoted values, otherwise false */ public boolean isEscapeUnquotedValues() { return escapeUnquotedValues; } /** * Configures the parser to process escape sequences in unquoted values. Defaults to {@code false}. * *

By default, this is disabled and if the input is {@code A""B,C}, the resulting value will be * {@code [A""B] and [C]} (i.e. the content is read as-is). However, if the parser is configured * to process escape sequences in unquoted values, the result will be {@code [A"B] and [C]}

* * @param escapeUnquotedValues a flag indicating whether escape sequences should be processed in unquoted values */ public void setEscapeUnquotedValues(boolean escapeUnquotedValues) { this.escapeUnquotedValues = escapeUnquotedValues; } /** * Indicates whether the parser should keep any escape sequences if they are present in the input (i.e. a quote escape sequence such as two double quotes * {@code ""} won't be replaced by a single double quote {@code "}). *

This is disabled by default

* * @return a flag indicating whether escape sequences should be kept (and not replaced) by the parser. */ public final boolean isKeepEscapeSequences() { return keepEscapeSequences; } /** * Configures the parser to keep any escape sequences if they are present in the input (i.e. a quote escape sequence such as 2 double quotes {@code ""} * won't be replaced by a single double quote {@code "}). *

This is disabled by default

* * @param keepEscapeSequences the flag indicating whether escape sequences should be kept (and not replaced) by the parser. */ public final void setKeepEscapeSequences(boolean keepEscapeSequences) { this.keepEscapeSequences = keepEscapeSequences; } /** * Returns a flag indicating whether the parser should analyze the input to discover the column delimiter character. *

Note that the detection process is not guaranteed to discover the correct column delimiter. In this case the delimiter provided by {@link * CsvFormat#getDelimiter()} will be used

* * @return a flag indicating whether the parser should analyze the input to discover the column delimiter character. */ public final boolean isDelimiterDetectionEnabled() { return delimiterDetectionEnabled; } /** * Configures the parser to analyze the input before parsing to discover the column delimiter character. *

Note that the detection process is not guaranteed to discover the correct column delimiter. * The first character in the list of delimiters allowed for detection will be used, if available, otherwise * the delimiter returned by {@link CsvFormat#getDelimiter()} will be used.

* * @param separatorDetectionEnabled the flag to enable/disable discovery of the column delimiter character. * to {@code true}, in order of priority. */ public final void setDelimiterDetectionEnabled(boolean separatorDetectionEnabled) { this.setDelimiterDetectionEnabled(separatorDetectionEnabled, new char[0]); } /** * Configures the parser to analyze the input before parsing to discover the column delimiter character. *

Note that the detection process is not guaranteed to discover the correct column delimiter. * The first character in the list of delimiters allowed for detection will be used, if available, otherwise * the delimiter returned by {@link CsvFormat#getDelimiter()} will be used.

* * @param separatorDetectionEnabled the flag to enable/disable discovery of the column delimiter character. * @param delimitersForDetection possible delimiters for detection when {@link #isDelimiterDetectionEnabled()} evaluates * to {@code true}, in order of priority. */ public final void setDelimiterDetectionEnabled(boolean separatorDetectionEnabled, char... delimitersForDetection) { this.delimiterDetectionEnabled = separatorDetectionEnabled; this.delimitersForDetection = delimitersForDetection; } /** * Returns a flag indicating whether the parser should analyze the input to discover the quote character. The quote escape will also be detected as part of * this process. *

Note that the detection process is not guaranteed to discover the correct quote & escape. * In this case the characters provided by {@link CsvFormat#getQuote()} and {@link CsvFormat#getQuoteEscape()} will be used

* * @return a flag indicating whether the parser should analyze the input to discover the quote character. The quote escape will also be detected as part of * this process. */ public final boolean isQuoteDetectionEnabled() { return quoteDetectionEnabled; } /** * Configures the parser to analyze the input before parsing to discover the quote character. The quote escape will also be detected as part of this * process. *

Note that the detection process is not guaranteed to discover the correct quote & escape. * In this case the characters provided by {@link CsvFormat#getQuote()} and {@link CsvFormat#getQuoteEscape()} will be used

* * @param quoteDetectionEnabled the flag to enable/disable discovery of the quote character. The quote escape will also be detected as part of this process. */ public final void setQuoteDetectionEnabled(boolean quoteDetectionEnabled) { this.quoteDetectionEnabled = quoteDetectionEnabled; } /** * Convenience method to turn on all format detection features in a single method call, namely: *
    *
  • {@link #setDelimiterDetectionEnabled(boolean, char[])}
  • *
  • {@link #setQuoteDetectionEnabled(boolean)}
  • *
  • {@link #setLineSeparatorDetectionEnabled(boolean)}
  • *
*/ public final void detectFormatAutomatically() { this.detectFormatAutomatically(new char[0]); } /** * Convenience method to turn on all format detection features in a single method call, namely: *
    *
  • {@link #setDelimiterDetectionEnabled(boolean, char[])}
  • *
  • {@link #setQuoteDetectionEnabled(boolean)}
  • *
  • {@link #setLineSeparatorDetectionEnabled(boolean)}
  • *
* * @param delimitersForDetection possible delimiters for detection, in order of priority. */ public final void detectFormatAutomatically(char... delimitersForDetection) { this.setDelimiterDetectionEnabled(true, delimitersForDetection); this.setQuoteDetectionEnabled(true); this.setLineSeparatorDetectionEnabled(true); } /** * Flag indicating whether the parser should replace line separators, specified in {@link Format#getLineSeparator()} * by the normalized line separator character specified in {@link Format#getNormalizedNewline()}, even on quoted values. * * This is enabled by default and is used to ensure data be read on any platform without introducing unwanted blank lines. * * For example, consider the quoted value {@code "Line1 \r\n Line2"}. If this is parsed using {@code "\r\n"} as * the line separator sequence, and the normalized new line is set to {@code '\n'} (the default), the output will be: * * {@code [Line1 \n Line2]} * * However, if the value is meant to be kept untouched, and the original line separator should be maintained, set * the {@link #normalizeLineEndingsWithinQuotes} to {@code false}. This will make the parser read the value as-is, producing: * * {@code [Line1 \r\n Line2]} * * @return {@code true} if line separators in quoted values will be normalized, {@code false} otherwise */ public boolean isNormalizeLineEndingsWithinQuotes() { return normalizeLineEndingsWithinQuotes; } /** * Configures the parser to replace line separators, specified in {@link Format#getLineSeparator()} * by the normalized line separator character specified in {@link Format#getNormalizedNewline()}, even on quoted values. * * This is enabled by default and is used to ensure data be read on any platform without introducing unwanted blank lines. * * For example, consider the quoted value {@code "Line1 \r\n Line2"}. If this is parsed using {@code "\r\n"} as * the line separator sequence, and the normalized new line is set to {@code '\n'} (the default), the output will be: * * {@code [Line1 \n Line2]} * * However, if the value is meant to be kept untouched, and the original line separator should be maintained, set * the {@link #normalizeLineEndingsWithinQuotes} to {@code false}. This will make the parser read the value as-is, producing: * * {@code [Line1 \r\n Line2]} * * @param normalizeLineEndingsWithinQuotes flag indicating whether line separators in quoted values should be replaced by * the the character specified in {@link Format#getNormalizedNewline()} . */ public void setNormalizeLineEndingsWithinQuotes(boolean normalizeLineEndingsWithinQuotes) { this.normalizeLineEndingsWithinQuotes = normalizeLineEndingsWithinQuotes; } /** * Configures the handling of values with unescaped quotes. * Defaults to {@code null}, for backward compatibility with {@link #isParseUnescapedQuotes()} and {@link #isParseUnescapedQuotesUntilDelimiter()}. * If set to a non-null value, this setting will override the configuration of {@link #isParseUnescapedQuotes()} and {@link * #isParseUnescapedQuotesUntilDelimiter()}. * * @param unescapedQuoteHandling the handling method to be used when unescaped quotes are found in the input. */ public void setUnescapedQuoteHandling(UnescapedQuoteHandling unescapedQuoteHandling) { this.unescapedQuoteHandling = unescapedQuoteHandling; } /** * Returns the method of handling values with unescaped quotes. * Defaults to {@code null}, for backward compatibility with {@link #isParseUnescapedQuotes()} and {@link #isParseUnescapedQuotesUntilDelimiter()} * If set to a non-null value, this setting will override the configuration of {@link #isParseUnescapedQuotes()} and {@link * #isParseUnescapedQuotesUntilDelimiter()}. * * @return the handling method to be used when unescaped quotes are found in the input, or {@code null} if not set. */ public UnescapedQuoteHandling getUnescapedQuoteHandling() { return this.unescapedQuoteHandling; } /** * Flag indicating whether the parser should keep enclosing quote characters in the values parsed from the input. *

Defaults to {@code false}

* * @return a flag indicating whether enclosing quotes should be maintained when parsing quoted values. */ public boolean getKeepQuotes() { return keepQuotes; } /** * Configures the parser to keep enclosing quote characters in the values parsed from the input. *

Defaults to {@code false}

* * @param keepQuotes flag indicating whether enclosing quotes should be maintained when parsing quoted values. */ public void setKeepQuotes(boolean keepQuotes) { this.keepQuotes = keepQuotes; } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); out.put("Empty value", emptyValue); out.put("Unescaped quote handling", unescapedQuoteHandling); out.put("Escape unquoted values", escapeUnquotedValues); out.put("Keep escape sequences", keepEscapeSequences); out.put("Keep quotes", keepQuotes); out.put("Normalize escaped line separators", normalizeLineEndingsWithinQuotes); out.put("Autodetect column delimiter", delimiterDetectionEnabled); out.put("Autodetect quotes", quoteDetectionEnabled); out.put("Delimiters for detection", Arrays.toString(delimitersForDetection)); out.put("Ignore leading whitespaces in quotes", ignoreLeadingWhitespacesInQuotes); out.put("Ignore trailing whitespaces in quotes", ignoreTrailingWhitespacesInQuotes); } @Override public final CsvParserSettings clone() { return (CsvParserSettings) super.clone(); } @Override public final CsvParserSettings clone(boolean clearInputSpecificSettings) { return (CsvParserSettings) super.clone(clearInputSpecificSettings); } /** * Returns the sequence of possible delimiters for detection when {@link #isDelimiterDetectionEnabled()} evaluates * to {@code true}, in order of priority. * * @return the possible delimiter characters, in order of priority. */ public final char[] getDelimitersForDetection() { return this.delimitersForDetection; } /** * Returns whether or not trailing whitespaces from within quoted values should be skipped (defaults to false) * * Note: if {@link #keepQuotes} evaluates to {@code true}, values won't be trimmed. * * @return true if trailing whitespaces from quoted values should be skipped, false otherwise */ public boolean getIgnoreTrailingWhitespacesInQuotes() { return ignoreTrailingWhitespacesInQuotes; } /** * Defines whether or not trailing whitespaces from quoted values should be skipped (defaults to false) * * Note: if {@link #keepQuotes} evaluates to {@code true}, values won't be trimmed. * * @param ignoreTrailingWhitespacesInQuotes whether trailing whitespaces from quoted values should be skipped */ public void setIgnoreTrailingWhitespacesInQuotes(boolean ignoreTrailingWhitespacesInQuotes) { this.ignoreTrailingWhitespacesInQuotes = ignoreTrailingWhitespacesInQuotes; } /** * Returns whether or not leading whitespaces from quoted values should be skipped (defaults to false) * * Note: if {@link #keepQuotes} evaluates to {@code true}, values won't be trimmed. * * @return true if leading whitespaces from quoted values should be skipped, false otherwise */ public boolean getIgnoreLeadingWhitespacesInQuotes() { return ignoreLeadingWhitespacesInQuotes; } /** * Defines whether or not leading whitespaces from quoted values should be skipped (defaults to false) * * Note: if {@link #keepQuotes} evaluates to {@code true}, values won't be trimmed. * * @param ignoreLeadingWhitespacesInQuotes whether leading whitespaces from quoted values should be skipped */ public void setIgnoreLeadingWhitespacesInQuotes(boolean ignoreLeadingWhitespacesInQuotes) { this.ignoreLeadingWhitespacesInQuotes = ignoreLeadingWhitespacesInQuotes; } /** * Configures the parser to trim any whitespaces around values extracted from within quotes. Shorthand for * {@link #setIgnoreLeadingWhitespacesInQuotes(boolean)} and {@link #setIgnoreTrailingWhitespacesInQuotes(boolean)} * * Note: if {@link #keepQuotes} evaluates to {@code true}, values won't be trimmed. * * @param trim a flag indicating whether whitespaces around values extracted from a quoted field should be removed */ public final void trimQuotedValues(boolean trim) { setIgnoreTrailingWhitespacesInQuotes(trim); setIgnoreLeadingWhitespacesInQuotes(trim); } /** * Returns the number of sample rows used in the CSV format auto-detection process (defaults to 20) * * @return the number of sample rows used in the CSV format auto-detection process */ public int getFormatDetectorRowSampleCount() { return formatDetectorRowSampleCount; } /** * Updates the number of sample rows used in the CSV format auto-detection process (defaults to 20) * * @param formatDetectorRowSampleCount the number of sample rows used in the CSV format auto-detection process */ public void setFormatDetectorRowSampleCount(int formatDetectorRowSampleCount) { this.formatDetectorRowSampleCount = formatDetectorRowSampleCount <= 0 ? 20 : formatDetectorRowSampleCount; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvRoutines.java000066400000000000000000000046761475274123300321440ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.routine.*; import java.io.*; /** * A collection of common routines involving the processing of CSV data. */ public class CsvRoutines extends AbstractRoutines { /** * Creates a new instance of the CSV routine class without any predefined parsing/writing configuration. */ public CsvRoutines() { this(null, null); } /** * Creates a new instance of the CSV routine class. * * @param parserSettings configuration to use for CSV parsing */ public CsvRoutines(CsvParserSettings parserSettings) { this(parserSettings, null); } /** * Creates a new instance of the CSV routine class. * * @param writerSettings configuration to use for CSV writing */ public CsvRoutines(CsvWriterSettings writerSettings) { this(null, writerSettings); } /** * Creates a new instance of the CSV routine class. * * @param parserSettings configuration to use for CSV parsing * @param writerSettings configuration to use for CSV writing */ public CsvRoutines(CsvParserSettings parserSettings, CsvWriterSettings writerSettings) { super("CSV parsing/writing routine", parserSettings, writerSettings); } @Override protected CsvParser createParser(CsvParserSettings parserSettings) { return new CsvParser(parserSettings); } @Override protected CsvWriter createWriter(Writer output, CsvWriterSettings writerSettings) { return new CsvWriter(output, writerSettings); } @Override protected CsvParserSettings createDefaultParserSettings() { return new CsvParserSettings(); } @Override protected CsvWriterSettings createDefaultWriterSettings() { return new CsvWriterSettings(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvWriter.java000066400000000000000000000340161475274123300315770ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import java.io.*; import java.nio.charset.*; import java.util.*; /** * A powerful and flexible CSV writer implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see CsvFormat * @see CsvWriterSettings * @see CsvParser * @see AbstractWriter */ public class CsvWriter extends AbstractWriter { private char delimiter; private char[] multiDelimiter; private char quoteChar; private char escapeChar; private char escapeEscape; private boolean quoteAllFields; private boolean escapeUnquoted; private boolean inputNotEscaped; private char newLine; private boolean dontProcessNormalizedNewLines; private boolean[] quotationTriggers; private char maxTrigger; private Set quotedColumns; private FieldSelector quotedFieldSelector; private boolean quoteNulls; /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. *

Important: by not providing an instance of {@link java.io.Writer} to this constructor, only the operations that write to Strings are * available.

* * @param settings the CSV writer configuration */ public CsvWriter(CsvWriterSettings settings) { this((Writer) null, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param writer the output resource that will receive CSV records produced by this class. * @param settings the CSV writer configuration */ public CsvWriter(Writer writer, CsvWriterSettings settings) { super(writer, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive CSV records produced by this class. * @param settings the CSV writer configuration */ public CsvWriter(File file, CsvWriterSettings settings) { super(file, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive CSV records produced by this class. * @param encoding the encoding of the file * @param settings the CSV writer configuration */ public CsvWriter(File file, String encoding, CsvWriterSettings settings) { super(file, encoding, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive CSV records produced by this class. * @param encoding the encoding of the file * @param settings the CSV writer configuration */ public CsvWriter(File file, Charset encoding, CsvWriterSettings settings) { super(file, encoding, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the CSV records produced by this class. * @param settings the CSV writer configuration */ public CsvWriter(OutputStream output, CsvWriterSettings settings) { super(output, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the CSV records produced by this class. * @param encoding the encoding of the stream * @param settings the CSV writer configuration */ public CsvWriter(OutputStream output, String encoding, CsvWriterSettings settings) { super(output, encoding, settings); } /** * The CsvWriter supports all settings provided by {@link CsvWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the CSV records produced by this class. * @param encoding the encoding of the stream * @param settings the CSV writer configuration */ public CsvWriter(OutputStream output, Charset encoding, CsvWriterSettings settings) { super(output, encoding, settings); } /** * Initializes the CSV writer with CSV-specific configuration * * @param settings the CSV writer configuration */ protected final void initialize(CsvWriterSettings settings) { CsvFormat format = settings.getFormat(); this.multiDelimiter = format.getDelimiterString().toCharArray(); if (multiDelimiter.length == 1) { delimiter = multiDelimiter[0]; multiDelimiter = null; } this.quoteChar = format.getQuote(); this.escapeChar = format.getQuoteEscape(); this.escapeEscape = settings.getFormat().getCharToEscapeQuoteEscaping(); this.newLine = format.getNormalizedNewline(); this.quoteAllFields = settings.getQuoteAllFields(); this.quoteNulls = settings.getQuoteNulls(); this.escapeUnquoted = settings.isEscapeUnquotedValues(); this.inputNotEscaped = !settings.isInputEscaped(); this.dontProcessNormalizedNewLines = !settings.isNormalizeLineEndingsWithinQuotes(); this.quotationTriggers = null; this.quotedColumns = null; this.maxTrigger = 0; quotedColumns = Collections.emptySet(); quotedFieldSelector = settings.getQuotedFieldSelector(); char[] sep = format.getLineSeparator(); int triggerCount = 3 + settings.getQuotationTriggers().length + sep.length; int offset = settings.isQuoteEscapingEnabled() ? 1 : 0; char[] tmp = Arrays.copyOf(settings.getQuotationTriggers(), triggerCount + offset); if (offset == 1) { tmp[triggerCount] = quoteChar; } tmp[triggerCount - 1] = '\n'; tmp[triggerCount - 2] = '\r'; tmp[triggerCount - 3] = newLine; tmp[triggerCount - 4] = sep[0]; if (sep.length > 1) { tmp[triggerCount - 5] = sep[1]; } for (int i = 0; i < tmp.length; i++) { if (maxTrigger < tmp[i]) { maxTrigger = tmp[i]; } } if (maxTrigger != 0) { maxTrigger++; this.quotationTriggers = new boolean[maxTrigger]; Arrays.fill(quotationTriggers, false); for (int i = 0; i < tmp.length; i++) { quotationTriggers[tmp[i]] = true; } } } @Override protected void processRow(Object[] row) { if (recordCount == 0L && quotedFieldSelector != null) { int[] quotedIndexes = quotedFieldSelector.getFieldIndexes(headers); if (quotedIndexes.length > 0) { quotedColumns = new HashSet(); for (int idx : quotedIndexes) { quotedColumns.add(idx); } } } for (int i = 0; i < row.length; i++) { if (i != 0) { if (multiDelimiter == null) { appendToRow(delimiter); } else { appendToRow(multiDelimiter); } } if (dontProcessNormalizedNewLines) { appender.enableDenormalizedLineEndings(false); } boolean allowTrim = allowTrim(i); String nextElement = getStringValue(row[i]); boolean quoteOn = quoteNulls || row[i] != null; int originalLength = appender.length(); boolean isElementQuoted = append(i, quoteOn && (quoteAllFields || quotedColumns.contains(i)), allowTrim, nextElement) && quoteOn; //skipped all whitespaces and wrote nothing if (appender.length() == originalLength && !usingNullOrEmptyValue) { if (isElementQuoted) { if (nextElement == null) { append(i, false, allowTrim, nullValue); } else { append(i, true, allowTrim, emptyValue); } } else if (nextElement == null) { append(i, false, allowTrim, nullValue); } else { append(i, false, allowTrim, emptyValue); } } if (isElementQuoted) { appendToRow(quoteChar); appendValueToRow(); appendToRow(quoteChar); if (dontProcessNormalizedNewLines) { appender.enableDenormalizedLineEndings(true); } } else { appendValueToRow(); } } } private boolean matchMultiDelimiter(String element, int from) { if (from + multiDelimiter.length - 2 >= element.length()) { return false; } for (int j = 1; j < multiDelimiter.length; j++, from++) { if (element.charAt(from) != multiDelimiter[j]) { return false; } } return true; } private boolean quoteElement(int start, String element) { final int length = element.length(); if (multiDelimiter == null) { if (maxTrigger == 0) { for (int i = start; i < length; i++) { char nextChar = element.charAt(i); if (nextChar == delimiter || nextChar == newLine) { return true; } } } else { for (int i = start; i < length; i++) { char nextChar = element.charAt(i); if (nextChar == delimiter || nextChar < maxTrigger && quotationTriggers[nextChar]) { return true; } } } } else { if (maxTrigger == 0) { for (int i = start; i < length; i++) { char nextChar = element.charAt(i); if ((nextChar == multiDelimiter[0] && matchMultiDelimiter(element, i + 1)) || nextChar == newLine) { return true; } } } else { for (int i = start; i < length; i++) { char nextChar = element.charAt(i); if ((nextChar == multiDelimiter[0] && matchMultiDelimiter(element, i + 1)) || nextChar < maxTrigger && quotationTriggers[nextChar]) { return true; } } } } return false; } private boolean append(int columnIndex, boolean isElementQuoted, boolean allowTrim, String element) { if (element == null) { if (nullValue == null) { return isElementQuoted; } element = nullValue; } int start = 0; if (allowTrim && this.ignoreLeading) { start = skipLeadingWhitespace(whitespaceRangeStart, element); } final int length = element.length(); if (start < length && (element.charAt(start) == quoteChar || columnIndex == 0 && element.charAt(0) == comment)) { isElementQuoted = true; } if (isElementQuoted) { if (usingNullOrEmptyValue && length >= 2) { if (element.charAt(0) == quoteChar && element.charAt(length - 1) == quoteChar) { appender.append(element); return false; } else { appendQuoted(start, allowTrim, element); return true; } } else { appendQuoted(start, allowTrim, element); return true; } } int i = start; char ch = '\0'; if (multiDelimiter == null) { for (; i < length; i++) { ch = element.charAt(i); if (ch == quoteChar || ch == delimiter || ch == escapeChar || (ch < maxTrigger && quotationTriggers[ch])) { appender.append(element, start, i); start = i + 1; if (ch == quoteChar || ch == escapeChar) { if (quoteElement(i, element)) { appendQuoted(i, allowTrim, element); return true; } else if (escapeUnquoted) { appendQuoted(i, allowTrim, element); } else { appender.append(element, i, length); if (allowTrim && ignoreTrailing && element.charAt(length - 1) <= ' ' && whitespaceRangeStart < element.charAt(length - 1)) { appender.updateWhitespace(); } } return isElementQuoted; } else if (ch == escapeChar && inputNotEscaped && escapeEscape != '\0' && escapeUnquoted) { appender.append(escapeEscape); } else if (ch == delimiter || ch < maxTrigger && quotationTriggers[ch]) { appendQuoted(i, allowTrim, element); return true; } appender.append(ch); } } } else { for (; i < length; i++) { ch = element.charAt(i); if (ch == quoteChar || (ch == multiDelimiter[0] && matchMultiDelimiter(element, i + 1)) || ch == escapeChar || (ch < maxTrigger && quotationTriggers[ch])) { appender.append(element, start, i); start = i + 1; if (ch == quoteChar || ch == escapeChar) { if (quoteElement(i, element)) { appendQuoted(i, allowTrim, element); return true; } else if (escapeUnquoted) { appendQuoted(i, allowTrim, element); } else { appender.append(element, i, length); if (allowTrim && ignoreTrailing && element.charAt(length - 1) <= ' ' && whitespaceRangeStart < element.charAt(length - 1)) { appender.updateWhitespace(); } } return isElementQuoted; } else if (ch == escapeChar && inputNotEscaped && escapeEscape != '\0' && escapeUnquoted) { appender.append(escapeEscape); } else if ((ch == multiDelimiter[0] && matchMultiDelimiter(element, i + 1)) || ch < maxTrigger && quotationTriggers[ch]) { appendQuoted(i, allowTrim, element); return true; } appender.append(ch); } } } appender.append(element, start, i); if (allowTrim && ch <= ' ' && ignoreTrailing && whitespaceRangeStart < ch) { appender.updateWhitespace(); } return isElementQuoted; } private void appendQuoted(int start, boolean allowTrim, String element) { final int length = element.length(); int i = start; char ch = '\0'; for (; i < length; i++) { ch = element.charAt(i); if (ch == quoteChar || ch == newLine || ch == escapeChar) { appender.append(element, start, i); start = i + 1; if (ch == quoteChar && inputNotEscaped) { appender.append(escapeChar); } else if (ch == escapeChar && inputNotEscaped && escapeEscape != '\0') { appender.append(escapeEscape); } appender.append(ch); } } appender.append(element, start, i); if (allowTrim && ch <= ' ' && ignoreTrailing && whitespaceRangeStart < ch) { appender.updateWhitespace(); } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/CsvWriterSettings.java000066400000000000000000000347001475274123300333200ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; import com.univocity.parsers.common.fields.*; import java.util.*; /** * This is the configuration class used by the CSV writer ({@link CsvWriter}) * *

In addition to the configuration options provided by {@link CommonWriterSettings}, the CsvWriterSettings include: * *

    *
  • emptyValue (defaults to null): Defines a replacement string to signify an empty value (which is not a null value) *

    If the writer has an empty String to write to the output, the emptyValue is used instead of an empty string

  • *
  • quoteAllFields (defaults to false): By default, only values that contain a field separator are enclosed within quotes. *

    If this property is set to true, this indicates that all written values should be enclosed within quotes (as defined in {@link CsvFormat})

  • *
* * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.csv.CsvWriter * @see com.univocity.parsers.csv.CsvFormat * @see com.univocity.parsers.common.CommonWriterSettings */ public class CsvWriterSettings extends CommonWriterSettings { private boolean escapeUnquotedValues = false; private boolean quoteAllFields = false; private boolean isInputEscaped = false; private boolean normalizeLineEndingsWithinQuotes = true; private char[] quotationTriggers = new char[0]; private boolean quoteEscapingEnabled = false; private boolean quoteNulls = true; private FieldSelector quotedFieldSelector = null; /** * Indicates that all written values should be enclosed within quotes (as defined in {@link CsvFormat}) *

(Defaults to false) * * @return true if all written values should be enclosed within quotes, false otherwise */ public boolean getQuoteAllFields() { return quoteAllFields; } /** * Indicates indicates whether or not all written values should be enclosed within quotes (as defined in {@link CsvFormat}) * *

(Defaults to false) *

By default, only values that contain a field separator are enclosed within quotes. * * @param quoteAllFields a flag indicating whether to enclose all fields within quotes */ public void setQuoteAllFields(boolean quoteAllFields) { this.quoteAllFields = quoteAllFields; } /** * Indicates whether escape sequences should be written in unquoted values. Defaults to {@code false}. * *

By default, this is disabled and if the input is {@code A""B,C}, the resulting value will be * {@code [A""B] and [C]} (i.e. the content is written as-is). However, if the writer is configured * to process escape sequences in unquoted values, the values will be written as {@code [A""""B] and [C]}

* * @return true if escape sequences should be processed in unquoted values, otherwise false */ public boolean isEscapeUnquotedValues() { return escapeUnquotedValues; } /** * Configures the writer to process escape sequences in unquoted values. Defaults to {@code false}. * *

By default, this is disabled and if the input is {@code A""B,C}, the result will be written as * {@code [A""B] and [C]} (i.e. the quotes written as-is). However, if the writer is configured * to process escape sequences in unquoted values, the values will written as {@code [A""""B] and [C]}

* * @param escapeUnquotedValues a flag indicating whether escape sequences should be processed in unquoted values */ public void setEscapeUnquotedValues(boolean escapeUnquotedValues) { this.escapeUnquotedValues = escapeUnquotedValues; } /** * Indicates that the user will provide escaped input, and the writer will not try to introduce escape sequences. The input will be written as-is. *

Warning! ensure your data is properly escaped, otherwise the writer will produce invalid CSV.

*

This is disabled by default

* * @return a flag indicating whether the escape sequences should not be introduced by the writer. */ public final boolean isInputEscaped() { return isInputEscaped; } /** * Configures the writer to prevent it to introduce escape sequences. The writer will assume the user is providing escaped input, and it will be written * as-is. *

Warning! ensure your data is properly escaped, otherwise the writer will produce invalid CSV.

*

This is disabled by default

* * @param isInputEscaped a flag indicating whether the input that will be written is already properly escaped. */ public final void setInputEscaped(boolean isInputEscaped) { this.isInputEscaped = isInputEscaped; } /** * Flag indicating whether the writer should replace the the normalized line separator character specified in {@link Format#getNormalizedNewline()} * by the sequence specified in {@link Format#getLineSeparator()}, when the value is enclosed within quotes. * * This is enabled by default and is used to ensure data be read on any platform without introducing unwanted blank lines. * * For example, consider the quoted value {@code "Line1 \n Line2"}. If this is written using {@code "\r\n"} as * the line separator sequence, and the normalized new line is set to {@code '\n'} (the default), the output will be: * * {@code [Line1 \r\n Line2]} * * However, if the value is meant to be kept untouched, and the original line separator should be maintained, set * the {@link #normalizeLineEndingsWithinQuotes} to {@code false}. This will make the writer output the value as-is, producing: * * {@code [Line1 \n Line2]} * * @return {@code true} if line separator characters in quoted values should be considered 'normalized' and replaced by the * sequence specified in {@link Format#getLineSeparator()}, {@code false} otherwise */ public boolean isNormalizeLineEndingsWithinQuotes() { return normalizeLineEndingsWithinQuotes; } /** * Flag indicating whether the writer should replace the the normalized line separator character specified in {@link Format#getNormalizedNewline()} * by the sequence specified in {@link Format#getLineSeparator()}, when the value is enclosed within quotes. * * This is enabled by default and is used to ensure data can be used on any platform without producing unrecognized line endings. * * For example, consider the quoted value {@code "Line1 \n Line2"}. If this is written using {@code "\r\n"} as * the line separator sequence, and the normalized new line is set to {@code '\n'} (the default), the output will be: * * {@code [Line1 \r\n Line2]} * * However, if the value is meant to be kept untouched, and the original line separator should be maintained, set * the {@link #normalizeLineEndingsWithinQuotes} to {@code false}. This will make the writer output the value as-is, producing: * * {@code [Line1 \n Line2]} * * @param normalizeLineEndingsWithinQuotes flag indicating that line separator characters in quoted values should be * considered 'normalized' and occurrences of {@link Format#getNormalizedNewline()} * should be replaced by the sequence specified in {@link Format#getLineSeparator()} */ public void setNormalizeLineEndingsWithinQuotes(boolean normalizeLineEndingsWithinQuotes) { this.normalizeLineEndingsWithinQuotes = normalizeLineEndingsWithinQuotes; } /** * Returns the default CsvFormat configured to produce CSV outputs compliant to the RFC4180 standard. * * @return and instance of CsvFormat configured to produce CSV outputs compliant to the RFC4180 standard. */ @Override protected CsvFormat createDefaultFormat() { return new CsvFormat(); } /** * Returns the list of characters that when present in a value to be written, will * force the output value to be enclosed in quotes. * * @return the characters that will trigger values to be quoted when present in a value to be written. */ public char[] getQuotationTriggers() { return quotationTriggers; } /** * Defines one or more "triggers" for enclosing a value within quotes. If one of the characters in the quotation trigger * list is found in a value to be written, the entire value will be enclosed in quotes. * * @param quotationTriggers a list of characters that when present in a value to be written, will * force the output value to be enclosed in quotes. */ public void setQuotationTriggers(char... quotationTriggers) { this.quotationTriggers = quotationTriggers == null ? new char[0] : quotationTriggers; } /** * Queries if a given character is a quotation trigger, i.e. a character that if present in a value to be written, * will make the CSV writer enclose the entire value within quotes. * * @param ch the character to be tested * * @return {@code true} if the given character is a quotation trigger, {@code false} otherwise. */ public boolean isQuotationTrigger(char ch) { for (int i = 0; i < quotationTriggers.length; i++) { if (quotationTriggers[i] == ch) { return true; } } return false; } /** * Indicates whether the CSV writer should escape values that contain the quote character, by enclosing the entire * value in quotes. * * For example, consider a value such as {@code [My "precious" value]}. * When quote escaping is enabled, the output will be: * * {@code ["My ""precious"" value"]} * * If disabled (the default), the value will be written as-is. Note that the CSV output will not conform to the RFC 4180 standard, * but it will still be valid as the value does not contain line separators nor the delimiter character. * * @return a flag indicating whether values containing quotes should be enclosed in quotes. */ public boolean isQuoteEscapingEnabled() { return quoteEscapingEnabled; } /** * Configures the CSV writer to escape values that contain the quote character, by enclosing the entire * value in quotes. * * For example, consider a value such as {@code [My "precious" value]}. * When quote escaping is enabled, the output will be: * * {@code ["My ""precious"" value"]} * * If disabled (the default), the value will be written as-is. Note that the CSV output will not conform to the RFC 4180 standard, * but it will still be valid as the value does not contain line separators nor the delimiter character. * * @param quoteEscapingEnabled a flag indicating whether values containing quotes should be enclosed in quotes. */ public void setQuoteEscapingEnabled(boolean quoteEscapingEnabled) { this.quoteEscapingEnabled = quoteEscapingEnabled; } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); out.put("Quote all fields", quoteAllFields); out.put("Escape unquoted values", escapeUnquotedValues); out.put("Normalize escaped line separators", normalizeLineEndingsWithinQuotes); out.put("Input escaped", isInputEscaped); out.put("Quote escaping enabled", quoteEscapingEnabled); out.put("Quotation triggers", Arrays.toString(quotationTriggers)); } @Override public final CsvWriterSettings clone() { return (CsvWriterSettings) super.clone(); } @Override public final CsvWriterSettings clone(boolean clearInputSpecificSettings) { return (CsvWriterSettings) super.clone(clearInputSpecificSettings); } /** * Returns the current selection of quoted fields (if any) * * @return the current selection of quoted fields */ final FieldSelector getQuotedFieldSelector() { return quotedFieldSelector; } /** * Replaces the current quoted field selection * * @param fieldSet the new set of selected fields * @param values the values to include to the selection * * @return the set of selected fields given in as a parameter. */ private FieldSet setFieldSet(FieldSet fieldSet, T... values) { this.quotedFieldSelector = (FieldSelector) fieldSet; fieldSet.add(values); return fieldSet; } /** * Selects fields whose values should always be written within quotes * * @param columns a selection of columns that will always be quoted * * @return the (modifiable) set of selected fields to be quoted. */ public final FieldSet quoteFields(Enum... columns) { return setFieldSet(new FieldEnumSelector(), columns); } /** * Selects fields whose values should always be written within quotes * * @param columns a selection of columns that will always be quoted * * @return the (modifiable) set of selected fields to be quoted. */ public final FieldSet quoteFields(String... columns) { return setFieldSet(new FieldNameSelector(), columns); } /** * Selects field positions whose values should always be written within quotes * * @param columns a selection of column indexes that will always be quoted * * @return the (modifiable) set of column positions to be quoted. */ public final FieldSet quoteIndexes(Integer... columns) { return setFieldSet(new FieldIndexSelector(), columns); } /** * Configures whether to quote {@code null} values sent to the {@link CsvWriter} when the corresponding column * is configured to be quoted via {@link #quoteFields(String...)}, or {@link #getQuoteAllFields()} evaluates to {@code true}. * * @param quoteNulls flag indicating whether {@code null} values should be quoted. */ public void setQuoteNulls(boolean quoteNulls) { this.quoteNulls = quoteNulls; } /** * Flag whether to quote {@code null} values sent to the {@link CsvWriter} when the corresponding column * is configured to be quoted via {@link #quoteFields(String...)}, or {@link #getQuoteAllFields()} evaluates to {@code true}. * * @return a flag indicating whether {@code null} values should be quoted. */ public boolean getQuoteNulls() { return quoteNulls; } } UnescapedQuoteHandling.java000066400000000000000000000052751475274123300341670ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/csv/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.common.*; /** * This enumeration is used to determine how the ({@link CsvParser}) will handle values with unescaped quotes. * * Use {@link CsvParserSettings#setUnescapedQuoteHandling(UnescapedQuoteHandling)} to configure the appropriate * handling of unescaped quotes on your input. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.csv.CsvParserSettings * @see com.univocity.parsers.csv.CsvFormat * @see com.univocity.parsers.csv.CsvParser * @see com.univocity.parsers.common.CommonParserSettings */ public enum UnescapedQuoteHandling { /** * If unescaped quotes are found in the input, accumulate the quote character and proceed parsing the value * as a quoted value, until a closing quote is found. */ STOP_AT_CLOSING_QUOTE, /** * If unescaped quotes are found in the input, consider the value as an unquoted value. This will make the parser * accumulate all characters of the current parsed value until the delimiter defined by {@link CsvFormat#getDelimiter()} is found. * If no delimiter is found in the value, the parser will continue accumulating characters from the input * until a delimiter or line ending is found. */ BACK_TO_DELIMITER, /** * If unescaped quotes are found in the input, consider the value as an unquoted value. This will make the parser * accumulate all characters until the delimiter defined by {@link CsvFormat#getDelimiter()}, or a line ending is found in the input. */ STOP_AT_DELIMITER, /** * If unescaped quotes are found in the input, the content parsed for the given value will be skipped * (until the next delimiter is found) and the value set in {@link CommonSettings#getNullValue()} will be produced instead. */ SKIP_VALUE, /** * If unescaped quotes are found in the input, a {@link TextParsingException} will be thrown. */ RAISE_ERROR, } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/000077500000000000000000000000001475274123300273045ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/FieldAlignment.java000066400000000000000000000035211475274123300330320ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; /** * Alignment of text in a fixed-width field. * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public enum FieldAlignment { /** * Aligns values to the left */ LEFT, /** * Centralizes values */ CENTER, /** * Aligns values to the right */ RIGHT; /** * Calculates how many whites paces to introduce before a value so it is printed as specified by the alignment type. * @param totalLength the total length available to write for a given field * @param lengthToWrite the length of a value that will be written to the field * @return the number of whites paces to introduce in before the value to make it align as specified. */ public int calculatePadding(int totalLength, int lengthToWrite) { if (this == LEFT || totalLength <= lengthToWrite) { return 0; } if (this == RIGHT) { return totalLength - lengthToWrite; } int padding = (totalLength / 2) - (lengthToWrite / 2); if (lengthToWrite + padding > totalLength) { padding--; } return padding; } } FixedWidthFieldLengths.java000066400000000000000000000052341475274123300344240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import java.util.*; /** * This class provides the name, length, alignment and padding of each field in a fixed-width record. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @deprecated This class has been modified over time and its name became misleading. Use {@link FixedWidthFields} instead. */ @Deprecated public class FixedWidthFieldLengths extends FixedWidthFields { /** * Defines a sequence of field names used to refer to columns in the input/output text of an entity, along with their lengths. * The field names defined will be used as headers, having the same effect of a call to {@link FixedWidthParserSettings#setHeaders(String...)}. * * @param fields a {@link LinkedHashMap} containing the sequence of fields to be associated with each column in the input/output, with their respective length. */ public FixedWidthFieldLengths(LinkedHashMap fields) { super(fields); } /** * Defines a sequence of field names used to refer to columns in the input/output text of an entity, along with their lengths. * The field names defined will be used as headers, having the same effect of a call to {@link FixedWidthParserSettings#setHeaders(String...)}. * * @param headers the sequence of fields to be associated with each column in the input/output * @param lengths the sequence of lengths to be associated with each given header. The size of this array must match the number of given headers. */ public FixedWidthFieldLengths(String[] headers, int[] lengths) { super(headers, lengths); } /** * Creates a new instance initialized with the lengths of all fields in a fixed-width record. * * @param fieldLengths The number lengths of all fields in a fixed-width record. All lengths must be greater than 0. */ public FixedWidthFieldLengths(int... fieldLengths) { super(fieldLengths); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/FixedWidthFields.java000066400000000000000000000753621475274123300333520ustar00rootroot00000000000000/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import java.util.*; import java.util.Map.*; /** * This class provides the name, length, alignment and padding of each field in a fixed-width record. * * @author Univocity Software Pty Ltd - parsers@univocity.com */ public class FixedWidthFields implements Cloneable { private List fieldLengths = new ArrayList(); private List fieldsToIgnore = new ArrayList(); private List fieldNames = new ArrayList(); private List fieldAlignment = new ArrayList(); private List fieldPadding = new ArrayList(); private List paddingsToKeep = new ArrayList(); private boolean noNames = true; private int totalLength = 0; /** * Defines a sequence of field names used to refer to columns in the input/output text of an entity, along with their lengths. * The field names defined will be used as headers, having the same effect of a call to {@link FixedWidthParserSettings#setHeaders(String...)}. * * @param fields a {@link LinkedHashMap} containing the sequence of fields to be associated with each column in the input/output, with their respective length. */ public FixedWidthFields(LinkedHashMap fields) { if (fields == null || fields.isEmpty()) { throw new IllegalArgumentException("Map of fields and their lengths cannot be null/empty"); } for (Entry entry : fields.entrySet()) { String fieldName = entry.getKey(); Integer fieldLength = entry.getValue(); addField(fieldName, fieldLength); } } /** * Defines a sequence of field names used to refer to columns in the input/output text of an entity, along with their lengths. * The field names defined will be used as headers, having the same effect of a call to {@link FixedWidthParserSettings#setHeaders(String...)}. * * @param headers the sequence of fields to be associated with each column in the input/output * @param lengths the sequence of lengths to be associated with each given header. The size of this array must match the number of given headers. */ public FixedWidthFields(String[] headers, int[] lengths) { if (headers == null || headers.length == 0) { throw new IllegalArgumentException("Headers cannot be null/empty"); } if (lengths == null || lengths.length == 0) { throw new IllegalArgumentException("Field lengths cannot be null/empty"); } if (headers.length != lengths.length) { throw new IllegalArgumentException("Sequence of headers and their respective lengths must match. Got " + headers.length + " headers but " + lengths.length + " lengths"); } for (int i = 0; i < headers.length; i++) { addField(headers[i], lengths[i]); } } /** * Creates a new instance initialized with the lengths of all fields in a fixed-width record. * * @param fieldLengths The number lengths of all fields in a fixed-width record. All lengths must be greater than 0. */ public FixedWidthFields(int... fieldLengths) { for (int i = 0; i < fieldLengths.length; i++) { addField(fieldLengths[i]); } } /** * Creates a new instance initialized from {@link FixedWidth} annotations in the fields and methods of a given class. Note that * all fields should additionally have the {@link Parsed} annotation to configure header names and/or their positions. * * @param beanClass the class whose {@link FixedWidth} annotations will be processed to configure this field list. * * @deprecated use {@link #forParsing(Class)} and {@link #forWriting(Class)} to initialize the fields from the given * class and filter out getters and setters that target the same field. If the given class has any annotated methods * only the setters will be used, making it usable only for parsing. */ @Deprecated public FixedWidthFields(Class beanClass) { this(beanClass, MethodFilter.ONLY_SETTERS); } /** * Creates a new instance initialized from {@link FixedWidth} annotations in the fields and methods of a given class. Note that * all fields should additionally have the {@link Parsed} annotation to configure header names and/or their positions. * * Only setter methods will be considered as fields. * * @param beanClass the class whose {@link FixedWidth} annotations will be processed to configure this field list. * * @return a new {@link FixedWidthFields} instance built with the {@link FixedWidth} annotations found in the given class' attributes and methods (excluding getters) */ public static FixedWidthFields forParsing(Class beanClass) { return new FixedWidthFields(beanClass, MethodFilter.ONLY_SETTERS); } /** * Creates a new instance initialized from {@link FixedWidth} annotations in the fields and methods of a given class. Note that * all fields should additionally have the {@link Parsed} annotation to configure header names and/or their positions. * * Only getter methods will be considered as fields. * * @param beanClass the class whose {@link FixedWidth} annotations will be processed to configure this field list. * * @return a new {@link FixedWidthFields} instance built with the {@link FixedWidth} annotations found in the given class' attributes and methods (excluding setters) */ public static FixedWidthFields forWriting(Class beanClass) { return new FixedWidthFields(beanClass, MethodFilter.ONLY_GETTERS); } /** * Creates a new instance initialized from {@link FixedWidth} annotations in the fields of a given class. Note that * all fields should additionally have the {@link Parsed} annotation to configure header names and/or their positions. * * @param beanClass the class whose {@link FixedWidth} annotations will be processed to configure this field list. * @param methodFilter filter to apply over annotated methods when the fixed-width writer is reading data from beans (to write values to an output) * or writing values into beans (when parsing). It is used to choose either a "get" or a "set" * method annotated with {@link Parsed}, when both methods target the same field. */ private FixedWidthFields(Class beanClass, MethodFilter methodFilter) { if (beanClass == null) { throw new IllegalArgumentException("Class must not be null."); } List fieldSequence = AnnotationHelper.getFieldSequence(beanClass, true, null, methodFilter); if (fieldSequence.isEmpty()) { throw new IllegalArgumentException("Can't derive fixed-width fields from class '" + beanClass.getName() + "'. No @Parsed annotations found."); } Set fieldNamesWithoutConfig = new LinkedHashSet(); for (TransformedHeader field : fieldSequence) { if (field == null) { continue; } String fieldName = field.getHeaderName(); FixedWidth fw = AnnotationHelper.findAnnotation(field.getTarget(), FixedWidth.class); if (fw == null) { fieldNamesWithoutConfig.add(field.getTargetName()); continue; } int length = AnnotationRegistry.getValue(field.getTarget(), fw, "value", fw.value()); int from = AnnotationRegistry.getValue(field.getTarget(), fw, "from", fw.from()); int to = AnnotationRegistry.getValue(field.getTarget(), fw, "to", fw.to()); FieldAlignment alignment = AnnotationRegistry.getValue(field.getTarget(), fw, "alignment", fw.alignment()); char padding = AnnotationRegistry.getValue(field.getTarget(), fw, "padding", fw.padding()); if (length != -1) { if (from != -1 || to != -1) { throw new IllegalArgumentException("Can't initialize fixed-width field from " + field.describe() + ". " + "Can't have field length (" + length + ") defined along with position from (" + from + ") and to (" + to + ")"); } addField(fieldName, length, alignment, padding); } else if (from != -1 && to != -1) { addField(fieldName, from, to, alignment, padding); } else { throw new IllegalArgumentException("Can't initialize fixed-width field from " + field.describe() + "'. " + "Field length/position undefined defined"); } boolean keepPadding = AnnotationRegistry.getValue(field.getTarget(), fw, "keepPadding", fw.keepPadding()); setKeepPaddingFlag(keepPadding, fieldLengths.size() - 1); } if (fieldNamesWithoutConfig.size() > 0) { throw new IllegalArgumentException("Can't derive fixed-width fields from class '" + beanClass.getName() + "'. " + "The following fields don't have a @FixedWidth annotation: " + fieldNamesWithoutConfig); } } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param startPosition starting position of the field. * @param endPosition ending position of the field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int startPosition, int endPosition) { return addField(null, startPosition, endPosition, FieldAlignment.LEFT, '\0'); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param name the name of the next field. It is not validated. * @param startPosition starting position of the field. * @param endPosition ending position of the field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int startPosition, int endPosition) { return addField(name, startPosition, endPosition, FieldAlignment.LEFT, '\0'); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param name the name of the next field. It is not validated. * @param startPosition starting position of the field. * @param endPosition ending position of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int startPosition, int endPosition, char padding) { return addField(name, startPosition, endPosition, FieldAlignment.LEFT, padding); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param name the name of the next field. It is not validated. * @param startPosition starting position of the field. * @param endPosition ending position of the field * @param alignment the alignment of the field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int startPosition, int endPosition, FieldAlignment alignment) { return addField(name, startPosition, endPosition, alignment, '\0'); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param startPosition starting position of the field. * @param endPosition ending position of the field * @param alignment the alignment of the field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int startPosition, int endPosition, FieldAlignment alignment) { return addField(null, startPosition, endPosition, alignment, '\0'); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param startPosition starting position of the field. * @param endPosition ending position of the field * @param alignment the alignment of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int startPosition, int endPosition, FieldAlignment alignment, char padding) { return addField(null, startPosition, endPosition, alignment, padding); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param startPosition starting position of the field. * @param endPosition ending position of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int startPosition, int endPosition, char padding) { return addField(null, startPosition, endPosition, FieldAlignment.LEFT, padding); } /** * Adds the range of the next field in a fixed-width record. The given range cannot overlap with previously defined fields. * Blanks will be used to fill any "gap" between record ranges when writing. * * @param name the name of the next field. It is not validated. * @param startPosition starting position of the field. * @param endPosition ending position of the field * @param alignment the alignment of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int startPosition, int endPosition, FieldAlignment alignment, char padding) { int length = endPosition - startPosition; if (startPosition < totalLength) { throw new IllegalArgumentException("Start position '" + startPosition + "' overlaps with one or more fields"); } else if (startPosition > totalLength) { addField(null, startPosition - totalLength, FieldAlignment.LEFT, '\0'); fieldsToIgnore.set(fieldsToIgnore.size() - 1, Boolean.TRUE); } return addField(name, length, alignment, padding); } /** * Returns the sequence of fields to ignore. * * @return the sequence of fields to ignore. */ boolean[] getFieldsToIgnore() { boolean[] out = new boolean[fieldsToIgnore.size()]; for (int i = 0; i < fieldsToIgnore.size(); i++) { out[i] = fieldsToIgnore.get(i).booleanValue(); } return out; } /** * Returns the sequence of fields whose padding character must/must not be retained in the parsed value * @return the sequence that have an explicit 'keepPadding' flag. */ Boolean[] getKeepPaddingFlags() { return paddingsToKeep.toArray(new Boolean[0]); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField(5).addField(6)... * * @param length the length of the next field. It must be greater than 0. * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int length) { return addField(null, length, FieldAlignment.LEFT, '\0'); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField(5).addField(6)... * * @param length the length of the next field. It must be greater than 0. * @param alignment the alignment of the field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int length, FieldAlignment alignment) { return addField(null, length, alignment, '\0'); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField("field_1", 5).addField("field_2", 6)... * * @param name the name of the next field. It is not validated. * @param length the length of the next field. It must be greater than 0. * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int length) { return addField(name, length, FieldAlignment.LEFT, '\0'); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField("field_1", 5).addField("field_2", 6)... * * @param name the name of the next field. It is not validated. * @param length the length of the next field. It must be greater than 0. * @param alignment the alignment of the field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int length, FieldAlignment alignment) { return addField(name, length, alignment, '\0'); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField(5).addField(6)... * * @param length the length of the next field. It must be greater than 0. * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int length, char padding) { return addField(null, length, FieldAlignment.LEFT, padding); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField(5).addField(6)... * * @param length the length of the next field. It must be greater than 0. * @param alignment the alignment of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(int length, FieldAlignment alignment, char padding) { return addField(null, length, alignment, padding); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField("field_1", 5).addField("field_2", 6)... * * @param name the name of the next field. It is not validated. * @param length the length of the next field. It must be greater than 0. * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int length, char padding) { return addField(name, length, FieldAlignment.LEFT, padding); } /** * Adds the length of the next field in a fixed-width record. This method can be chained like this: addField("field_1", 5).addField("field_2", 6)... * * @param name the name of the next field. It is not validated. * @param length the length of the next field. It must be greater than 0. * @param alignment the alignment of the field * @param padding the representation of unused space in this field * * @return the FixedWidthFields instance itself for chaining. */ public FixedWidthFields addField(String name, int length, FieldAlignment alignment, char padding) { validateLength(name, length); fieldLengths.add(length); fieldsToIgnore.add(Boolean.FALSE); fieldNames.add(NormalizedString.valueOf(name)); fieldPadding.add(padding); paddingsToKeep.add(null); if (name != null) { noNames = false; } fieldAlignment.add(alignment); totalLength += length; return this; } private void validateLength(String name, int length) { if (length < 1) { if (name == null) { throw new IllegalArgumentException("Invalid field length: " + length + " for field at index " + fieldLengths.size()); } else { throw new IllegalArgumentException("Invalid field length: " + length + " for field " + name); } } } /** * Returns the number of fields in a fixed-width record * * @return the number of fields in a fixed-width record */ public int getFieldsPerRecord() { return fieldLengths.size(); } /** * Returns the name of each field in a fixed-width record, if any * * @return the name of each field in a fixed-width record, or null if no name has been defined. */ public NormalizedString[] getFieldNames() { if (noNames) { return null; } return getSelectedElements(fieldNames).toArray(ArgumentUtils.EMPTY_NORMALIZED_STRING_ARRAY); } private List getSelectedElements(List elements) { List out = new ArrayList(); for (int i = 0; i < elements.size(); i++) { if (!fieldsToIgnore.get(i)) { out.add(elements.get(i)); } } return out; } /** * Returns a copy of the sequence of field lengths of a fixed-width record * * @return a copy of the sequence of field lengths of a fixed-width record */ public int[] getFieldLengths() { return ArgumentUtils.toIntArray(getSelectedElements(fieldLengths)); } int[] getAllLengths() { return ArgumentUtils.toIntArray(fieldLengths); } /** * Modifies the length of a given field * * @param name the name of the field whose length must be altered * @param newLength the new length of the given field */ public void setFieldLength(String name, int newLength) { if (name == null) { throw new IllegalArgumentException("Field name cannot be null"); } int index = fieldNames.indexOf(name); if (index == -1) { throw new IllegalArgumentException("Cannot find field with name '" + name + '\''); } validateLength(name, newLength); fieldLengths.set(index, newLength); } /** * Modifies the length of a given field * * @param position the position of the field whose length must be altered * @param newLength the new length of the given field */ public void setFieldLength(int position, int newLength) { validateIndex(position); validateLength("at index " + position, newLength); fieldLengths.set(position, newLength); } /** * Applies alignment to a given list of fields * * @param alignment the alignment to apply * @param positions the positions of the fields that should be aligned */ public void setAlignment(FieldAlignment alignment, int... positions) { for (int position : positions) { setAlignment(position, alignment); } } /** * Applies alignment to a given list of fields * * @param alignment the alignment to apply * @param names the names of the fields that should be aligned */ public void setAlignment(FieldAlignment alignment, String... names) { for (String name : names) { int position = indexOf(name); setAlignment(position, alignment); } } private void validateIndex(int position) { if (position < 0 && position >= fieldLengths.size()) { throw new IllegalArgumentException("No field defined at index " + position); } } /** * Returns the index of a field name. An {@code IllegalArgumentException} will be thrown if no names have been defined. * * @param fieldName the name of the field to be searched * * @return the index of the field, or -1 if it does not exist. */ public int indexOf(String fieldName) { if (noNames) { throw new IllegalArgumentException("No field names defined"); } if (fieldName == null || fieldName.trim().isEmpty()) { throw new IllegalArgumentException("Field name cannot be null/empty"); } NormalizedString normalizedFieldName = NormalizedString.valueOf(fieldName); int i = 0; for (NormalizedString name : this.fieldNames) { if (name.equals(normalizedFieldName)) { return i; } i++; } return -1; } private void setAlignment(int position, FieldAlignment alignment) { if (alignment == null) { throw new IllegalArgumentException("Alignment cannot be null"); } validateIndex(position); this.fieldAlignment.set(position, alignment); } /** * Returns the alignment of a given field. * * @param position the index of the field whose alignment will be returned * * @return the alignment of the field */ public FieldAlignment getAlignment(int position) { validateIndex(position); return fieldAlignment.get(position); } /** * Returns the alignment of a given field. An {@code IllegalArgumentException} will be thrown if no names have been defined. * * @param fieldName the name of the field whose alignment will be returned * * @return the alignment of the given field */ public FieldAlignment getAlignment(String fieldName) { int index = indexOf(fieldName); if (index == -1) { throw new IllegalArgumentException("Field '" + fieldName + "' does not exist. Available field names are: " + this.fieldNames); } return getAlignment(index); } /** * Returns a copy of the sequence of alignment settings to apply over each field in the fixed-width record. * * @return the sequence of alignment settings to apply over each field in the fixed-width record. */ public FieldAlignment[] getFieldAlignments() { return fieldAlignment.toArray(new FieldAlignment[fieldAlignment.size()]); } /** * Returns a copy of the sequence of padding characters to apply over each field in the fixed-width record. * * The null character ({@code '\0'}) is used to inform no padding has been explicitly set for a field, and that the * default padding character defined in {@link FixedWidthFormat#getPadding()} should be used. * * @return the sequence of padding characters to apply over each field in the fixed-width record. */ public char[] getFieldPaddings() { return ArgumentUtils.toCharArray(fieldPadding); } char[] getFieldPaddings(FixedWidthFormat format) { char[] out = getFieldPaddings(); for (int i = 0; i < out.length; i++) { if (out[i] == '\0') { out[i] = format.getPadding(); } } return out; } /** * Applies a custom padding character to a given list of fields * * @param padding the padding to apply * @param positions the positions of the fields that should use the given padding character */ public void setPadding(char padding, int... positions) { for (int position : positions) { setPadding(position, padding); } } /** * Applies a custom padding character to a given list of fields * * @param padding the padding to apply * @param names the names of the fields that should use the given padding character */ public void setPadding(char padding, String... names) { for (String name : names) { int position = indexOf(name); setPadding(position, padding); } } private void setPadding(int position, char padding) { if (padding == '\0') { throw new IllegalArgumentException("Cannot use the null character as padding"); } validateIndex(position); fieldPadding.set(position, padding); } /** * Configures a given list of fields to retain the padding character in any parsed values, * overriding the any default set for the whole input in {@link FixedWidthParserSettings#getKeepPadding()} * * @param position the positions of the fields that should keep the padding character * @param positions additional positions */ public void keepPaddingOn(int position, int... positions) { setKeepPaddingFlag(true, position, positions); } /** * Configures a given list of fields to retain the padding character in any parsed values, * overriding the any default set for the whole input in {@link FixedWidthParserSettings#getKeepPadding()} * * @param name the name of the first field that should keep the padding character * @param names the names of more fields that should keep the padding character */ public void keepPaddingOn(String name, String... names) { setKeepPaddingFlag(true, name, names); } /** * Configures a given list of fields to remove the padding character in any parsed values, * overriding the any default set for the whole input in {@link FixedWidthParserSettings#getKeepPadding()} * * @param position the positions of the fields that should keep the padding character * @param positions additional positions */ public void stripPaddingFrom(int position, int... positions) { setKeepPaddingFlag(false, position, positions); } /** * Configures a given list of fields to remove the padding character in any parsed values, * overriding the any default set for the whole input in {@link FixedWidthParserSettings#getKeepPadding()} * * @param name the name of the first field that have any padding characters removed * @param names the names of the fields that should have any padding characters removed */ public void stripPaddingFrom(String name, String... names) { setKeepPaddingFlag(false, name, names); } private void setKeepPaddingFlag(boolean keep, int position, int... positions) { setPaddingToKeep(position, keep); for (int p : positions) { setPaddingToKeep(p, keep); } } private void setKeepPaddingFlag(boolean keep, String name, String... names) { int position = indexOf(name); setPaddingToKeep(position, keep); for (String n : names) { position = indexOf(n); setPaddingToKeep(position, keep); } } private void setPaddingToKeep(int position, boolean keepPaddingFlag) { validateIndex(position); paddingsToKeep.set(position, keepPaddingFlag); } @Override public String toString() { StringBuilder out = new StringBuilder(); int i = 0; for (Integer length : fieldLengths) { out.append("\n\t\t").append(i + 1).append('\t'); if (i < fieldNames.size()) { out.append(fieldNames.get(i)); } out.append(", length: ").append(length); out.append(", align: ").append(fieldAlignment.get(i)); out.append(", padding: ").append(fieldPadding.get(i)); out.append(", keepPadding: ").append(paddingsToKeep.get(i)); i++; } return out.toString(); } static void setHeadersIfPossible(FixedWidthFields fieldLengths, CommonSettings settings) { if (fieldLengths != null && settings.getHeaders() == null) { NormalizedString[] headers = fieldLengths.getFieldNames(); if (headers != null) { int[] lengths = fieldLengths.getFieldLengths(); if (lengths.length == headers.length) { settings.setHeaders(NormalizedString.toArray(headers)); } } } } @Override protected FixedWidthFields clone() { try { FixedWidthFields out = (FixedWidthFields) super.clone(); out.fieldLengths = new ArrayList(fieldLengths); out.fieldNames = new ArrayList(fieldNames); out.fieldAlignment = new ArrayList(fieldAlignment); out.fieldPadding = new ArrayList(fieldPadding); out.paddingsToKeep = new ArrayList(paddingsToKeep); return out; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/FixedWidthFormat.java000066400000000000000000000070751475274123300333700ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.common.*; import java.util.*; /** * The Fixed-Width format configuration. In addition to the default configuration in {@link Format}, the fixed-width format defines: * *
    *
  • padding (defaults to ' '): the character used for filling unwritten spaces in a fixed-width record. *

    e.g. if a field has a length of 5 characters, but the value is 'ZZ', the field should contain [ZZ ] (i.e. ZZ followed by 3 unwritten spaces). *
    If the padding is set to '_', then the field will be written as [ZZ___]

  • *
* * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.common.Format */ public class FixedWidthFormat extends Format { private char padding = ' '; private char lookupWildcard = '?'; /** * Returns the padding character used to represent unwritten spaces. Defaults to ' ' * * @return the padding character */ public char getPadding() { return padding; } /** * Defines the padding character used to represent unwritten spaces. Defaults to ' ' * * @param padding the padding character */ public void setPadding(char padding) { this.padding = padding; } /** * Identifies whether or not a given character represents a padding character * * @param padding the character to be verified * * @return true if the given character is the padding character, false otherwise */ public boolean isPadding(char padding) { return this.padding == padding; } @Override protected TreeMap getConfiguration() { TreeMap out = new TreeMap(); out.put("Padding", padding); return out; } @Override public final FixedWidthFormat clone() { return (FixedWidthFormat) super.clone(); } /** * Returns the lookup wildcard character to accept any character in look-ahead or look-behind patterns defined * using {@link FixedWidthParserSettings#addFormatForLookahead(String, FixedWidthFields)} or * {@link FixedWidthParserSettings#addFormatForLookbehind(String, FixedWidthFields)}. * * Defaults to {@code '?'} * * @return the wildcard character to be used in lookahead/behind patterns. */ public char getLookupWildcard() { return lookupWildcard; } /** * Defines the lookup wildcard character to accept any character in look-ahead or look-behind patterns defined * using {@link FixedWidthParserSettings#addFormatForLookahead(String, FixedWidthFields)} or * {@link FixedWidthParserSettings#addFormatForLookbehind(String, FixedWidthFields)}. * * Defaults to {@code '?'} * * @param lookupWildcard the wildcard character to be used in lookahead/behind patterns. */ public void setLookupWildcard(char lookupWildcard) { this.lookupWildcard = lookupWildcard; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/FixedWidthParser.java000066400000000000000000000251611475274123300333700ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.*; import com.univocity.parsers.common.record.*; /** * A fast and flexible fixed-with parser implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see FixedWidthFormat * @see FixedWidthFields * @see FixedWidthParserSettings * @see FixedWidthWriter * @see AbstractParser */ public class FixedWidthParser extends AbstractParser { private int[] lengths; private int[] rootLengths; private boolean[] ignore; private boolean[] rootIgnore; private FieldAlignment[] alignments; private FieldAlignment[] rootAlignments; private char[] paddings; private char[] rootPaddings; private Boolean[] keepPaddingFlags; private Boolean[] rootKeepPaddingFlags; private final Lookup[] lookaheadFormats; private final Lookup[] lookbehindFormats; private Lookup lookupFormat; private Lookup lookbehindFormat; private int maxLookupLength; private final boolean skipToNewLine; private final boolean recordEndsOnNewLine; private final boolean skipEmptyLines; private final boolean keepPadding; private boolean useDefaultPadding; private final char defaultPadding; private char padding; private FieldAlignment alignment; private final char newLine; private int length; private boolean initializeLookaheadInput = false; private LookaheadCharInputReader lookaheadInput; private final char wildcard; /** * The FixedWidthParser supports all settings provided by {@link FixedWidthParserSettings}, and requires this configuration to be properly initialized. * * @param settings the parser configuration */ public FixedWidthParser(FixedWidthParserSettings settings) { super(settings); skipToNewLine = settings.getSkipTrailingCharsUntilNewline(); recordEndsOnNewLine = settings.getRecordEndsOnNewline(); skipEmptyLines = settings.getSkipEmptyLines(); lengths = settings.getAllLengths(); alignments = settings.getFieldAlignments(); paddings = settings.getFieldPaddings(); ignore = settings.getFieldsToIgnore(); keepPaddingFlags = settings.getKeepPaddingFlags(); keepPadding = settings.getKeepPadding(); lookaheadFormats = settings.getLookaheadFormats(); lookbehindFormats = settings.getLookbehindFormats(); wildcard = settings.getFormat().getLookupWildcard(); if (lookaheadFormats != null || lookbehindFormats != null) { initializeLookaheadInput = true; rootLengths = lengths; rootAlignments = alignments; rootPaddings = paddings; rootIgnore = ignore; rootKeepPaddingFlags = keepPaddingFlags; maxLookupLength = Lookup.calculateMaxLookupLength(lookaheadFormats, lookbehindFormats); } FixedWidthFormat format = settings.getFormat(); padding = format.getPadding(); defaultPadding = padding; newLine = format.getNormalizedNewline(); useDefaultPadding = settings.getUseDefaultPaddingForHeaders() && settings.isHeaderExtractionEnabled(); } @Override protected ParsingContext createParsingContext() { final ParsingContext context = super.createParsingContext(); if (lookaheadFormats != null || lookbehindFormats != null) { return new ParsingContextWrapper(context) { @Override public String[] headers() { return lookupFormat != null ? NormalizedString.toArray(lookupFormat.fieldNames) : super.headers(); } public Record toRecord(String[] row) { if (lookupFormat != null) { if (lookupFormat.context == null) { lookupFormat.initializeLookupContext(context, lookupFormat.fieldNames); } return lookupFormat.context.toRecord(row); } else { return super.toRecord(row); } } }; } else { return context; } } @Override protected void parseRecord() { if (ch == newLine && skipEmptyLines) { return; } boolean matched = false; if (lookaheadFormats != null || lookbehindFormats != null) { if (initializeLookaheadInput) { initializeLookaheadInput = false; this.lookaheadInput = new LookaheadCharInputReader(input, newLine, whitespaceRangeStart); this.input = lookaheadInput; } lookaheadInput.lookahead(maxLookupLength); if (lookaheadFormats != null) { for (int i = 0; i < lookaheadFormats.length; i++) { if (lookaheadInput.matches(ch, lookaheadFormats[i].value, wildcard)) { lengths = lookaheadFormats[i].lengths; alignments = lookaheadFormats[i].alignments; paddings = lookaheadFormats[i].paddings; ignore = lookaheadFormats[i].ignore; keepPaddingFlags = lookaheadFormats[i].keepPaddingFlags; lookupFormat = lookaheadFormats[i]; matched = true; break; } } if (lookbehindFormats != null && matched) { lookbehindFormat = null; for (int i = 0; i < lookbehindFormats.length; i++) { if (lookaheadInput.matches(ch, lookbehindFormats[i].value, wildcard)) { lookbehindFormat = lookbehindFormats[i]; break; } } } } else { for (int i = 0; i < lookbehindFormats.length; i++) { if (lookaheadInput.matches(ch, lookbehindFormats[i].value, wildcard)) { lookbehindFormat = lookbehindFormats[i]; matched = true; lengths = rootLengths; ignore = rootIgnore; keepPaddingFlags = rootKeepPaddingFlags; break; } } } if (!matched) { if (lookbehindFormat == null) { if (rootLengths == null) { throw new TextParsingException(context, "Cannot process input with the given configuration. No default field lengths defined and no lookahead/lookbehind value match '" + lookaheadInput.getLookahead(ch) + '\''); } lengths = rootLengths; alignments = rootAlignments; paddings = rootPaddings; ignore = rootIgnore; keepPaddingFlags = rootKeepPaddingFlags; lookupFormat = null; } else { lengths = lookbehindFormat.lengths; alignments = lookbehindFormat.alignments; paddings = lookbehindFormat.paddings; ignore = lookbehindFormat.ignore; keepPaddingFlags = lookbehindFormat.keepPaddingFlags; lookupFormat = lookbehindFormat; } } } int i; for (i = 0; i < lengths.length; i++) { final boolean ignorePadding = keepPaddingFlags[i] == null ? !keepPadding : !keepPaddingFlags[i]; length = lengths[i]; if (paddings != null) { padding = useDefaultPadding ? defaultPadding : paddings[i]; } if (alignments != null) { alignment = alignments[i]; } final boolean lastFieldOfRecord = (i + 1 >= lengths.length); if (ignorePadding) { skipPadding(lastFieldOfRecord); } if (ignoreLeadingWhitespace) { skipWhitespace(lastFieldOfRecord, ignorePadding); } if (recordEndsOnNewLine) { readValueUntilNewLine(ignorePadding); if (ch == newLine) { output.valueParsed(); useDefaultPadding = false; return; } } else if (length > 0) { readValue(ignorePadding); if (!lastFieldOfRecord) { ch = input.nextChar(); } } if (ignore[i]) { output.appender.reset(); } else { output.valueParsed(); } } if (skipToNewLine) { skipToNewLine(); } useDefaultPadding = false; } private void skipToNewLine() { try { while (ch != newLine) { ch = input.nextChar(); } } catch (EOFException e) { //ignore and let the EOF blow up again after the record is generated. } } private void skipPadding(boolean lastFieldOfRecord) { while (ch == padding && length-- > 0) { if (!lastFieldOfRecord || length > 0) { ch = input.nextChar(); } } } private void skipWhitespace(boolean lastFieldOfRecord, boolean ignorePadding) { while ((ch <= ' ' && whitespaceRangeStart < ch || ch == padding) && !(!ignorePadding && ch == padding) && length-- > 0) { if (!lastFieldOfRecord || length > 0) { ch = input.nextChar(); } } } private void readValueUntilNewLine(boolean ignorePadding) { if (ignoreTrailingWhitespace) { if (alignment == FieldAlignment.RIGHT) { while (length-- > 0 && ch != newLine) { output.appender.appendIgnoringWhitespace(ch); ch = input.nextChar(); } } else if (ignorePadding) { while (length-- > 0 && ch != newLine) { output.appender.appendIgnoringWhitespaceAndPadding(ch, padding); ch = input.nextChar(); } } else { while (length-- > 0 && ch != newLine) { output.appender.append(ch); ch = input.nextChar(); } } } else { if (alignment == FieldAlignment.RIGHT) { while (length-- > 0 && ch != newLine) { output.appender.append(ch); ch = input.nextChar(); } } else if (ignorePadding) { while (length-- > 0 && ch != newLine) { output.appender.appendIgnoringPadding(ch, padding); ch = input.nextChar(); } } else { while (length-- > 0 && ch != newLine) { output.appender.append(ch); ch = input.nextChar(); } } } } private void readValue(boolean ignorePadding) { length--; if (ignoreTrailingWhitespace) { if (alignment == FieldAlignment.RIGHT) { output.appender.appendIgnoringWhitespace(ch); while (length-- > 0) { output.appender.appendIgnoringWhitespace(ch = input.nextChar()); } } else if (ignorePadding) { output.appender.appendIgnoringWhitespaceAndPadding(ch, padding); while (length-- > 0) { output.appender.appendIgnoringWhitespaceAndPadding(ch = input.nextChar(), padding); } } else { output.appender.append(ch); while (length-- > 0) { output.appender.append(ch = input.nextChar()); } } } else { if (alignment == FieldAlignment.RIGHT) { output.appender.append(ch); while (length-- > 0) { output.appender.append(ch = input.nextChar()); } } else if (ignorePadding) { output.appender.appendIgnoringPadding(ch, padding); while (length-- > 0) { output.appender.appendIgnoringPadding(ch = input.nextChar(), padding); } } else { output.appender.append(ch); while (length-- > 0) { output.appender.append(ch = input.nextChar()); } } } } } FixedWidthParserSettings.java000066400000000000000000000436611475274123300350370ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.input.*; import java.util.*; /** * This is the configuration class used by the Fixed-Width parser ({@link FixedWidthParser}) * *

In addition to the configuration options provided by {@link CommonParserSettings}, the FixedWidthParserSettings include: * *

    *
  • skipTrailingCharsUntilNewline (defaults to {@code false}): Indicates whether or not any trailing characters beyond the record's length should be skipped until the newline is reached *

    For example, if the record length is 5, but the row contains "12345678\n", then portion containing "678" will be discarded and not considered part of the next record

  • *
  • recordEndsOnNewline (defaults to {@code false}): Indicates whether or not a record is considered parsed when a newline is reached. *

    For example, if recordEndsOnNewline is set to true, then given a record of length 4, and the input "12\n3456", the parser will identify [12] and [3456] *

    If recordEndsOnNewline is set to false, then given a record of length 4, and the input "12\n3456", the parser will identify a multi-line record [12\n3] and [456 ]

  • *
* *

The FixedWidthParserSettings need a definition of the field lengths of each record in the input. This must provided using an instance of {@link FixedWidthFields}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.fixed.FixedWidthParser * @see com.univocity.parsers.fixed.FixedWidthFormat * @see FixedWidthFields * @see com.univocity.parsers.common.CommonParserSettings */ public class FixedWidthParserSettings extends CommonParserSettings { protected boolean skipTrailingCharsUntilNewline = false; protected boolean recordEndsOnNewline = false; private boolean useDefaultPaddingForHeaders = true; private boolean keepPadding = false; private FixedWidthFields fieldLengths; private Map lookaheadFormats = new HashMap(); private Map lookbehindFormats = new HashMap(); /** * You can only create an instance of this class by providing a definition of the field lengths of each record in the input. *

This must provided using an instance of {@link FixedWidthFields}. * * @param fieldLengths the instance of {@link FixedWidthFields} which provides the lengths of each field in the fixed-width records to be parsed * * @see FixedWidthFields */ public FixedWidthParserSettings(FixedWidthFields fieldLengths) { if (fieldLengths == null) { throw new IllegalArgumentException("Field lengths cannot be null"); } this.fieldLengths = fieldLengths; NormalizedString[] names = fieldLengths.getFieldNames(); if (names != null) { setHeaders(NormalizedString.toArray(names)); } } /** * Creates a basic configuration object for the Fixed-Width parser with no field length configuration. * This constructor is intended to be used when the record length varies depending of the input row. * Refer to {@link #addFormatForLookahead(String, FixedWidthFields)}, {@link #addFormatForLookbehind(String, FixedWidthFields)} */ public FixedWidthParserSettings() { fieldLengths = null; } /** * Returns the sequence of lengths to be read by the parser to form a record. * * @return the sequence of lengths to be read by the parser to form a record. */ int[] getFieldLengths() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldLengths(); } int[] getAllLengths() { if (fieldLengths == null) { return null; } return fieldLengths.getAllLengths(); } /** * Returns the sequence of paddings used by each field of each record. * * @return the sequence of paddings used by each field of each record. */ char[] getFieldPaddings() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldPaddings(this.getFormat()); } /** * Returns the sequence of fields to ignore. * * @return the sequence of fields to ignore. */ boolean[] getFieldsToIgnore() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldsToIgnore(); } /** * Returns the sequence of alignments to consider for each field of each record. * * @return the sequence of alignments to consider for each field of each record. */ FieldAlignment[] getFieldAlignments() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldAlignments(); } /** * Indicates whether or not any trailing characters beyond the record's length should be skipped until the newline is reached (defaults to {@code false}) *

For example, if the record length is 5, but the row contains "12345678\n", then the portion containing "678\n" will be discarded and not considered part of the next record * * @return returns true if any trailing characters beyond the record's length should be skipped until the newline is reached, false otherwise */ public boolean getSkipTrailingCharsUntilNewline() { return skipTrailingCharsUntilNewline; } /** * Defines whether or not any trailing characters beyond the record's length should be skipped until the newline is reached (defaults to {@code false}) *

For example, if the record length is 5, but the row contains "12345678\n", then the portion containing "678\n" will be discarded and not considered part of the next record * * @param skipTrailingCharsUntilNewline a flag indicating if any trailing characters beyond the record's length should be skipped until the newline is reached */ public void setSkipTrailingCharsUntilNewline(boolean skipTrailingCharsUntilNewline) { this.skipTrailingCharsUntilNewline = skipTrailingCharsUntilNewline; } /** * Indicates whether or not a record is considered parsed when a newline is reached. Examples: *

    *
  • Consider two records of length 4, and the input 12\n3456
  • *
  • When {@link FixedWidthParserSettings#recordEndsOnNewline} is set to true: the first value will be read as 12 and the second 3456
  • *
  • When {@link FixedWidthParserSettings#recordEndsOnNewline} is set to false: the first value will be read as 12\n3 and the second 456
  • *
*

defaults to {@code false} * * @return true if a record should be considered parsed when a newline is reached; false otherwise */ public boolean getRecordEndsOnNewline() { return recordEndsOnNewline; } /** * Defines whether or not a record is considered parsed when a newline is reached. Examples: *

    *
  • Consider two records of length 4, and the input 12\n3456
  • *
  • When {@link FixedWidthParserSettings#recordEndsOnNewline} is set to true: the first value will be read as 12 and the second 3456
  • *
  • When {@link FixedWidthParserSettings#recordEndsOnNewline} is set to false: the first value will be read as 12\n3 and the second 456
  • *
* * @param recordEndsOnNewline a flag indicating whether or not a record is considered parsed when a newline is reached */ public void setRecordEndsOnNewline(boolean recordEndsOnNewline) { this.recordEndsOnNewline = recordEndsOnNewline; } /** * Returns the default FixedWidthFormat configured to handle Fixed-Width inputs * * @return and instance of FixedWidthFormat configured to handle Fixed-Width inputs */ @Override protected FixedWidthFormat createDefaultFormat() { return new FixedWidthFormat(); } /** * Returns an instance of CharAppender with the configured limit of maximum characters per column and, default value used to represent a null value (when the String parsed from the input is empty), and the padding character to handle unwritten positions * *

This overrides the parent implementation to create a CharAppender capable of handling padding characters that represent unwritten positions. * * @return an instance of CharAppender with the configured limit of maximum characters per column and, default value used to represent a null value (when the String parsed from the input is empty), and the padding character to handle unwritten positions */ @Override protected CharAppender newCharAppender() { return new DefaultCharAppender(getMaxCharsPerColumn(), getNullValue(), getWhitespaceRangeStart()); } /** * The maximum number of characters allowed for any given value being written/read. Used to avoid OutOfMemoryErrors (defaults to a minimum of 4096 characters). * *

This overrides the parent implementation and calculates the absolute minimum number of characters required to store the values of a record *

If the sum of all field lengths is greater than the configured maximum number of characters per column, the calculated amount will be returned. * * @return The maximum number of characters allowed for any given value being written/read */ @Override public int getMaxCharsPerColumn() { int max = super.getMaxCharsPerColumn(); int minimum = 0; for (int length : calculateMaxFieldLengths()) { //adding 2 to give room for line breaks in every record (e.g. "\r\n"). minimum += length + 2; } return max > minimum ? max : minimum; } /** * Returns the hard limit of how many columns a record can have (defaults to a maximum of 512). * You need this to avoid OutOfMemory errors in case of inputs that might be inconsistent with the format you are dealing with. * *

This overrides the parent implementation and calculates the absolute minimum number of columns required to store the values of a record *

If the sum of all fields is greater than the configured maximum number columns, the calculated amount will be returned. * * @return The maximum number of columns a record can have. */ @Override public int getMaxColumns() { int max = super.getMaxColumns(); int minimum = calculateMaxFieldLengths().length; return max > minimum ? max : minimum; } private int[] calculateMaxFieldLengths() { return Lookup.calculateMaxFieldLengths(fieldLengths, lookaheadFormats, lookbehindFormats); } Lookup[] getLookaheadFormats() { return Lookup.getLookupFormats(lookaheadFormats, getFormat()); } Lookup[] getLookbehindFormats() { return Lookup.getLookupFormats(lookbehindFormats, getFormat()); } /** * Defines the format of records identified by a lookahead symbol. * * @param lookahead the lookahead value that when found in the input, * will notify the parser to switch to a new record format, with different field lengths * @param lengths the field lengths of the record format identified by the given lookahead symbol. */ public void addFormatForLookahead(String lookahead, FixedWidthFields lengths) { Lookup.registerLookahead(lookahead, lengths, lookaheadFormats); } /** * Defines the format of records identified by a lookbehind symbol. * * @param lookbehind the lookbehind value that when found in the previous input row, * will notify the parser to switch to a new record format, with different field lengths * @param lengths the field lengths of the record format identified by the given lookbehind symbol. */ public void addFormatForLookbehind(String lookbehind, FixedWidthFields lengths) { Lookup.registerLookbehind(lookbehind, lengths, lookbehindFormats); } /** * Indicates whether headers should be parsed using the default padding specified in {@link FixedWidthFormat#getPadding()} * instead of any custom padding associated with a given field (in {@link FixedWidthFields#setPadding(char, int...)}) * Defaults to {@code true} * * @return {@code true} if the default padding is to be used when reading headers, otherwise {@code false} */ public boolean getUseDefaultPaddingForHeaders() { return useDefaultPaddingForHeaders; } /** * Defines whether headers should be parsed using the default padding specified in {@link FixedWidthFormat#getPadding()} * instead of any custom padding associated with a given field (in {@link FixedWidthFields#setPadding(char, int...)}) * * @param useDefaultPaddingForHeaders flag indicating whether the default padding is to be used when parsing headers */ public void setUseDefaultPaddingForHeaders(boolean useDefaultPaddingForHeaders) { this.useDefaultPaddingForHeaders = useDefaultPaddingForHeaders; } @Override protected void configureFromAnnotations(Class beanClass) { if (fieldLengths == null) { try { fieldLengths = FixedWidthFields.forParsing(beanClass); Headers headerAnnotation = AnnotationHelper.findHeadersAnnotation(beanClass); if (headerExtractionEnabled == null && headerAnnotation != null) { setHeaderExtractionEnabled(headerAnnotation.extract()); } } catch (IllegalArgumentException e) { throw e; } catch (Exception ex) { //ignore. } } if (headerExtractionEnabled == null) { setHeaderExtractionEnabled(false); } super.configureFromAnnotations(beanClass); if (!isHeaderExtractionEnabled()) { FixedWidthFields.setHeadersIfPossible(fieldLengths, this); } } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); out.put("Skip trailing characters until new line", skipTrailingCharsUntilNewline); out.put("Record ends on new line", recordEndsOnNewline); out.put("Field lengths", fieldLengths == null ? "" : fieldLengths.toString()); out.put("Lookahead formats", lookaheadFormats); out.put("Lookbehind formats", lookbehindFormats); } /** * Clones this configuration object to reuse all user-provided settings, including the fixed-width field configuration. * * @return a copy of all configurations applied to the current instance. */ @Override public final FixedWidthParserSettings clone() { return (FixedWidthParserSettings) super.clone(); } /** * Clones this configuration object to reuse most user-provided settings. This includes the fixed-width field configuration, * but doesn't include other input-specific settings. This method is meant to be used internally only. * * @return a copy of all configurations applied to the current instance. * * @deprecated doesn't really make sense for fixed-width. Use alternative method {@link #clone(FixedWidthFields)}. */ @Deprecated protected final FixedWidthParserSettings clone(boolean clearInputSpecificSettings) { return clone(clearInputSpecificSettings, fieldLengths == null ? null : fieldLengths.clone()); } /** * Clones this configuration object to reuse most user-provided settings. Properties that are specific to a given * input (such as header names and selection of fields) will be reset to their defaults. * * To obtain a full copy, use {@link #clone()}. * * @param fields the fixed-width field configuration to be used by the cloned settings object. * * @return a copy of the general configurations applied to the current instance. */ public final FixedWidthParserSettings clone(FixedWidthFields fields) { return clone(true, fields); } private FixedWidthParserSettings clone(boolean clearInputSpecificSettings, FixedWidthFields fields) { FixedWidthParserSettings out = (FixedWidthParserSettings) super.clone(clearInputSpecificSettings); out.fieldLengths = fields; if (clearInputSpecificSettings) { out.lookaheadFormats = new HashMap(); out.lookbehindFormats = new HashMap(); } else { out.lookaheadFormats = new HashMap(this.lookaheadFormats); out.lookbehindFormats = new HashMap(this.lookbehindFormats); } return out; } /** * Indicate the padding character should be kept in the parsed value * * (defaults to {@code false}) * * This setting can be overridden for individual fields through * {@link FixedWidthFields#stripPaddingFrom(String, String...)} and * {@link FixedWidthFields#keepPaddingOn(String, String...)} * * @return flag indicating the padding character should be kept in the parsed value */ public final boolean getKeepPadding() { return keepPadding; } /** * Configures the fixed-width parser to retain the padding character in any parsed values * * (defaults to {@code false}) * * This setting can be overridden for individual fields through * {@link FixedWidthFields#stripPaddingFrom(String, String...)} and * {@link FixedWidthFields#keepPaddingOn(String, String...)} * * @param keepPadding flag indicating the padding character should be kept in the parsed value */ public final void setKeepPadding(boolean keepPadding) { this.keepPadding = keepPadding; } /** * Returns the sequence of fields whose padding character must/must not be retained in the parsed value * @return the sequence that have an explicit 'keepPadding' flag. */ Boolean[] getKeepPaddingFlags() { if (fieldLengths == null) { return null; } Boolean[] keepFlags = fieldLengths.getKeepPaddingFlags(); Boolean[] out = new Boolean[keepFlags.length]; Arrays.fill(out, getKeepPadding()); for (int i = 0; i < keepFlags.length; i++) { Boolean flag = keepFlags[i]; if (flag != null) { out[i] = flag; } } return out; } } FixedWidthRoutines.java000066400000000000000000000055711475274123300336700ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.common.routine.*; import java.io.*; /** * A collection of common routines involving the processing of Fixed-Width data. */ public class FixedWidthRoutines extends AbstractRoutines { /** * Creates a new instance of the Fixed-width routine class without any predefined parsing/writing configuration. */ public FixedWidthRoutines() { this(null, null); } /** * Creates a new instance of the Fixed-width routine class. * * @param parserSettings configuration to use for Fixed-width parsing */ public FixedWidthRoutines(FixedWidthParserSettings parserSettings) { this(parserSettings, null); } /** * Creates a new instance of the Fixed-width routine class. * * @param writerSettings configuration to use for Fixed-width writing */ public FixedWidthRoutines(FixedWidthWriterSettings writerSettings) { this(null, writerSettings); } /** * Creates a new instance of the Fixed-width routine class. * * @param parserSettings configuration to use for Fixed-width parsing * @param writerSettings configuration to use for Fixed-width writing */ public FixedWidthRoutines(FixedWidthParserSettings parserSettings, FixedWidthWriterSettings writerSettings) { super("Fixed-width parsing/writing routine", parserSettings, writerSettings); } protected void adjustColumnLengths(String[] headers, int[] lengths){ if(getWriterSettings().getFieldLengths() == null) { getWriterSettings().setFieldLengths(new FixedWidthFields(headers, lengths)); } } @Override protected FixedWidthParser createParser(FixedWidthParserSettings parserSettings) { return new FixedWidthParser(parserSettings); } @Override protected FixedWidthWriter createWriter(Writer output, FixedWidthWriterSettings writerSettings) { return new FixedWidthWriter(output, writerSettings); } @Override protected FixedWidthParserSettings createDefaultParserSettings() { return new FixedWidthParserSettings(); } @Override protected FixedWidthWriterSettings createDefaultWriterSettings() { return new FixedWidthWriterSettings(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/FixedWidthWriter.java000066400000000000000000000270611475274123300334110ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.common.*; import java.io.*; import java.nio.charset.*; /** * A fast and flexible fixed-with writer implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see FixedWidthFormat * @see FixedWidthFields * @see FixedWidthWriterSettings * @see FixedWidthParser * @see AbstractWriter */ public class FixedWidthWriter extends AbstractWriter { private int[] fieldLengths; private FieldAlignment[] fieldAlignments; private char[] fieldPaddings; private char padding; private char defaultPadding; private int length; private FieldAlignment alignment; private Lookup[] lookaheadFormats; private Lookup[] lookbehindFormats; private char[] lookupChars; private Lookup lookbehindFormat; private int[] rootLengths; private FieldAlignment[] rootAlignments; private boolean[] ignore; private boolean[] rootIgnore; private int ignoreCount; private char[] rootPaddings; private boolean defaultHeaderPadding; private FieldAlignment defaultHeaderAlignment; /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. *

Important: by not providing an instance of {@link java.io.Writer} to this constructor, only the operations that write to Strings are available.

* * @param settings the fixed-width writer configuration */ public FixedWidthWriter(FixedWidthWriterSettings settings) { this((Writer) null, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param writer the output resource that will receive fixed-width records produced by this class. * @param settings the fixed-width writer configuration */ public FixedWidthWriter(Writer writer, FixedWidthWriterSettings settings) { super(writer, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive fixed-width records produced by this class. * @param settings the fixed-width writer configuration */ public FixedWidthWriter(File file, FixedWidthWriterSettings settings) { super(file, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive fixed-width records produced by this class. * @param encoding the encoding of the file * @param settings the fixed-width writer configuration */ public FixedWidthWriter(File file, String encoding, FixedWidthWriterSettings settings) { super(file, encoding, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive fixed-width records produced by this class. * @param encoding the encoding of the file * @param settings the fixed-width writer configuration */ public FixedWidthWriter(File file, Charset encoding, FixedWidthWriterSettings settings) { super(file, encoding, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the fixed-width records produced by this class. * @param settings the fixed-width writer configuration */ public FixedWidthWriter(OutputStream output, FixedWidthWriterSettings settings) { super(output, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the fixed-width records produced by this class. * @param encoding the encoding of the stream * @param settings the fixed-width writer configuration */ public FixedWidthWriter(OutputStream output, String encoding, FixedWidthWriterSettings settings) { super(output, encoding, settings); } /** * The FixedWidthWriter supports all settings provided by {@link FixedWidthWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the fixed-width records produced by this class. * @param encoding the encoding of the stream * @param settings the fixed-width writer configuration */ public FixedWidthWriter(OutputStream output, Charset encoding, FixedWidthWriterSettings settings) { super(output, encoding, settings); } /** * Initializes the Fixed-Width writer with CSV-specific configuration * * @param settings the Fixed-Width writer configuration */ protected final void initialize(FixedWidthWriterSettings settings) { FixedWidthFormat format = settings.getFormat(); this.padding = format.getPadding(); this.defaultPadding = padding; this.fieldLengths = settings.getAllLengths(); this.fieldAlignments = settings.getFieldAlignments(); this.fieldPaddings = settings.getFieldPaddings(); this.ignore = settings.getFieldsToIgnore(); if (ignore != null) { for (int i = 0; i < ignore.length; i++) { if (ignore[i]) { ignoreCount++; } } } this.lookaheadFormats = settings.getLookaheadFormats(); this.lookbehindFormats = settings.getLookbehindFormats(); this.defaultHeaderPadding = settings.getUseDefaultPaddingForHeaders(); this.defaultHeaderAlignment = settings.getDefaultAlignmentForHeaders(); super.enableNewlineAfterRecord(settings.getWriteLineSeparatorAfterRecord()); if (lookaheadFormats != null || lookbehindFormats != null) { lookupChars = new char[Lookup.calculateMaxLookupLength(lookaheadFormats, lookbehindFormats)]; rootLengths = fieldLengths; rootAlignments = fieldAlignments; rootPaddings = fieldPaddings; rootIgnore = ignore; } else { lookupChars = null; rootLengths = null; rootAlignments = null; rootPaddings = null; rootIgnore = null; } } @Override protected void processRow(Object[] row) { if (row.length > 0 && lookaheadFormats != null || lookbehindFormats != null) { int dstBegin = 0; for (int i = 0; i < row.length && dstBegin < lookupChars.length; i++) { String value = String.valueOf(row[i]); int len = value.length(); if (dstBegin + len > lookupChars.length) { len = lookupChars.length - dstBegin; } value.getChars(0, len, lookupChars, dstBegin); dstBegin += len; } for (int i = lookupChars.length - 1; i > dstBegin; i--) { lookupChars[i] = '\0'; } boolean matched = false; if (lookaheadFormats != null) { for (int i = 0; i < lookaheadFormats.length; i++) { if (lookaheadFormats[i].matches(lookupChars)) { fieldLengths = lookaheadFormats[i].lengths; fieldAlignments = lookaheadFormats[i].alignments; fieldPaddings = lookaheadFormats[i].paddings; ignore = lookaheadFormats[i].ignore; matched = true; break; } } if (lookbehindFormats != null && matched) { lookbehindFormat = null; for (int i = 0; i < lookbehindFormats.length; i++) { if (lookbehindFormats[i].matches(lookupChars)) { lookbehindFormat = lookbehindFormats[i]; break; } } } } else { for (int i = 0; i < lookbehindFormats.length; i++) { if (lookbehindFormats[i].matches(lookupChars)) { lookbehindFormat = lookbehindFormats[i]; matched = true; fieldLengths = rootLengths; fieldAlignments = rootAlignments; fieldPaddings = rootPaddings; ignore = rootIgnore; break; } } } if (!matched) { if (lookbehindFormat == null) { if (rootLengths == null) { throw new TextWritingException("Cannot write with the given configuration. No default field lengths defined and no lookahead/lookbehind value match '" + new String(lookupChars) + '\'', getRecordCount(), row); } fieldLengths = rootLengths; fieldAlignments = rootAlignments; fieldPaddings = rootPaddings; ignore = rootIgnore; } else { fieldLengths = lookbehindFormat.lengths; fieldAlignments = lookbehindFormat.alignments; fieldPaddings = lookbehindFormat.paddings; ignore = lookbehindFormat.ignore; } } } if (expandRows) { row = expand(row, fieldLengths.length - ignoreCount, null); } final int lastIndex = fieldLengths.length < row.length ? fieldLengths.length : row.length; int off = 0; for (int i = 0; i < lastIndex + off; i++) { length = fieldLengths[i]; if (ignore[i]) { off++; this.appender.fill(' ', length); } else { alignment = fieldAlignments[i]; padding = fieldPaddings[i]; if (writingHeaders) { if (defaultHeaderPadding) { padding = defaultPadding; } if (defaultHeaderAlignment != null) { alignment = defaultHeaderAlignment; } } String nextElement = getStringValue(row[i - off]); boolean allowTrim = allowTrim(i); processElement(nextElement, allowTrim); appendValueToRow(); } } } private void append(String element, boolean allowTrim) { int start = 0; if (allowTrim && this.ignoreLeading) { start = skipLeadingWhitespace(whitespaceRangeStart, element); } int padCount = alignment.calculatePadding(length, element.length() - start); length -= padCount; appender.fill(padding, padCount); if (allowTrim && this.ignoreTrailing) { int i = start; while (i < element.length() && length > 0) { for (; i < element.length() && length-- > 0; i++) { char nextChar = element.charAt(i); appender.appendIgnoringWhitespace(nextChar); } if (length == -1 && appender.whitespaceCount() > 0) { //if we got here then the value to write got truncated exactly after one or more whitespaces. //In this case, if the whitespaces are not at the end of the truncated value they will be put back to the output. for (int j = i; j < element.length(); j++) { if (element.charAt(j) > ' ') { //resets the whitespace count so the original whitespaces are printed to the output. appender.resetWhitespaceCount(); break; } } if (appender.whitespaceCount() > 0) { length = 0; } } length += appender.whitespaceCount(); appendValueToRow(); } } else { for (int i = start; i < element.length() && length-- > 0; i++) { char nextChar = element.charAt(i); appender.append(nextChar); } } } private void processElement(String element, boolean allowTrim) { if (element != null) { append(element, allowTrim); } appender.fill(padding, length); } } FixedWidthWriterSettings.java000066400000000000000000000325341475274123300350540ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.annotations.*; import com.univocity.parsers.annotations.helpers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.Format; import java.util.*; /** * This is the configuration class used by the Fixed-Width writer ({@link FixedWidthWriter}) * *

The FixedWidthWriterSettings provides all configuration options in {@link CommonWriterSettings} and currently does not require any additional setting. * *

The FixedWidthParserSettings requires a definition of the field lengths of each record in the input. This must provided using an instance of {@link FixedWidthFields}. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.fixed.FixedWidthWriter * @see com.univocity.parsers.fixed.FixedWidthFormat * @see FixedWidthFields * @see com.univocity.parsers.common.CommonWriterSettings */ public class FixedWidthWriterSettings extends CommonWriterSettings { private FixedWidthFields fieldLengths; private Map lookaheadFormats = new HashMap(); private Map lookbehindFormats = new HashMap(); private boolean useDefaultPaddingForHeaders = true; private FieldAlignment defaultAlignmentForHeaders = null; private boolean writeLineSeparatorAfterRecord = true; /** * You can only create an instance of this class by providing a definition of the field lengths of each record in the input. *

This must provided using an instance of {@link FixedWidthFields}. * * @param fieldLengths the instance of {@link FixedWidthFields} which provides the lengths of each field in the fixed-width records to be parsed * * @see FixedWidthFields */ public FixedWidthWriterSettings(FixedWidthFields fieldLengths) { setFieldLengths(fieldLengths); NormalizedString[] names = fieldLengths.getFieldNames(); if (names != null) { setHeaders(NormalizedString.toArray(names)); } } /** * Creates a basic configuration object for the Fixed-Width writer with no field length configuration. * This constructor is intended to be used when the record length varies depending of the input row. * Refer to {@link #addFormatForLookahead(String, FixedWidthFields)}, {@link #addFormatForLookbehind(String, FixedWidthFields)} */ public FixedWidthWriterSettings() { this.fieldLengths = null; } final void setFieldLengths(FixedWidthFields fieldLengths) { if (fieldLengths == null) { throw new IllegalArgumentException("Field lengths cannot be null"); } this.fieldLengths = fieldLengths; } /** * Returns the sequence of field lengths to be written to form a record. * * @return the sequence of field lengths to be written to form a record. */ int[] getFieldLengths() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldLengths(); } /** * Returns the sequence of field lengths to be written to form a record. * * @return the sequence of field lengths to be written to form a record. */ int[] getAllLengths() { if (fieldLengths == null) { return null; } return fieldLengths.getAllLengths(); } /** * Returns the sequence of field alignments to apply to each field in the record. * * @return the sequence of field alignments to apply to each field in the record. */ FieldAlignment[] getFieldAlignments() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldAlignments(); } /** * Returns the sequence of paddings used by each field of each record. * * @return the sequence of paddings used by each field of each record. */ char[] getFieldPaddings() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldPaddings(getFormat()); } /** * Returns the sequence of fields to ignore. * * @return the sequence of fields to ignore. */ boolean[] getFieldsToIgnore() { if (fieldLengths == null) { return null; } return fieldLengths.getFieldsToIgnore(); } /** * Returns the default FixedWidthFormat configured to handle Fixed-Width outputs * * @return and instance of FixedWidthFormat configured to handle Fixed-Width outputs */ @Override protected FixedWidthFormat createDefaultFormat() { return new FixedWidthFormat(); } @Override public int getMaxColumns() { int max = super.getMaxColumns(); int minimum = Lookup.calculateMaxFieldLengths(fieldLengths, lookaheadFormats, lookbehindFormats).length; return max > minimum ? max : minimum; } /** * Defines the format of records identified by a lookahead symbol. * * @param lookahead the lookahead value that when found in the output row, * will notify the writer to switch to a new record format, with different field lengths * @param lengths the field lengths of the record format identified by the given lookahead symbol. */ public void addFormatForLookahead(String lookahead, FixedWidthFields lengths) { Lookup.registerLookahead(lookahead, lengths, lookaheadFormats); } /** * Defines the format of records identified by a lookbehind symbol. * * @param lookbehind the lookbehind value that when present in the previous output row, * will notify the writer to switch to a new record format, with different field lengths * @param lengths the field lengths of the record format identified by the given lookbehind symbol. */ public void addFormatForLookbehind(String lookbehind, FixedWidthFields lengths) { Lookup.registerLookbehind(lookbehind, lengths, lookbehindFormats); } Lookup[] getLookaheadFormats() { return Lookup.getLookupFormats(lookaheadFormats, getFormat()); } Lookup[] getLookbehindFormats() { return Lookup.getLookupFormats(lookbehindFormats, getFormat()); } /** * Indicates whether headers should be written using the default padding specified in {@link FixedWidthFormat#getPadding()} * instead of any custom padding associated with a given field (in {@link FixedWidthFields#setPadding(char, int...)}) * Defaults to {@code true} * * @return {@code true} if the default padding is to be used when writing headers, otherwise {@code false} */ public boolean getUseDefaultPaddingForHeaders() { return useDefaultPaddingForHeaders; } /** * Defines whether headers should be written using the default padding specified in {@link FixedWidthFormat#getPadding()} * instead of any custom padding associated with a given field (in {@link FixedWidthFields#setPadding(char, int...)}) * * @param useDefaultPaddingForHeaders flag indicating whether the default padding is to be used when writing headers */ public void setUseDefaultPaddingForHeaders(boolean useDefaultPaddingForHeaders) { this.useDefaultPaddingForHeaders = useDefaultPaddingForHeaders; } /** * Returns the default alignment to use when writing headers. If none is specified (i.e. {@code null}), the headers will be aligned * according to the corresponding field alignment in {@link FixedWidthFields#getAlignment(String)}. * * Defaults to {@code null}. * * @return the default alignment for headers, or {@code null} if the headers should be aligned according to the column alignment. */ public FieldAlignment getDefaultAlignmentForHeaders() { return defaultAlignmentForHeaders; } /** * Defines the default alignment to use when writing headers. If none is specified (i.e. {@code null}), the headers will be aligned * according to the corresponding field alignment in {@link FixedWidthFields#getAlignment(String)}. * * Defaults to {@code null}. * * @param defaultAlignmentForHeaders the alignment to use when writing headers. {@code null} indicates that headers * should be aligned according to the column alignment. */ public void setDefaultAlignmentForHeaders(FieldAlignment defaultAlignmentForHeaders) { this.defaultAlignmentForHeaders = defaultAlignmentForHeaders; } /** * Returns a flag indicating whether each record, when written, should be followed by a line separator (as specified in {@link Format#getLineSeparator()}. * * Consider the records {@code [a,b]} and {@code [c,d]}, with field lengths {@code [2, 2]}, and line separator = {@code \n}: *

    *
  • When {@link #getWriteLineSeparatorAfterRecord()} is enabled, the output will be written as: {@code a b \nc d \n}
  • *
  • When {@link #getWriteLineSeparatorAfterRecord()} is disabled, the output will be written as: {@code a b c d }
  • *
* * Defaults to {@code true}. * * @return whether the writer should add a line separator after a record is written to the output. */ public boolean getWriteLineSeparatorAfterRecord() { return writeLineSeparatorAfterRecord; } /** * Defines whether each record, when written, should be followed by a line separator (as specified in {@link Format#getLineSeparator()}. * * Consider the records {@code [a,b]} and {@code [c,d]}, with field lengths {@code [2, 2]}, and line separator = {@code \n}: *
    *
  • When {@link #getWriteLineSeparatorAfterRecord()} is enabled, the output will be written as: {@code a b \nc d \n}
  • *
  • When {@link #getWriteLineSeparatorAfterRecord()} is disabled, the output will be written as: {@code a b c d }
  • *
* * Defaults to {@code true}. * * @param writeLineSeparatorAfterRecord flag indicating whether the writer should add a line separator after a record is written to the output. */ public void setWriteLineSeparatorAfterRecord(boolean writeLineSeparatorAfterRecord) { this.writeLineSeparatorAfterRecord = writeLineSeparatorAfterRecord; } @Override protected void configureFromAnnotations(Class beanClass) { if (fieldLengths != null) { return; } try { fieldLengths = FixedWidthFields.forWriting(beanClass); Headers headerAnnotation = AnnotationHelper.findHeadersAnnotation(beanClass); setHeaderWritingEnabled(headerAnnotation != null && headerAnnotation.write()); } catch (Exception ex) { //ignore. } super.configureFromAnnotations(beanClass); FixedWidthFields.setHeadersIfPossible(fieldLengths, this); } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); out.put("Write line separator after record", writeLineSeparatorAfterRecord); out.put("Field lengths", fieldLengths); out.put("Lookahead formats", lookaheadFormats); out.put("Lookbehind formats", lookbehindFormats); out.put("Use default padding for headers", useDefaultPaddingForHeaders); out.put("Default alignment for headers", defaultAlignmentForHeaders); } /** * Clones this configuration object to reuse all user-provided settings, including the fixed-width field configuration. * * @return a copy of all configurations applied to the current instance. */ @Override public final FixedWidthWriterSettings clone() { return (FixedWidthWriterSettings) super.clone(false); } /** * Clones this configuration object to reuse most user-provided settings. This includes the fixed-width field configuration, * but doesn't include other input-specific settings. This method is meant to be used internally only. * * @return a copy of all configurations applied to the current instance. * * @deprecated doesn't really make sense for fixed-width. . Use alternative method {@link #clone(FixedWidthFields)}. */ @Deprecated protected final FixedWidthWriterSettings clone(boolean clearInputSpecificSettings) { return clone(clearInputSpecificSettings, fieldLengths == null ? null : fieldLengths.clone()); } /** * Clones this configuration object to reuse most user-provided settings. Properties that are specific to a given * input (such as header names and selection of fields) will be reset to their defaults. * * To obtain a full copy, use {@link #clone()}. * * @param fields the fixed-width field configuration to be used by the cloned settings object. * * @return a copy of the general configurations applied to the current instance. */ public final FixedWidthWriterSettings clone(FixedWidthFields fields) { return clone(true, fields); } private FixedWidthWriterSettings clone(boolean clearInputSpecificSettings, FixedWidthFields fields) { FixedWidthWriterSettings out = (FixedWidthWriterSettings) super.clone(clearInputSpecificSettings); out.fieldLengths = fields; if (clearInputSpecificSettings) { out.lookaheadFormats = new HashMap(); out.lookbehindFormats = new HashMap(); } else { out.lookaheadFormats = new HashMap(this.lookaheadFormats); out.lookbehindFormats = new HashMap(this.lookbehindFormats); } return out; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/fixed/Lookup.java000066400000000000000000000126741475274123300314320ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.fixed; import com.univocity.parsers.common.*; import com.univocity.parsers.common.record.*; import java.util.*; import java.util.Map.*; class Lookup { final char[] value; final int[] lengths; final FieldAlignment[] alignments; final boolean[] ignore; final Boolean[] keepPaddingFlags; final char[] paddings; final NormalizedString[] fieldNames; final char wildcard; Context context; Lookup(String value, FixedWidthFields config, FixedWidthFormat format) { this.value = value.toCharArray(); this.lengths = config.getAllLengths(); this.alignments = config.getFieldAlignments(); this.fieldNames = config.getFieldNames(); this.paddings = config.getFieldPaddings(format); this.wildcard = format.getLookupWildcard(); this.ignore = config.getFieldsToIgnore(); this.keepPaddingFlags = config.getKeepPaddingFlags(); } void initializeLookupContext(ParsingContext context, final NormalizedString[] headersToUse) { final String[] headers = NormalizedString.toArray(headersToUse); this.context = new ParsingContextWrapper(context) { RecordFactory recordFactory; final ColumnMap columnMap = new ColumnMap(this, null); @Override public String[] headers() { return headers; } @Override public int indexOf(String header) { return columnMap.indexOf(header); } @Override public int indexOf(Enum header) { return columnMap.indexOf(header); } @Override public Record toRecord(String[] row) { if (recordFactory == null) { recordFactory = new RecordFactory(this); } return recordFactory.newRecord(row); } @Override public RecordMetaData recordMetaData(){ if(recordFactory == null){ recordFactory = new RecordFactory(this); } return recordFactory.getRecordMetaData(); } }; } boolean matches(char[] lookup) { if (value.length > lookup.length) { return false; } for (int i = 0; i < value.length; i++) { char ch = value[i]; if (ch != wildcard && ch != lookup[i]) { return false; } } return true; } static void registerLookahead(String lookup, FixedWidthFields lengths, Map map) { registerLookup("ahead", lookup, lengths, map); } static void registerLookbehind(String lookup, FixedWidthFields lengths, Map map) { registerLookup("behind", lookup, lengths, map); } private static void registerLookup(String direction, String lookup, FixedWidthFields lengths, Map map) { if (lookup == null) { throw new IllegalArgumentException("Look" + direction + " value cannot be null"); } if (lengths == null) { throw new IllegalArgumentException("Lengths of fields associated to look" + direction + " value '" + lookup + "' cannot be null"); } map.put(lookup, lengths); } static Lookup[] getLookupFormats(Map map, FixedWidthFormat format) { if (map.isEmpty()) { return null; } Lookup[] out = new Lookup[map.size()]; int i = 0; for (Entry e : map.entrySet()) { out[i++] = new Lookup(e.getKey(), e.getValue(), format); } Arrays.sort(out, new Comparator() { @Override public int compare(Lookup o1, Lookup o2) { //longer values go first. return o1.value.length < o2.value.length ? 1 : o1.value.length == o2.value.length ? 0 : -1; } }); return out; } static int calculateMaxLookupLength(Lookup[]... lookupArrays) { int max = 0; for (Lookup[] lookups : lookupArrays) { if (lookups != null) { for (Lookup lookup : lookups) { if (max < lookup.value.length) { max = lookup.value.length; } } } } return max; } static int[] calculateMaxFieldLengths(FixedWidthFields fieldLengths, Map lookaheadFormats, Map lookbehindFormats) { List allLengths = new ArrayList(); if (fieldLengths != null) { allLengths.add(fieldLengths.getFieldLengths()); } for (FixedWidthFields lengths : lookaheadFormats.values()) { allLengths.add(lengths.getFieldLengths()); } for (FixedWidthFields lengths : lookbehindFormats.values()) { allLengths.add(lengths.getFieldLengths()); } if (allLengths.isEmpty()) { throw new IllegalStateException("Cannot determine field lengths to use."); } int lastColumn = -1; for (int[] lengths : allLengths) { if (lastColumn < lengths.length) { lastColumn = lengths.length; } } int[] out = new int[lastColumn]; Arrays.fill(out, 0); for (int[] lengths : allLengths) { for (int i = 0; i < lastColumn; i++) { if (i < lengths.length) { int length = lengths[i]; if (out[i] < length) { out[i] = length; } } } } return out; } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/000077500000000000000000000000001475274123300270215ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/TsvFormat.java000077500000000000000000000066371475274123300316300ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.tsv; import com.univocity.parsers.common.*; import java.util.*; /** * The TSV format configuration, for tab-separated inputs. It offers the options in the default configuration in {@link Format}, as well as * the {@link #escapeChar} character for escaping \t, \n, \r and \ in TSV values. * * Delimiters are defined as tab characters '\t' * * @see com.univocity.parsers.common.Format * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class TsvFormat extends Format { private char escapeChar = '\\'; private char escapedTabChar = 't'; /** * Defines the character used for escaping special characters in TSV inputs: \t, \n, \r and \ . Defaults to '\\' * @param escapeChar the escape character */ public void setEscapeChar(char escapeChar) { this.escapeChar = escapeChar; } /** * Returns the character used for escaping special characters in TSV inputs: \t, \n, \r and \ * * @return the escape character. */ public char getEscapeChar() { return escapeChar; } /** * Returns the character that should be used to represent an escaped tab, i.e. the character before the defined * {@link #getEscapeChar()}. For example, if {@link #getEscapeChar()} == '\\' and {@link #getEscapedTabChar() == 'X'}, * the sequence {@code '\X'} will identify a tab. * * Defaults to {@code 't'}. * * @return the character following the {@link #getEscapeChar()} that represents an escaped tab. */ public char getEscapedTabChar() { return escapedTabChar; } /** * Defines the character that should be used to represent an escaped tab, i.e. the character before the defined * {@link #getEscapeChar()}. For example, if {@link #getEscapeChar()} == '\\' and {@link #getEscapedTabChar() == 'X'}, * the sequence {@code '\X'} will identify a tab. * * Defaults to {@code 't'}. * * @param escapedTabChar the character following the {@link #getEscapeChar()} that represents an escaped tab. */ public void setEscapedTabChar(char escapedTabChar) { this.escapedTabChar = escapedTabChar; } /** * Identifies whether or not a given character is used for escaping special characters in TSV (\t, \n, \r and \). * @param ch the character to be verified * @return true if the given character is escape character, false otherwise */ public boolean isEscapeChar(char ch) { return this.escapeChar == ch; } @Override protected TreeMap getConfiguration() { TreeMap out = new TreeMap(); out.put("Escape character", escapeChar); return out; } @Override public final TsvFormat clone() { return (TsvFormat) super.clone(); } }jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/TsvParser.java000077500000000000000000000063051475274123300316240ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.tsv; import com.univocity.parsers.common.*; /** * A very fast TSV parser implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see TsvFormat * @see TsvParserSettings * @see TsvWriter * @see AbstractParser */ public class TsvParser extends AbstractParser { private final boolean joinLines; private final char newLine; private final char escapeChar; private final char escapedTabChar; /** * The TsvParser supports all settings provided by {@link TsvParserSettings}, and requires this configuration to be properly initialized. * * @param settings the parser configuration */ public TsvParser(TsvParserSettings settings) { super(settings); joinLines = settings.isLineJoiningEnabled(); TsvFormat format = settings.getFormat(); newLine = format.getNormalizedNewline(); escapeChar = settings.getFormat().getEscapeChar(); escapedTabChar = format.getEscapedTabChar(); } @Override protected void initialize() { output.trim = ignoreTrailingWhitespace; } /** * {@inheritDoc} */ @Override protected void parseRecord() { if (ignoreLeadingWhitespace && ch != '\t' && ch <= ' ' && whitespaceRangeStart < ch) { ch = input.skipWhitespace(ch, '\t', escapeChar); } while (ch != newLine) { parseField(); if (ch != newLine) { ch = input.nextChar(); if (ch == newLine) { output.emptyParsed(); } } } } private void parseField() { if (ignoreLeadingWhitespace && ch != '\t' && ch <= ' ' && whitespaceRangeStart < ch) { ch = input.skipWhitespace(ch, '\t', escapeChar); } if (ch == '\t') { output.emptyParsed(); } else { while (ch != '\t' && ch != newLine) { if (ch == escapeChar) { ch = input.nextChar(); if (ch == 't' || ch == escapedTabChar) { output.appender.append('\t'); } else if (ch == 'n') { output.appender.append('\n'); } else if (ch == '\\') { output.appender.append('\\'); } else if (ch == 'r') { output.appender.append('\r'); } else if (ch == newLine && joinLines) { output.appender.append(newLine); } else { output.appender.append(escapeChar); if (ch == newLine || ch == '\t') { break; } output.appender.append(ch); } ch = input.nextChar(); } else { ch = output.appender.appendUntil(ch, input, '\t', escapeChar, newLine); } } output.valueParsed(); } } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/TsvParserSettings.java000077500000000000000000000105531475274123300333450ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.tsv; import com.univocity.parsers.common.*; import java.util.*; /** * This is the configuration class used by the TSV parser ({@link TsvParser}) * *

It supports the configuration options provided by {@link CommonParserSettings} only * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see com.univocity.parsers.tsv.TsvParser * @see com.univocity.parsers.tsv.TsvFormat * @see com.univocity.parsers.common.CommonParserSettings */ public class TsvParserSettings extends CommonParserSettings { private boolean lineJoiningEnabled = false; /** * Identifies whether or lines ending with the escape character (defined by {@link TsvFormat#getEscapeChar()} * and followed by a line separator character should be joined with the following line. * * Typical examples include inputs where lines end with sequences such as: {@code '\'+'\n'} and {@code '\'+'\r'+'\n'}. * * When line joining is disabled (the default), the {@link TsvParser} converts sequences containing * the escape character (typically '\') followed by characters 'n' or 'r' into a '\n' or '\r' character. * It will continue processing the contents found in the same line, until a new line character is found. * * If line joining is enabled, the {@link TsvParser} will convert sequences containing * the escape character, followed by characters '\n', '\r' or '\r\n', into a '\n' or '\r' character. * It will continue processing the contents found in the next line, until a new line character is found, given it is * not preceded by another escape character. * * @return {@code true} if line joining is enabled, otherwise {@code false} */ public boolean isLineJoiningEnabled() { return lineJoiningEnabled; } /** * Defines how the parser should handle escaped line separators. By enabling lines joining, * lines ending with the escape character (defined by {@link TsvFormat#getEscapeChar()} * and followed by a line separator character will be joined with the following line. * * Typical examples include inputs where lines end with sequences such as: {@code '\'+'\n'} and {@code '\'+'\r'+'\n'}. * * When line joining is disabled (the default), the {@link TsvParser} converts sequences containing * the escape character (typically '\') followed by characters 'n' or 'r' into a '\n' or '\r' character. * It will continue processing the contents found in the same line, until a new line character is found. * * If line joining is enabled, the {@link TsvParser} will convert sequences containing * the escape character, followed by characters '\n', '\r' or '\r\n', into a '\n' or '\r' character. * It will continue processing the contents found in the next line, until a new line character is found, given it is * not preceded by another escape character. * * @param lineJoiningEnabled a flag indicating whether or not to enable line joining. */ public void setLineJoiningEnabled(boolean lineJoiningEnabled) { this.lineJoiningEnabled = lineJoiningEnabled; } /** * Returns the default TsvFormat configured to handle TSV inputs * * @return and instance of TsvFormat configured to handle TSV */ @Override protected TsvFormat createDefaultFormat() { return new TsvFormat(); } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); } @Override public final TsvParserSettings clone() { return (TsvParserSettings) super.clone(); } @Override public final TsvParserSettings clone(boolean clearInputSpecificSettings) { return (TsvParserSettings) super.clone(clearInputSpecificSettings); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/TsvRoutines.java000066400000000000000000000046761475274123300322060ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.tsv; import com.univocity.parsers.common.routine.*; import java.io.*; /** * A collection of common routines involving the processing of TSV data. */ public class TsvRoutines extends AbstractRoutines { /** * Creates a new instance of the TSV routine class without any predefined parsing/writing configuration. */ public TsvRoutines() { this(null, null); } /** * Creates a new instance of the TSV routine class. * * @param parserSettings configuration to use for TSV parsing */ public TsvRoutines(TsvParserSettings parserSettings) { this(parserSettings, null); } /** * Creates a new instance of the TSV routine class. * * @param writerSettings configuration to use for TSV writing */ public TsvRoutines(TsvWriterSettings writerSettings) { this(null, writerSettings); } /** * Creates a new instance of the TSV routine class. * * @param parserSettings configuration to use for TSV parsing * @param writerSettings configuration to use for TSV writing */ public TsvRoutines(TsvParserSettings parserSettings, TsvWriterSettings writerSettings) { super("TSV parsing/writing routine", parserSettings, writerSettings); } @Override protected TsvParser createParser(TsvParserSettings parserSettings) { return new TsvParser(parserSettings); } @Override protected TsvWriter createWriter(Writer output, TsvWriterSettings writerSettings) { return new TsvWriter(output, writerSettings); } @Override protected TsvParserSettings createDefaultParserSettings() { return new TsvParserSettings(); } @Override protected TsvWriterSettings createDefaultWriterSettings() { return new TsvWriterSettings(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/TsvWriter.java000066400000000000000000000151451475274123300316430ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.tsv; import com.univocity.parsers.common.*; import java.io.*; import java.nio.charset.*; /** * A powerful and flexible TSV writer implementation. * * @author Univocity Software Pty Ltd - parsers@univocity.com * @see TsvFormat * @see TsvWriterSettings * @see TsvParser * @see AbstractWriter */ public class TsvWriter extends AbstractWriter { private boolean joinLines; private char escapeChar; private char escapedTabChar; private char newLine; /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. *

Important: by not providing an instance of {@link java.io.Writer} to this constructor, only the operations that write to Strings are available.

* * @param settings the TSV writer configuration */ public TsvWriter(TsvWriterSettings settings) { this((Writer) null, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param writer the output resource that will receive TSV records produced by this class. * @param settings the TSV writer configuration */ public TsvWriter(Writer writer, TsvWriterSettings settings) { super(writer, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive TSV records produced by this class. * @param settings the TSV writer configuration */ public TsvWriter(File file, TsvWriterSettings settings) { super(file, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive TSV records produced by this class. * @param encoding the encoding of the file * @param settings the TSV writer configuration */ public TsvWriter(File file, String encoding, TsvWriterSettings settings) { super(file, encoding, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param file the output file that will receive TSV records produced by this class. * @param encoding the encoding of the file * @param settings the TSV writer configuration */ public TsvWriter(File file, Charset encoding, TsvWriterSettings settings) { super(file, encoding, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the TSV records produced by this class. * @param settings the TSV writer configuration */ public TsvWriter(OutputStream output, TsvWriterSettings settings) { super(output, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the TSV records produced by this class. * @param encoding the encoding of the stream * @param settings the TSV writer configuration */ public TsvWriter(OutputStream output, String encoding, TsvWriterSettings settings) { super(output, encoding, settings); } /** * The TsvWriter supports all settings provided by {@link TsvWriterSettings}, and requires this configuration to be properly initialized. * * @param output the output stream that will be written with the TSV records produced by this class. * @param encoding the encoding of the stream * @param settings the TSV writer configuration */ public TsvWriter(OutputStream output, Charset encoding, TsvWriterSettings settings) { super(output, encoding, settings); } /** * Initializes the TSV writer with TSV-specific configuration * * @param settings the TSV writer configuration */ protected final void initialize(TsvWriterSettings settings) { this.escapeChar = settings.getFormat().getEscapeChar(); this.escapedTabChar = settings.getFormat().getEscapedTabChar(); this.joinLines = settings.isLineJoiningEnabled(); this.newLine = settings.getFormat().getNormalizedNewline(); } @Override protected void processRow(Object[] row) { for (int i = 0; i < row.length; i++) { if (i != 0) { appendToRow('\t'); } String nextElement = getStringValue(row[i]); boolean allowTrim = allowTrim(i); int originalLength = appender.length(); append(nextElement, allowTrim); //skipped all whitespaces and wrote nothing if (appender.length() == originalLength && nullValue != null && !nullValue.isEmpty()) { append(nullValue, allowTrim); } appendValueToRow(); } } private void append(String element, boolean allowTrim) { if (element == null) { element = nullValue; } if (element == null) { return; } int start = 0; if (allowTrim && this.ignoreLeading) { start = skipLeadingWhitespace(whitespaceRangeStart, element); } final int length = element.length(); int i = start; char ch = '\0'; for (; i < length; i++) { ch = element.charAt(i); if (ch == '\t' || ch == '\n' || ch == '\r' || ch == '\\') { appender.append(element, start, i); start = i + 1; appender.append(escapeChar); if (ch == '\t') { appender.append(escapedTabChar); } else if (ch == '\n') { appender.append(joinLines ? newLine : 'n'); } else if (ch == '\\') { appender.append('\\'); } else { appender.append(joinLines ? newLine : 'r'); } } } appender.append(element, start, i); if (allowTrim && ch <= ' ' && ignoreTrailing && whitespaceRangeStart < ch) { appender.updateWhitespace(); } } }jtreg7-7.5.1+1+ds1/univocity-parsers/src/main/java/com/univocity/parsers/tsv/TsvWriterSettings.java000066400000000000000000000116541475274123300333650ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.tsv; import com.univocity.parsers.common.*; import java.util.*; /** * This is the configuration class used by the TSV writer ({@link TsvWriter}) * *

It does not offer additional configuration options on top of the ones provided by the {@link CommonWriterSettings}

* * @see com.univocity.parsers.tsv.TsvWriter * @see com.univocity.parsers.tsv.TsvFormat * @see com.univocity.parsers.common.CommonWriterSettings * * @author Univocity Software Pty Ltd - parsers@univocity.com * */ public class TsvWriterSettings extends CommonWriterSettings { private boolean lineJoiningEnabled = false; /** * Identifies whether values containing line endings should have the line separator written using * the escape character (defined by {@link TsvFormat#getEscapeChar()} followed by the actual line separator character * instead of other characters such as the standard letters 'n' and 'r' * * When line joining is disabled (the default), the {@link TsvWriter} will convert new line characters into * sequences containing the escape character (typically '\') followed by characters 'n' or 'r'. * No matter how many line separators the values written contain, the will be escaped and the entire output * of a record will be written into a single line of text. For example, '\n' and '\r' characters will be * written as: {@code '\'+'n'} and {@code '\'+'r'}. * * If line joining is enabled, the {@link TsvWriter} will convert line new line characters into sequences * containing the escape character, followed by characters '\n', '\r' or both. * A new line of text will be generated for each line separator found in the value to be written, "marking" the end * of each line with the escape character to indicate the record continues on the next line. For example, '\n' and '\r' * characters will be written as: {@code '\'+'\n'} and {@code '\'+'\r'}. * * @return {@code true} if line joining is enabled, otherwise {@code false} */ public boolean isLineJoiningEnabled() { return lineJoiningEnabled; } /** * Defines how the writer should handle the escaping of line separators. * Values containing line endings should be escaped and the line separator characters can be written using * the escape character (defined by {@link TsvFormat#getEscapeChar()} followed by the actual line separator character * instead of other characters such as the standard letters 'n' and 'r' * * When line joining is disabled (the default), the {@link TsvWriter} will convert new line characters into * sequences containing the escape character (typically '\') followed by characters 'n' or 'r'. * No matter how many line separators the values written contain, the will be escaped and the entire output * of a record will be written into a single line of text. For example, '\n' and '\r' characters will be * written as: {@code '\'+'n'} and {@code '\'+'r'}. * * If line joining is enabled, the {@link TsvWriter} will convert line new line characters into sequences * containing the escape character, followed by characters '\n', '\r' or both. * A new line of text will be generated for each line separator found in the value to be written, "marking" the end * of each line with the escape character to indicate the record continues on the next line. For example, '\n' and '\r' * characters will be written as: {@code '\'+'\n'} and {@code '\'+'\r'}. * * @param lineJoiningEnabled a flag indicating whether or not to enable line joining. */ public void setLineJoiningEnabled(boolean lineJoiningEnabled) { this.lineJoiningEnabled = lineJoiningEnabled; } /** * Returns the default TsvFormat. * @return and instance of TsvFormat configured to produce TSV outputs. */ @Override protected TsvFormat createDefaultFormat() { return new TsvFormat(); } @Override protected void addConfiguration(Map out) { super.addConfiguration(out); } @Override public final TsvWriterSettings clone() { return (TsvWriterSettings) super.clone(); } @Override public final TsvWriterSettings clone(boolean clearInputSpecificSettings) { return (TsvWriterSettings) super.clone(clearInputSpecificSettings); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/000077500000000000000000000000001475274123300210315ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/000077500000000000000000000000001475274123300217525ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/000077500000000000000000000000001475274123300225305ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/000077500000000000000000000000001475274123300245615ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/000077500000000000000000000000001475274123300262405ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/ParserTestCase.java000066400000000000000000000045351475274123300320020ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.csv.*; import java.io.*; import java.net.*; import java.util.*; import static org.testng.Assert.*; public abstract class ParserTestCase { protected RowListProcessor processor = newRowListProcessor(); protected RowListProcessor newRowListProcessor() { return new RowListProcessor(); } public static Reader newReader(String path) throws UnsupportedEncodingException { Reader reader = new InputStreamReader(ParserTestCase.class.getResourceAsStream(path), "UTF-8"); return reader; } public void assertHeadersAndValuesMatch(RowListProcessor processor, String[] expectedHeaders, Object[][] expectedResult) { String[] headers = processor.getHeaders(); TestUtils.assertEquals(headers, expectedHeaders); List rows = processor.getRows(); assertEquals(rows.size(), expectedResult.length); for (int i = 0; i < expectedResult.length; i++) { String[] row = rows.get(i); Object[] expectedRow = expectedResult[i]; assertEquals(row, expectedRow, "Inconsistency found on row " + i); } } public void assertHeadersAndValuesMatch(String[] expectedHeaders, Object[][] expectedResult) { assertHeadersAndValuesMatch(processor, expectedHeaders, expectedResult); } public String readFileContent(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String line; StringBuilder fileContent = new StringBuilder(); while((line = reader.readLine()) != null) { fileContent.append(line).append('\n'); } return fileContent.toString(); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/000077500000000000000000000000001475274123300305755ustar00rootroot00000000000000AnnotationHelperTest.java000066400000000000000000000043101475274123300354710ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations; import com.univocity.parsers.annotations.helpers.AnnotationHelper; import java.io.*; import java.lang.reflect.Constructor; import java.util.*; import com.univocity.parsers.annotations.meta.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import static org.testng.Assert.*; public class AnnotationHelperTest { @Test public void shouldCreateAnnotationHelper() throws Exception { Constructor c = AnnotationHelper.class.getDeclaredConstructor(); c.setAccessible(true); AnnotationHelper helper = c.newInstance(); assertNotNull(helper); } @Test public void testContentCleaner() { CsvWriterSettings settings = new CsvWriterSettings(); settings.getFormat().setDelimiter(';'); settings.getFormat().setLineSeparator("\n"); settings.setRowWriterProcessor(new BeanWriterProcessor(CleanBeanTest.class)); StringWriter out = new StringWriter(); CsvWriter writer = new CsvWriter(out, settings); List beans = new ArrayList(); beans.add(new CleanBeanTest("this;is;a;test", ";and;another;test;", 1)); beans.add(new CleanBeanTest("this;is;b;test", ";", 2)); beans.add(new CleanBeanTest("this;is;c;test", ";;", 3)); writer.processRecordsAndClose(beans); assertEquals(out.toString(), "" + "thisistest;andanothertest;1\n" + "thisisbtest;;2\n" + "thisisctest;;\n"); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/000077500000000000000000000000001475274123300315235ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/Clean.java000066400000000000000000000026421475274123300334140ustar00rootroot00000000000000/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; import com.univocity.parsers.annotations.*; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Convert(conversionClass = ContentCleaner.class) @Parsed @IntArray(ints = {}) public @interface Clean { @Copy(to = Parsed.class) String field() default ""; @Copy(to = Parsed.class) int index() default -1; @Copy(to = Convert.class, property = "args") String remove(); //not used for anything else than testing whether the AnnotationHelper will bomb @Copy(to = IntArray.class, property = "ints") int[] theInts(); } CleanBeanTest.java000066400000000000000000000020741475274123300347620ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; public class CleanBeanTest { @Clean(remove = "a;", theInts = 0) String a; @Clean(remove = ";", theInts = {1,2}) String b; @Clean(remove = "3", theInts = {}) int c; public CleanBeanTest(String a, String b, int c) { this.a = a; this.b = b; this.c = c; } } ContentCleaner.java000066400000000000000000000036231475274123300352170ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; import com.univocity.parsers.common.input.*; import com.univocity.parsers.conversions.*; import java.util.*; public class ContentCleaner implements Conversion { private final char[] charsToRemove; private final char min; private final char max; public ContentCleaner(String[] args) { charsToRemove = args[0].toCharArray(); Arrays.sort(charsToRemove); min = charsToRemove[0]; max = charsToRemove[charsToRemove.length - 1]; } @Override public String execute(Object input) { return clean(input); } @Override public Object revert(String input) { return clean(input); } private String clean(Object input){ String result = String.valueOf(input); StringBuilder out = null; for(int i = 0; i < result.length(); i++){ char ch = result.charAt(i); if(ch >= min && ch <= max){ if(Arrays.binarySearch(charsToRemove, ch) >= 0){ if(out == null){ out = new StringBuilder(result.length()); out.append(result, 0, i); } } } else if (out != null){ out.append(ch); } } if(out != null){ result = out.toString(); } return result; } } IntArray.java000066400000000000000000000017711475274123300340460ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface IntArray { int[] ints(); } MetaAnnotationTest.java000066400000000000000000000050751475274123300360770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.csv.*; import com.univocity.parsers.fixed.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; /** * @author Univocity Software Pty Ltd - dev@univocity.com */ public class MetaAnnotationTest { @Test public void testParseWithMetaAnnotation() throws Exception { BeanListProcessor rowProcessor = new BeanListProcessor(ReplacementBean.class); CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.getFormat().setLineSeparator("\n"); parserSettings.setProcessor(rowProcessor); CsvParser parser = new CsvParser(parserSettings); parser.parse(new StringReader("a,BB,x,y,z\n`Va`,`Vb`,,,`vc`")); List beans = rowProcessor.getBeans(); assertEquals(beans.size(), 1); assertEquals(beans.get(0).a, "Va"); assertEquals(beans.get(0).b, "VB"); assertEquals(beans.get(0).c, "VC"); } @Test public void testWriteWithMetaAnnotation() throws Exception { BeanWriterProcessor rowProcessor = new BeanWriterProcessor(ReplacementBean.class); CsvWriterSettings settings = new CsvWriterSettings(); settings.getFormat().setLineSeparator("\n"); settings.setRowWriterProcessor(rowProcessor); StringWriter out = new StringWriter(); CsvWriter writer = new CsvWriter(out, settings); List beans = new ArrayList(); beans.add(new ReplacementBean("iii4", "blah blah", "`c`")); beans.add(new ReplacementBean("zzz7674", "etc", "`c`")); writer.processRecordsAndClose(beans); assertEquals(out.toString(), "" + "iii4,BLAH BLAH,,,C\n" + "zzz7674,ETC,,,C\n"); } } MyReplacement.java000066400000000000000000000024701475274123300350570ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; import com.univocity.parsers.annotations.*; import java.lang.annotation.*; /** * @author Univocity Software Pty Ltd - dev@univocity.com */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Replace(expression = "`", replacement = "") @Parsed public @interface MyReplacement { @Copy(to = Parsed.class) String field() default ""; @Copy(to = Parsed.class, property = "index") int myIndex() default -1; } MyReplacementUpperCase.java000066400000000000000000000024671475274123300366750ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; import com.univocity.parsers.annotations.*; import java.lang.annotation.*; /** * @author Univocity Software Pty Ltd - dev@univocity.com */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @MyReplacement @UpperCase @Trim public @interface MyReplacementUpperCase { @Copy(to = MyReplacement.class) String field() default ""; @Copy(to = MyReplacement.class, property = "myIndex") int idx() default -1; } ReplacementBean.java000066400000000000000000000023141475274123300353340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/annotations/meta/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.annotations.meta; /** * @author Univocity Software Pty Ltd - dev@univocity.com */ public class ReplacementBean { @MyReplacement public String a; @MyReplacementUpperCase(field = "BB") public String b; @MyReplacementUpperCase(idx = 4) public String c; public ReplacementBean(String a, String b, String c) { this.a = a; this.b = b; this.c = c; } public ReplacementBean() { } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/000077500000000000000000000000001475274123300275305ustar00rootroot00000000000000AbstractWriterTest.java000066400000000000000000000124471475274123300341240ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.ParserTestCase; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import com.univocity.parsers.fixed.*; import com.univocity.parsers.fixed.FixedWidthFields; import org.testng.annotations.Test; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEqualsNoOrder; public class AbstractWriterTest extends ParserTestCase { @Test public void testWriteRowWithObjectCollection() throws IOException { FixedWidthWriterSettings settings = new FixedWidthWriterSettings(new FixedWidthFields(4, 4)); settings.getFormat().setLineSeparator("\n"); File file = File.createTempFile("test", "csv"); FixedWidthWriter writer = new FixedWidthWriter(file, settings); Collection objects = new ArrayList(); objects.add("A"); objects.add("B"); writer.writeRow(objects); writer.close(); assertEquals(readFileContent(file), "A B \n"); } @Test public void testWriteRowWithNullObjectCollection() throws IOException { FixedWidthWriterSettings settings = new FixedWidthWriterSettings(new FixedWidthFields(4, 4)); settings.getFormat().setLineSeparator("\n"); File file = File.createTempFile("test", "csv"); FixedWidthWriter writer = new FixedWidthWriter(file, settings); Collection objects = null; writer.writeRow(objects); writer.close(); assertEquals(readFileContent(file), ""); } @Test public void testWriteStringRows() throws IOException { FixedWidthWriterSettings settings = new FixedWidthWriterSettings(new FixedWidthFields(4, 4)); settings.getFormat().setLineSeparator("\n"); settings.addFormatForLookahead("MASTER", new FixedWidthFields(3, 3, 3, 3)); File file = File.createTempFile("test", "csv"); FixedWidthWriter writer = new FixedWidthWriter(file, settings); List> rows = new ArrayList>(); rows.add(Arrays.asList("A", "B")); rows.add(Arrays.asList("C", "D")); writer.writeStringRows(rows); writer.close(); assertEquals(readFileContent(file), "A B \nC D \n"); } @Test public void testWriteBufferedWriter() throws IOException { FixedWidthWriterSettings settings = new FixedWidthWriterSettings(new FixedWidthFields(3, 3)); settings.getFormat().setLineSeparator("\n"); File file = File.createTempFile("test", "csv"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file)); FixedWidthWriter writer = new FixedWidthWriter(bufferedWriter, settings); writer.writeRow("Ã", "É"); writer.close(); assertEquals(readFileContent(file), "Ã É \n"); } @Test public void testRowExpansion() { StringWriter output = new StringWriter(); CsvWriterSettings settings = new CsvWriterSettings(); settings.setExpandIncompleteRows(true); settings.getFormat().setLineSeparator("\n"); settings.setHeaderWritingEnabled(true); settings.setHeaders("A", "B", "C", "D", "E", "F"); CsvWriter writer = new CsvWriter(output, settings); writer.writeRow(); writer.writeRow("V1", "V2", "V3"); writer.writeRow("V1", "V2", "V3", 4, 5); writer.writeRow("V1", "V2", "V3", 4, 5, 6); writer.close(); assertEquals(output.toString(), "A,B,C,D,E,F\n,,,,,\nV1,V2,V3,,,\nV1,V2,V3,4,5,\nV1,V2,V3,4,5,6\n"); } @Test public void testSelectFields() { StringWriter output = new StringWriter(); CsvWriterSettings settings = new CsvWriterSettings(); settings.setHeaderWritingEnabled(true); settings.setColumnReorderingEnabled(true); settings.setHeaders("A", "B", "C"); settings.selectFields("A", "C"); CsvWriter writer = new CsvWriter(output, settings); writer.writeRow("V1", "V2", "V3"); writer.writeRow("V1", "V2", "V3"); writer.writeRow("V1", "V2", "V3"); writer.close(); assertEquals(output.toString(), "A,C\nV1,V3\nV1,V3\nV1,V3\n"); } @Test public void testExcludeFields() { StringWriter output = new StringWriter(); CsvWriterSettings settings = new CsvWriterSettings(); settings.setHeaderWritingEnabled(true); settings.setColumnReorderingEnabled(true); settings.setHeaders("A", "B", "C"); settings.excludeFields("B"); CsvWriter writer = new CsvWriter(output, settings); writer.writeRow("V1", "V2", "V3"); writer.writeRow("V1", "V2", "V3"); writer.writeRow("V1", "V2", "V3"); writer.close(); assertEquals(output.toString(), "A,C\nV1,V3\nV1,V3\nV1,V3\n"); } }DataProcessingExceptionTest.java000066400000000000000000000070661475274123300357520ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; public class DataProcessingExceptionTest { @Test public void testRestrictionOfValuesDisplayedInErrorMessage() { String[] headers = new String[]{"aaaa", "bbbb", "cccc"}; DataProcessingException ex = new DataProcessingException("{x}boom: '{value}' is broken. Headers: {headers}"); assertEquals(ex.getMessage(), "" + "{x}boom: '{value}' is broken. Headers: {headers}"); ex.setValue("Mary had a little lamb"); assertEquals(ex.getMessage(), "" + "{x}boom: 'Mary had a little lamb' is broken. Headers: {headers}\n" + "Internal state when error was thrown: value=Mary had a little lamb"); ex.setErrorContentLength(14); assertEquals(ex.getMessage(), "" + "{x}boom: '... a little lamb' is broken. Headers: {headers}\n" + "Internal state when error was thrown: value=... a little lamb"); ex.setValue("headers", headers); assertEquals(ex.getMessage(), "" + "{x}boom: '... a little lamb}' is broken. Headers: ...a, bbbb, cccc]\n" + "Internal state when error was thrown: value=... a little lamb"); ex.setErrorContentLength(0); assertEquals(ex.getMessage(), "" + "{x}boom: '{value}' is broken. Headers: {headers}"); } @Test public void testRestrictionOfValuesDisplayedInErrorMessageWhileParsing() { CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setErrorContentLength(0); BeanListProcessor beanProcessor = new BeanListProcessor(A.class); parserSettings.getFormat().setLineSeparator("\n"); parserSettings.setProcessor(beanProcessor); CsvParser parser = new CsvParser(parserSettings); try { parser.parse(new StringReader("AA,BB\nA,B\nC,D,\n1,true")); } catch (DataProcessingException e) { assertFalse(e.getMessage().contains("Unable to set value 'A'")); } } @Test public void testRestrictionOfValuesDisplayedInErrorMessageWhileWriting() { CsvWriterSettings writerSettings = new CsvWriterSettings(); writerSettings.setErrorContentLength(0); BeanWriterProcessor beanProcessor = new BeanWriterProcessor(A.class); writerSettings.getFormat().setLineSeparator("\n"); writerSettings.setHeaders("AA", "BB"); writerSettings.setRowWriterProcessor(beanProcessor); CsvWriter writer = new CsvWriter(new StringWriter(), writerSettings); try { writer.processRecordsAndClose(new Object[]{"I'm not a bean", null, new A(new Date())}); } catch (DataProcessingException e) { assertFalse(e.getMessage().contains("I'm not a bean")); } } public static class A { @Parsed(field = "AA") private Date a; public A(){ } public A(Date a) { this.a = a; } } }NormalizedStringTest.java000066400000000000000000000176141475274123300344600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/******************************************************************************* * Copyright 2019 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common; import org.testng.annotations.*; import java.util.*; import static org.testng.Assert.*; public class NormalizedStringTest { private NormalizedString A = NormalizedString.valueOf("A"); private NormalizedString a = NormalizedString.valueOf("a"); private NormalizedString _a_ = NormalizedString.valueOf(" a "); private NormalizedString _A_ = NormalizedString.valueOf(" A "); NormalizedString[] normalized = new NormalizedString[]{A, a, _a_, _A_}; private NormalizedString dA = NormalizedString.literalValueOf("A"); private NormalizedString da = NormalizedString.literalValueOf("a"); private NormalizedString d_a_ = NormalizedString.literalValueOf(" a "); private NormalizedString d_A_ = NormalizedString.literalValueOf(" A "); NormalizedString[] literal = new NormalizedString[]{dA, da, d_a_, d_A_}; @Test public void testEqualsHashCodeContract() throws Exception { for (int i = 0; i < normalized.length; i++) { for (int j = 0; j < normalized.length; j++) { assertEquals(normalized[i], normalized[j]); assertEquals(normalized[j], normalized[i]); assertEquals(normalized[i].hashCode(), normalized[j].hashCode()); } } for (int i = 0; i < literal.length; i++) { for (int j = 0; j < literal.length; j++) { if (i == j) { assertEquals(literal[i], literal[j]); assertEquals(literal[j], literal[i]); assertEquals(literal[i].hashCode(), literal[j].hashCode()); } else { assertFalse(literal[i].equals(literal[j])); assertFalse(literal[j].equals(literal[i])); } } } for (int i = 0; i < normalized.length; i++) { if (normalized[i].equals(literal[i])) { assertEquals(literal[i], normalized[i]); assertEquals(normalized[i].hashCode(), literal[i].hashCode()); } else { assertNotEquals(literal[i], normalized[i]); } } } @Test public void testCompareToContract() throws Exception { for (int i = 0; i < normalized.length; i++) { for (int j = 0; j < normalized.length; j++) { assertEquals(normalized[i], normalized[j]); assertTrue(normalized[i].compareTo(normalized[j]) == 0); } } for (int i = 0; i < literal.length; i++) { for (int j = 0; j < literal.length; j++) { if (i == j) { assertEquals(literal[i], literal[j]); assertTrue(literal[i].compareTo(literal[j]) == 0); } else { assertFalse(literal[i].equals(literal[j])); assertFalse(literal[i].compareTo(literal[j]) == 0); } } } for (int i = 0; i < normalized.length; i++) { if (normalized[i].equals(literal[i])) { assertTrue(normalized[i].compareTo(literal[i]) == 0); } else { assertFalse(normalized[i].compareTo(literal[i]) == 0); } } } @DataProvider private Object[][] setProvider() { return new Object[][]{ {new HashSet(), "HashSet"}, {new TreeSet(), "TreeSet"} }; } @Test(dataProvider = "setProvider") public void testSetBehaves(Set set, String name) { Collections.addAll(set, normalized); // 1 assertEquals(set.size(), 1); //hashcode & equals are the same for all elements, so we'll end up with just one. for (NormalizedString element : normalized) { assertTrue(set.contains(element)); } int count = 0; for (NormalizedString element : literal) { if (set.contains(element)) { count++; } } assertEquals(count, 1); // only one literal element will match because the original strings are compared and if they match then the NormalizedString always matches. Collections.addAll(set, literal); assertEquals(set.size(), literal.length); //all literal elements should be in the set for (NormalizedString element : normalized) { assertTrue(set.contains(element)); //normalized Strings should all be found here } for (NormalizedString element : literal) { assertTrue(set.contains(element)); //literal Strings should all be found here } } @Test public void testComparisonForOrdering() { TreeSet set = new TreeSet(); Collections.addAll(set, literal); TreeSet stringSet = new TreeSet(); for (NormalizedString element : literal) { stringSet.add(element.toString()); } assertEquals(stringSet.toString(), set.toString()); set.add(NormalizedString.valueOf("0")); set.add(NormalizedString.literalValueOf(" 0")); set.add(NormalizedString.literalValueOf("Z")); set.add(NormalizedString.valueOf("z")); stringSet.add("0"); stringSet.add(" 0"); stringSet.add("Z"); stringSet.add("z"); assertEquals(set.toString(), stringSet.toString()); } @Test public void testHashMap() { Map map = new HashMap(); putString(map, "A"); putString(map, "'a'"); //literal assertEquals(map.get(NormalizedString.valueOf("A")), "A"); assertEquals(map.get(NormalizedString.literalValueOf("A")), "A"); assertEquals(map.get(NormalizedString.valueOf("'a'")), "'a'"); assertEquals(map.get(NormalizedString.literalValueOf("a")), "'a'"); // Unspecified behavior here as A and 'a' clash (A should be a literal in this test, but it isn't). // A normalized, non literal 'a' can match either the literal 'a' or the normalized A, depending on the // HashMap implementation. These entries have the same hashcode and the equals method will // compare this: // Search entry: // NormalizedString.valueOf("a") - not a literal, normalized value = a // Keys in map // NormalizedString.valueOf("A") - not literal, normalized value = a (will match) // NormalizedString.valueOf("'a'") - literal, original value = a (will also match) // The entry picked up first by the map implementation will be returned. // On JDK 6 this is the expected output: // assertEquals(map.get(NormalizedString.valueOf("a")), "'a'"); // On JDK 8 the expected output is: // assertEquals(map.get(NormalizedString.valueOf("a")), "A"); } @Test public void testTreeMap() { Map map = new TreeMap(); putString(map, "A"); putString(map, "'a'"); //literal assertEquals(map.get(NormalizedString.valueOf("A")), "A"); assertEquals(map.get(NormalizedString.literalValueOf("A")), "A"); assertEquals(map.get(NormalizedString.valueOf("'a'")), "'a'"); assertEquals(map.get(NormalizedString.literalValueOf("a")), "'a'"); assertEquals(map.get(NormalizedString.valueOf("a")), "A"); //compareTo implementation will run a compareTo against normalized values (normalized against normalized) } private void putString(Map map, String str) { map.put(NormalizedString.valueOf(str), str); } @Test public void identifyLiterals(){ NormalizedString[] s = NormalizedString.toArray("a", "A", " a ", " A ", "a ", "A ", "B"); Set set = new HashSet(); Collections.addAll(set, s); assertEquals(set.size(), 2); NormalizedString.identifyLiterals(s); assertTrue(s[0].isLiteral()); assertTrue(s[1].isLiteral()); assertTrue(s[2].isLiteral()); assertTrue(s[3].isLiteral()); assertTrue(s[4].isLiteral()); assertTrue(s[5].isLiteral()); assertFalse(s[6].isLiteral()); set = new HashSet(); Collections.addAll(set, s); assertEquals(set.size(), 7); } }jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/000077500000000000000000000000001475274123300307765ustar00rootroot00000000000000ExcludeFieldEnumSelectorTest.java000066400000000000000000000023401475274123300373040ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import org.testng.annotations.*; import static org.testng.Assert.*; public class ExcludeFieldEnumSelectorTest { @Test public void getFieldsToExtract() { ExcludeFieldEnumSelector selector = new ExcludeFieldEnumSelector(); selector.add(TestEnum.D, TestEnum.A); int[] indexes = selector.getFieldIndexes(new String[]{"A", "B", "C", "D", "E", "F"}); int[] expected = new int[]{1, 2, 4, 5}; assertEquals(indexes, expected); } } ExcludeFieldNameSelectorTest.java000066400000000000000000000023221475274123300372600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import org.testng.annotations.*; import static org.testng.Assert.*; public class ExcludeFieldNameSelectorTest { @Test public void getFieldsToExtract() { ExcludeFieldNameSelector selector = new ExcludeFieldNameSelector(); selector.add("D", "A"); int[] indexes = selector.getFieldIndexes(new String[]{"A", "B", "C", "D", "E", "F"}); int[] expected = new int[]{1, 2, 4, 5}; assertEquals(indexes, expected); } } ExcludeIndexSelectorTest.java000066400000000000000000000023221475274123300365030ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import org.testng.annotations.*; import static org.testng.Assert.*; public class ExcludeIndexSelectorTest { @Test public void getFieldsToExtract() { ExcludeFieldIndexSelector selector = new ExcludeFieldIndexSelector(); selector.add(3, 0); int[] indexes = selector.getFieldIndexes(new String[]{null, null, null, null, null, null}); int[] expected = new int[]{1, 2, 4, 5}; assertEquals(indexes, expected); } } FieldEnumSelectorTest.java000066400000000000000000000023051475274123300357730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import org.testng.annotations.*; import static org.testng.Assert.*; public class FieldEnumSelectorTest { @Test public void getFieldsToExtract() { FieldEnumSelector selector = new FieldEnumSelector(); selector.add(TestEnum.D, TestEnum.A); int[] indexes = selector.getFieldIndexes(new String[]{"A", "B", "C", "D", "E", "F"}); int[] expected = new int[]{3, 0}; assertEquals(indexes, expected); } } FieldIndexSelectorTest.java000066400000000000000000000022741475274123300361430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import org.testng.annotations.*; import static org.testng.Assert.*; public class FieldIndexSelectorTest { @Test public void getFieldsToExtract() { FieldIndexSelector selector = new FieldIndexSelector(); selector.add(3, 0); int[] indexes = selector.getFieldIndexes(new String[]{null, null, null, null, null, null}); int[] expected = new int[]{3, 0}; assertEquals(indexes, expected); } } FieldNameSelectorTest.java000066400000000000000000000045741475274123300357610ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; import org.testng.annotations.*; import java.util.*; import static org.testng.Assert.*; public class FieldNameSelectorTest { @Test public void getFieldsToExtract() { FieldNameSelector selector = new FieldNameSelector(); selector.add("D", "A"); int[] indexes = selector.getFieldIndexes(new String[]{"A", "B", "C", "D", "E", "F"}); int[] expected = new int[]{3, 0}; assertEquals(indexes, expected); } @Test public void getFieldsToExtract2() { String[] fields = new String[]{"SellerID", "Brand", "MPN", "SoldPrice", "Shipping", "TotalAmount", "Currency", "SoldPriceUSD", "ShippingUSD", "TotalAmountUSD", "SoldQuantity", "Condition", "Format", "SoldDate", "ProductRating", "UPC", "EAN", "ItemLocation", "Title", "PictureURL", "ListingURL"}; String[] selection = new String[]{"Format", "PictureURL", "SellerID", "SoldDate", "ListingURL", "Currency", "Condition", "Title", "BidPrice", "SoldPrice", "SoldPriceUSD", "SystemCurrency", "SoldPriceDiscounted", "Shipping", "ShippingUSD", "TotalAmount", "TotalAmountUSD", "SoldQuantity", "ProductRating", "Brand", "EAN", "UPC", "MPN", "ItemLocation", "SellerID", "SellerFeedback", "StockQuantity", "eBayItemNumber", "PicURL1", "PicURL2", "PicURL3", "PicURL4", "PicURL5", "PicURL6", "PicURL7", "PicURL8", "PicURL9", "PicURL10"}; FieldNameSelector selector = new FieldNameSelector(); selector.add(selection); int[] indexes = selector.getFieldIndexes(fields); assertEquals(Arrays.toString(indexes), "[12, 19, 0, 13, 20, 6, 11, 18, -1, 3, 7, -1, -1, 4, 8, 5, 9, 10, 14, 1, 16, 15, 2, 17, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]"); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/fields/TestEnum.java000066400000000000000000000015221475274123300334050ustar00rootroot00000000000000/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.fields; public enum TestEnum { A, B, C, D, E, F } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/input/000077500000000000000000000000001475274123300306675ustar00rootroot00000000000000DefaultCharInputReaderTest.java000066400000000000000000000054311475274123300366430ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import org.testng.annotations.*; import java.io.*; import static org.testng.Assert.*; public class DefaultCharInputReaderTest { private void assertEOF(DefaultCharInputReader reader) { try { reader.nextChar(); fail("Expected EOFException"); } catch (EOFException ex) { //pass } } @Test public void testInputReading() { DefaultCharInputReader reader = new DefaultCharInputReader("\n\r".toCharArray(), '\n', 2, -1, true); reader.start(new StringReader("a")); assertEquals('a', reader.nextChar()); assertEquals(reader.lastIndexOf('a'), 0); assertEquals(reader.lastIndexOf('b'), -1); assertEOF(reader); reader.start(new StringReader("ab")); assertEquals('a', reader.nextChar()); assertEquals('b', reader.nextChar()); assertEquals(reader.lastIndexOf('a'), 0); assertEquals(reader.lastIndexOf('b'), 1); assertEOF(reader); reader.start(new StringReader("a\n\r")); assertEquals('a', reader.nextChar()); assertEquals('\n', reader.nextChar()); assertEOF(reader); assertEquals(reader.lastIndexOf('a'), 0); assertEquals(reader.lastIndexOf('\n'), 1); reader.start(new StringReader("a\r\n")); assertEquals('a', reader.nextChar()); assertEquals(reader.lastIndexOf('a'), 0); assertEquals('\r', reader.nextChar()); assertEquals(reader.lastIndexOf('\r'), 1); assertEquals('\n', reader.nextChar()); assertEquals(reader.lastIndexOf('\n'), 2); assertEOF(reader); assertEquals(reader.lastIndexOf('a'), 0); assertEquals(reader.lastIndexOf('\r'), 1); assertEquals(reader.lastIndexOf('\n'), 2); reader.start(new StringReader("\n\ra")); assertEquals('\n', reader.nextChar()); assertEquals('a', reader.nextChar()); assertEOF(reader); assertEquals(reader.lastIndexOf('\n'), 0); assertEquals(reader.lastIndexOf('\r'), 1); assertEquals(reader.lastIndexOf('a'), 2); reader.start(new StringReader("\n\r")); assertEquals('\n', reader.nextChar()); assertEquals(reader.lastIndexOf('\n'), 0); assertEquals(reader.lastIndexOf('\r'), 1); assertEOF(reader); } } ExpandingCharAppenderTest.java000066400000000000000000000137051475274123300365130ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import org.testng.annotations.*; import static org.testng.Assert.*; public class ExpandingCharAppenderTest { @Test public void testAppendIgnoringWhitespace() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(2, null, -1); assertEquals(a.chars.length, 2); a.append('a'); a.append('b'); a.appendIgnoringWhitespace(' '); assertEquals(a.toString(), "ab"); assertEquals(a.chars.length, 6); a.appendIgnoringWhitespace('c'); a.appendIgnoringWhitespace(' '); assertEquals(a.toString(), "ab c"); assertEquals(a.chars.length, 6); } @Test public void testAppendIgnoringPadding() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(1, null, -1); assertEquals(a.chars.length, 1); a.append('_'); a.append('b'); a.appendIgnoringPadding('_', '_'); assertEquals(a.toString(), "_b"); assertEquals(a.chars.length, 4); a.appendIgnoringPadding('a', '_'); assertEquals(a.toString(), "_b_a"); assertEquals(a.chars.length, 4); } @Test public void testAppendIgnoringWhitespaceAndPadding() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(1, null, -1); assertEquals(a.chars.length, 1); a.append('_'); a.append('b'); a.appendIgnoringWhitespaceAndPadding(' ', '_'); assertEquals(a.toString(), "_b"); assertEquals(a.chars.length, 4); a.appendIgnoringWhitespaceAndPadding('_', '_'); assertEquals(a.toString(), "_b"); assertEquals(a.chars.length, 4); a.appendIgnoringWhitespaceAndPadding('c', '_'); assertEquals(a.toString(), "_b _c"); assertEquals(a.chars.length, 10); } @Test public void testAppend() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(1, null, -1); a.append('a'); assertEquals(a.toString(), "a"); assertEquals(a.chars.length, 1); a.append('b'); assertEquals(a.toString(), "ab"); assertEquals(a.chars.length, 4); a.append('c'); a.append('d'); a.append('e'); assertEquals(a.toString(), "abcde"); assertEquals(a.chars.length, 10); } @Test public void testFill() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(2, null, -1); a.fill('*', 2); assertEquals(a.toString(), "**"); assertEquals(a.chars.length, 2); a.fill('*', 4); assertEquals(a.toString(), "******"); assertEquals(a.chars.length, 6); a.fill('*', 1); assertEquals(a.toString(), "*******"); assertEquals(a.chars.length, 14); } @Test public void testPrepend() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(2, null, -1); a.prepend('a'); assertEquals(a.toString(), "a"); assertEquals(a.chars.length, 2); a.prepend('b'); assertEquals(a.toString(), "ba"); assertEquals(a.chars.length, 2); a.prepend('c'); assertEquals(a.toString(), "cba"); assertEquals(a.chars.length, 4); a.prepend("12345678890".toCharArray()); assertEquals(a.toString(), "12345678890cba"); } @Test public void testAppend1() throws Exception { ExpandingCharAppender a = new ExpandingCharAppender(2, null, -1); ExpandingCharAppender b = new ExpandingCharAppender(2, null, -1); a.append(b); assertEquals(a.toString(), null); assertEquals(a.chars.length, 2); b.append('a'); b.append('b'); a.append(b); //whitespaceRangeStart gets reset here assertEquals(a.toString(), "ab"); assertEquals(a.chars.length, 2); a.append(b); //should make no difference assertEquals(a.toString(), "ab"); assertEquals(a.chars.length, 2); assertEquals(b.toString(), null); assertEquals(b.chars.length, 2); b.append('c'); b.append('d'); a.append(b); assertEquals(a.toString(), "abcd"); assertEquals(a.chars.length, 6); assertEquals(b.toString(), null); assertEquals(b.chars.length, 2); } @Test public void testAppendArray() { ExpandingCharAppender a = new ExpandingCharAppender(2, null, -1); a.append("abc".toCharArray(), 0, 3); assertEquals(a.toString(), "abc"); assertEquals(a.chars.length, 5); a.append("defghi".toCharArray(), 0, 3); assertEquals(a.toString(), "abcdef"); a.append("defghi".toCharArray(), 4, 2); assertEquals(a.toString(), "abcdefhi"); a.append("012345678901234567890123456789012345678901234567890123456789".toCharArray(), 0, 60); assertEquals(a.toString(), "abcdefhi012345678901234567890123456789012345678901234567890123456789"); } @Test public void testRemove(){ ExpandingCharAppender a = new ExpandingCharAppender(10, null, -1); a.append("0123456789"); a.remove(0, 0); assertEquals(a.toString(), "0123456789"); a.remove(10, 0); assertEquals(a.toString(), "0123456789"); a.remove(0, 1); assertEquals(a.toString(), "123456789"); a.remove(8, 1); assertEquals(a.toString(), "12345678"); a.remove(2, 3); assertEquals(a.toString(), "12678"); a.remove(1, 2); assertEquals(a.toString(), "178"); a.remove(1, 1); assertEquals(a.toString(), "18"); a.remove(1, 1); assertEquals(a.toString(), "1"); a.remove(0, 1); assertEquals(a.toString(), null); a.append("0123456789"); a.remove(1, 1); assertEquals(a.toString(), "023456789"); a.remove(1, 4); assertEquals(a.toString(), "06789"); a.reset(); a.append("0123456789"); a.remove(1, 7); assertEquals(a.toString(), "089"); a.remove(0, 3); assertEquals(a.toString(), null); } }LookaheadCharInputReaderTest.java000066400000000000000000000046761475274123300371600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/input/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.input; import org.testng.annotations.*; import java.io.*; import static org.testng.Assert.*; public class LookaheadCharInputReaderTest { @Test public void testLookahead() { LookaheadCharInputReader reader = new LookaheadCharInputReader(new DefaultCharInputReader("\n\r".toCharArray(), '\n', 2, -1, true), '\n', -1); reader.start(new StringReader("abcdefgh")); assertEquals(reader.nextChar(), 'a'); reader.lookahead(1); reader.lookahead(1); assertTrue(reader.matches(new char[]{'b', 'c'}, '?')); assertTrue(reader.matches(new char[]{'b'}, '?')); assertFalse(reader.matches(new char[]{'c'}, '?')); assertFalse(reader.matches(new char[]{'a', 'b'}, '?')); assertFalse(reader.matches(new char[]{'c', 'd'}, '?')); assertEquals(reader.nextChar(), 'b'); assertFalse(reader.matches(new char[]{'b'}, '?')); assertTrue(reader.matches(new char[]{'c'}, '?')); assertEquals(reader.nextChar(), 'c'); assertFalse(reader.matches(new char[]{'c'}, '?')); assertFalse(reader.matches(new char[]{'d'}, '?')); assertEquals(reader.nextChar(), 'd'); assertEquals(reader.nextChar(), 'e'); reader.lookahead(5); assertTrue(reader.matches(new char[]{'f', 'g', 'h'}, '?')); assertTrue(reader.matches(new char[]{'f', 'g'}, '?')); assertTrue(reader.matches(new char[]{'f'}, '?')); assertEquals(reader.nextChar(), 'f'); assertEquals(reader.nextChar(), 'g'); assertTrue(reader.matches(new char[]{'h'}, '?')); assertEquals(reader.nextChar(), 'h'); assertFalse(reader.matches(new char[]{'f'}, '?')); try { char ch = reader.nextChar(); fail("Expected EOFException after end of the input. Got char: " + ch); } catch (EOFException ex) { //pass } } } WriterCharAppenderTest.java000066400000000000000000000036221475274123300360470ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/input/* * Copyright 2016 Univocity Software Pty Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.input; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import java.io.StringWriter; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; public class WriterCharAppenderTest { @Test public void testAppendAndExpandWhenAppendingChar() { CsvWriterSettings settings = new CsvWriterSettings(); settings.getFormat().setLineSeparator("\n"); settings.getFormat().setDelimiter('\t'); settings.setMaxCharsPerColumn(16); // note default max length before expanding settings.getFormat().setQuote('"'); settings.getFormat().setQuoteEscape('"'); settings.setIgnoreLeadingWhitespaces(false); settings.setIgnoreTrailingWhitespaces(false); settings.setQuoteAllFields(true); settings.setEmptyValue(""); StringWriter stringWriter = new StringWriter(); CsvWriter writer = new CsvWriter(stringWriter, settings); // test data's first column length is specific to repro bug occuring due to // appending quote character occuring at writer buffer boundary String[] testCase = {"abcdefghijklmno", "pqrst", "uvwxyz"}; String expectedString = "\"abcdefghijklmno\"\t\"pqrst\"\t\"uvwxyz\"\n"; writer.writeRow(testCase); writer.close(); assertEquals(stringWriter.toString(), expectedString); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/000077500000000000000000000000001475274123300315475ustar00rootroot00000000000000AnnotatedBeanProcessorTest.java000077500000000000000000000127231475274123300376060ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.annotations.*; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.lang.annotation.*; import java.math.*; import java.util.*; import static org.testng.Assert.*; public class AnnotatedBeanProcessorTest { String input = "date,amount,quantity,pending,comments,active\n" + "10-oct-2001,555.999,1,yEs,?,n\n" + "2001-10-10,,?,N,\" \"\" something \"\" \",true"; @Trim @UpperCase @BooleanString(falseStrings = "N", trueStrings = {"TRUE", "Y"}) @Parsed @Retention(RetentionPolicy.RUNTIME) @Inherited @Target(value = {ElementType.FIELD}) public @interface MetaBoolean { } public static class TestBean { @Parsed(defaultNullRead = "0") Integer quantity; @Trim(length = 8) @LowerCase @Parsed(index = 4) String commts; @Parsed(field = "amount") BigDecimal amnt; @Trim @LowerCase @BooleanString(falseStrings = {"no", "n", "null"}, trueStrings = {"yes", "y"}) @Parsed Boolean pending; @MetaBoolean Boolean active; @BooleanString(falseStrings = "0", trueStrings = "1") @Parsed Boolean other; } protected CsvParserSettings newCsvInputSettings() { return new CsvParserSettings(); } @Test public void testAnnotatedBeanProcessor() { BeanListProcessor processor = new BeanListProcessor(TestBean.class); processor.convertAll(Conversions.toNull("", "?")); CsvParserSettings settings = newCsvInputSettings(); settings.getFormat().setLineSeparator("\n"); settings.excludeIndexes(0); StringReader reader = new StringReader(input); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); CsvParser parser = new CsvParser(settings); parser.parse(reader); List beans = processor.getBeans(); assertEquals(beans.size(), 2); TestBean bean; bean = beans.get(0); assertEquals(bean.amnt, new BigDecimal("555.999")); assertEquals(bean.quantity, (Object) 1); assertTrue(bean.pending); assertNull(bean.commts); bean = beans.get(1); assertEquals(bean.amnt, null); assertEquals(bean.quantity, (Object) 0); assertFalse(bean.pending); assertEquals(bean.commts, "\" someth"); // trimmed to 8 characters } @Test public void testAnnotatedBeanWithLessColumns() { BeanListProcessor processor = new BeanListProcessor(TestBean.class); CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\n"); settings.setProcessor(processor); StringReader reader = new StringReader("active,other\n,1\n,,\ny,0"); CsvParser parser = new CsvParser(settings); parser.parse(reader); List beans = processor.getBeans(); assertTrue(beans.get(0).other); assertNull(beans.get(1).other); assertFalse(beans.get(2).other); } @Test public void testAnnotatedBeanProcessorWithOneFieldOnly() { BeanListProcessor processor = new BeanListProcessor(TestBean.class); processor.convertAll(Conversions.toNull("", "?")); CsvParserSettings settings = newCsvInputSettings(); settings.getFormat().setLineSeparator("\n"); settings.setColumnReorderingEnabled(true); settings.selectIndexes(1); StringReader reader = new StringReader(input); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); CsvParser parser = new CsvParser(settings); parser.parse(reader); List beans = processor.getBeans(); assertEquals(beans.size(), 2); TestBean bean; bean = beans.get(0); assertEquals(bean.amnt, new BigDecimal("555.999")); assertEquals(bean.quantity, Integer.valueOf(0)); assertNull(bean.pending); assertNull(bean.commts); bean = beans.get(1); assertEquals(bean.amnt, null); assertEquals(bean.quantity, Integer.valueOf(0)); assertNull(bean.pending); assertNull(bean.commts); } public static class Data { @Parsed(index = 0) public String value; @Parsed(index = 1) public String foo; @Nested MetaData metaData; } public static class MetaData { @Parsed(index = 1) public String title; } @Test public void testRepeatedIndexInAnnotation() { BeanListProcessor rowProcessor = new BeanListProcessor(Data.class); CsvParserSettings settings = new CsvParserSettings(); settings.setProcessor(rowProcessor); settings.setLineSeparatorDetectionEnabled(true); CsvParser parser = new CsvParser(settings); parser.parseAll(new StringReader("a1,b1,c1\na2,b2,c2\na3,b3,c3")); List beans = rowProcessor.getBeans(); for (int i = 1; i <= beans.size(); i++) { Data bean = beans.get(i - 1); assertEquals(bean.value, "a" + i); assertEquals(bean.foo, "b" + i); assertEquals(bean.metaData.title, "b" + i); } } } BatchedColumnProcessorTest.java000066400000000000000000000051021475274123300376010ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; public class BatchedColumnProcessorTest { private static final String INPUT = "" + "A,B,C" + "\n1A,1B,1C" + "\n2A,2B" + "\n3A,3B,3C" + "\n4A,4B,4C,4D"; @Test public void testColumnValues() { final String[][] expectedValueOnFirstBatch = new String[][]{ {"1A", "2A"}, {"1B", "2B"}, {"1C", null}, }; final String[][] expectedValueOnSecondBatch = new String[][]{ {"3A", "4A"}, {"3B", "4B"}, {"3C", "4C"}, {null, "4D"} }; BatchedColumnProcessor processor = new BatchedColumnProcessor(2) { @Override public void batchProcessed(int rowsInThisBatch) { List> columnValues = getColumnValuesAsList(); Map> columnsByIndex = getColumnValuesAsMapOfIndexes(); String[][] expectedValues = getBatchesProcessed() == 0 ? expectedValueOnFirstBatch : expectedValueOnSecondBatch; assertEquals(columnValues.size(), expectedValues.length); for (int i = 0; i < expectedValues.length; i++) { assertEquals(columnValues.get(i).size(), rowsInThisBatch); assertEquals(columnValues.get(i).toArray(), expectedValues[i]); assertEquals(columnsByIndex.get(i).toArray(), expectedValues[i]); } if (expectedValues.length == 4) { try { getColumnValuesAsMapOfNames(); fail("Expected exception. No name defined for 4th column"); } catch (Exception e) { //OK } } assertEquals(getHeaders(), new String[]{"A", "B", "C"}); } }; CsvParserSettings settings = new CsvParserSettings(); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); new CsvParser(settings).parse(new StringReader(INPUT)); } } BatchedObjectColumnProcessorTest.java000066400000000000000000000056151475274123300407410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.math.*; import java.util.*; import static org.testng.Assert.*; public class BatchedObjectColumnProcessorTest { private static final String INPUT = "" + "A,B,C" + "\n1,true,C" + "\n2,false" + "\n3,,C" + "\n4,false,C,55.4"; @Test public void testColumnValues() { final Object[][] expectedValueOnFirstBatch = new Object[][]{ {1, 2}, {true, false}, {'C', null}, }; final Object[][] expectedValueOnSecondBatch = new Object[][]{ {3, 4}, {null, false}, {'C', 'C'}, {null, new BigDecimal("55.4")} }; BatchedObjectColumnProcessor processor = new BatchedObjectColumnProcessor(2) { @Override public void batchProcessed(int rowsInThisBatch) { List> columnValues = getColumnValuesAsList(); Map> columnsByIndex = getColumnValuesAsMapOfIndexes(); Object[][] expectedValues = getBatchesProcessed() == 0 ? expectedValueOnFirstBatch : expectedValueOnSecondBatch; assertEquals(columnValues.size(), expectedValues.length); for (int i = 0; i < expectedValues.length; i++) { assertEquals(columnValues.get(i).size(), rowsInThisBatch); assertEquals(columnValues.get(i).toArray(), expectedValues[i]); assertEquals(columnsByIndex.get(i).toArray(), expectedValues[i]); } if (expectedValues.length == 4) { try { getColumnValuesAsMapOfNames(); fail("Expected exception. No name defined for 4th column"); } catch (Exception e) { //OK } } assertEquals(getHeaders(), new String[]{"A", "B", "C"}); } }; processor.convertFields(Conversions.toInteger()).add("A"); processor.convertFields(Conversions.toBoolean()).add("B"); processor.convertFields(Conversions.toChar()).add("C"); processor.convertIndexes(Conversions.toBigDecimal()).add(3); CsvParserSettings settings = new CsvParserSettings(); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); new CsvParser(settings).parse(new StringReader(INPUT)); } } BeanWriterProcessorTest.java000066400000000000000000000060211475274123300371340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.math.*; import static org.testng.Assert.*; public class BeanWriterProcessorTest { static class TestBean { @Parsed(defaultNullRead = "0") Integer quantity; @Trim @LowerCase @Parsed(index = 4) String commts; @Parsed(field = "amount") BigDecimal amnt; @Trim @LowerCase @BooleanString(falseStrings = {"no", "n", "null"}, trueStrings = {"yes", "y"}) @Parsed Boolean pending; } private final NormalizedString[] headers = NormalizedString.toArray("date,amount,quantity,pending,comments".split(",")); @Test public void testAnnotatedBeanProcessor() { BeanWriterProcessor processor = new BeanWriterProcessor(TestBean.class); processor.convertAll(Conversions.toNull("?")); processor.initialize(); Object[] row; TestBean bean1 = new TestBean(); bean1.amnt = new BigDecimal("555.999"); bean1.commts = null; bean1.pending = true; bean1.quantity = 1; row = processor.write(bean1, headers, null); assertEquals(row[0], "?"); // date not mapped in bean assertEquals(row[1], "555.999"); assertEquals(row[2], "1"); assertEquals(row[3], "yes"); assertEquals(row[4], "?"); TestBean bean2 = new TestBean(); bean2.amnt = null; bean2.quantity = 0; bean2.pending = false; bean2.commts = " something "; row = processor.write(bean2, headers, null); assertEquals(row[0], "?"); // date not mapped in bean assertEquals(row[1], "?"); assertEquals(row[2], "0"); assertEquals(row[3], "no"); assertEquals(row[4], "something"); // trimmed } @Test public void testRepeatedIndexInAnnotation() { BeanWriterProcessor rowProcessor = new BeanWriterProcessor(AnnotatedBeanProcessorTest.Data.class); CsvWriterSettings settings = new CsvWriterSettings(); settings.setRowWriterProcessor(rowProcessor); try { new CsvWriter(settings); fail("Expecting validation error on duplicate field"); } catch(Exception e){ assertTrue(e.getMessage().startsWith("Duplicate field index '1' found in attribute")); } } } ColumnProcessorTest.java000077500000000000000000000043631475274123300363410ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; public class ColumnProcessorTest { private static final String INPUT = "" + "A,B,C" + "\n1A,1B,1C" + "\n2A,2B" + "\n3A,3B,3C" + "\n4A,4B,4C,4D"; @Test public void testColumnValues() { ColumnProcessor processor = new ColumnProcessor(); CsvParserSettings settings = new CsvParserSettings(); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); settings.getFormat().setLineSeparator("\n"); new CsvParser(settings).parse(new StringReader(INPUT)); String[][] expectedValues = new String[][]{ {"1A", "2A", "3A", "4A"}, {"1B", "2B", "3B", "4B"}, {"1C", null, "3C", "4C"}, {null, null, null, "4D"} }; List> columnValues = processor.getColumnValuesAsList(); Map> columnsByIndex = processor.getColumnValuesAsMapOfIndexes(); assertEquals(columnValues.size(), expectedValues.length); int i = 0; for (List column : columnValues) { assertEquals(column.toArray(new String[0]), expectedValues[i]); assertEquals(columnsByIndex.get(i).toArray(new String[0]), expectedValues[i]); i++; } try { processor.getColumnValuesAsMapOfNames(); fail("Expected exception. No name defined for 4th column"); } catch (Exception e) { //OK } assertEquals(processor.getHeaders(), new String[]{"A", "B", "C"}); } } ConcurrentRowProcessorTest.java000066400000000000000000000071021475274123300377050ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; public class ConcurrentRowProcessorTest { private final int LINES = 5000; private String input; @BeforeClass public void init() throws Exception { StringBuilder bigInput = new StringBuilder("A,B,C,D,E,F,G\n"); for (int i = 0; i < LINES; i++) { bigInput.append("A").append(i); bigInput.append(",B").append(i); bigInput.append(",C").append(i); bigInput.append(",D").append(i); bigInput.append(",E").append(i); bigInput.append(",F").append(i); bigInput.append(",G").append(i); bigInput.append("\n"); } input = bigInput.toString(); } @DataProvider private Object[][] getLimits() { return new Object[][]{ {-1}, {0}, {1}, {2}, {5}, {10}, {100} }; } @Test(dataProvider = "getLimits") public void concurrentRowProcessorTest(int limit) throws Exception { ColumnProcessor processor = new ColumnProcessor(); CsvParserSettings settings = new CsvParserSettings(); settings.setLineSeparatorDetectionEnabled(true); settings.setColumnReorderingEnabled(true); Reader reader = new StringReader(input); settings.setHeaderExtractionEnabled(true); ConcurrentRowProcessor concurrentRowProcessor = new ConcurrentRowProcessor(processor, limit); settings.setProcessor(concurrentRowProcessor); CsvParser parser = new CsvParser(settings); //long start = System.currentTimeMillis(); parser.parse(reader); List> columnValues = processor.getColumnValuesAsList(); //System.out.println("Concurrently processed " + LINES + " lines in " + (System.currentTimeMillis() - start) + "ms with limit of " + limit); assertEquals(columnValues.size(), 7); for (int i = 0; i < 7; i++) { assertEquals(columnValues.get(i).size(), LINES); } } @Test public void ensureContextIsPreserved() throws Exception { CsvParserSettings settings = new CsvParserSettings(); settings.setLineSeparatorDetectionEnabled(true); settings.setColumnReorderingEnabled(true); Reader reader = new StringReader(input); settings.setHeaderExtractionEnabled(true); final StringBuilder out = new StringBuilder("A,B,C,D,E,F,G\n"); RowProcessor myProcessor = new AbstractRowProcessor(){ @Override public void rowProcessed(String[] row, ParsingContext context) { out.append(context.currentParsedContent()); } @Override public void processEnded(ParsingContext context) { assertEquals(out.toString(), input); } }; ConcurrentRowProcessor concurrent = new ConcurrentRowProcessor(myProcessor); concurrent.setContextCopyingEnabled(true); settings.setProcessor(concurrent); CsvParser parser = new CsvParser(settings); parser.parse(reader); } } MasterDetailProcessorTest.java000077500000000000000000000061731475274123300374630ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.math.*; import java.util.*; import static org.testng.Assert.*; public class MasterDetailProcessorTest { private String totalsOnTop = "type,amount\n" + "T,100\n" + "50\n" + "40\n" + "10\n" + "T,200\n" + "170\n" + "30"; private String totalsAtBottom = "type,amount\n" + "50\n" + "40\n" + "10\n" + "T,100\n" + "170\n" + "30\n" + "T,200"; @DataProvider(name = "inputsAndProcessors") private Object[][] getInputsAndProcessors() { return new Object[][]{ {totalsOnTop, getProcessor(true)}, {totalsAtBottom, getProcessor(false)}, }; } @Test(dataProvider = "inputsAndProcessors") public void testMasterDetail(String input, MasterDetailListProcessor processor) { StringReader reader = new StringReader(input); CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\n"); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); CsvParser parser = new CsvParser(settings); parser.parse(reader); List records = processor.getRecords(); assertEquals(records.size(), 2); MasterDetailRecord record; record = records.get(0); assertEquals(sumItems(record), getTotal(record)); record = records.get(1); assertEquals(sumItems(record), getTotal(record)); } private Integer getTotal(MasterDetailRecord record) { Object[] masterRow = record.getMasterRow(); return ((BigInteger) masterRow[1]).intValue(); } private Integer sumItems(MasterDetailRecord record) { List rows = record.getDetailRows(); Integer out = 0; for (Object[] row : rows) { out += (Integer) row[0]; } return out; } private MasterDetailListProcessor getProcessor(boolean totalsOnTop) { final ObjectRowListProcessor items = new ObjectRowListProcessor(); MasterDetailListProcessor totals = new MasterDetailListProcessor(totalsOnTop ? RowPlacement.TOP : RowPlacement.BOTTOM, items) { @Override protected boolean isMasterRecord(String[] row, ParsingContext context) { return "T".equals(row[0]); } }; totals.convertIndexes(Conversions.toBigInteger()).set(1); items.convertIndexes(Conversions.toInteger()).set(0); return totals; } } MultiBeanListProcessorTest.java000077500000000000000000000102541475274123300376140ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/* * Copyright (c) 2015. Univocity Software Pty Ltd *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.univocity.parsers.common.processor; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.*; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.math.*; import java.util.*; import static org.testng.Assert.*; public class MultiBeanListProcessorTest extends AnnotatedBeanProcessorTest{ public static class AmountBean { @Trim @UpperCase @Parsed(index = 4) String commts; @Parsed(field = "amount") BigDecimal amnt; } public static class QuantityBean { @Parsed(defaultNullRead = "-1") Integer quantity; @Trim @LowerCase @BooleanString(falseStrings = {"no", "n", "null"}, trueStrings = {"yes", "y"}) @Parsed Boolean pending; } public static class BrokenBean { @Parsed(index = 4) String commts; @Parsed int quantity; public int getQuantity() { return this.quantity; } public void setQuantity(int quantity) { if(quantity == 0) { throw new NullPointerException("throwing error on purpose"); } this.quantity = quantity; } } @Test public void testMultiBeanProcessor() { MultiBeanListProcessor processor = new MultiBeanListProcessor(TestBean.class, AmountBean.class, QuantityBean.class, BrokenBean.class); processor.convertAll(Conversions.toNull("", "?")); CsvParserSettings settings = newCsvInputSettings(); settings.setRowProcessorErrorHandler(new RowProcessorErrorHandler() { @Override public void handleError(DataProcessingException error, Object[] inputRow, ParsingContext context) { assertEquals(context.currentRecord(), 2L); } }); settings.excludeIndexes(0); StringReader reader = new StringReader(input); settings.setHeaderExtractionEnabled(true); settings.getFormat().setLineSeparator("\n"); settings.setRowProcessor(processor); CsvParser parser = new CsvParser(settings); parser.parse(reader); List testBeans = processor.getBeans(TestBean.class); List amountBeans = processor.getBeans(AmountBean.class); List quantityBeans = processor.getBeans(QuantityBean.class); List brokenBeans = processor.getBeans(BrokenBean.class); assertEquals(testBeans.size(), 2); assertEquals(amountBeans.size(), 2); assertEquals(quantityBeans.size(), 2); assertEquals(brokenBeans.size(), 2); TestBean testBean; AmountBean amountBean; QuantityBean quantityBean; BrokenBean brokenBean; testBean = testBeans.get(0); amountBean = amountBeans.get(0); quantityBean = quantityBeans.get(0); brokenBean = brokenBeans.get(0); assertEquals(testBean.amnt, new BigDecimal("555.999")); assertNull(testBean.commts); assertEquals(testBean.quantity, (Object) 1); assertTrue(testBean.pending); assertEquals(brokenBean.quantity, 1); assertNull(brokenBean.commts); assertEquals(amountBean.amnt, new BigDecimal("555.999")); assertNull(amountBean.commts); assertEquals(quantityBean.quantity, (Object) 1); assertTrue(quantityBean.pending); testBean = testBeans.get(1); amountBean = amountBeans.get(1); quantityBean = quantityBeans.get(1); assertNull(brokenBeans.get(1)); //Second row generated a NullPointerException and no bean is generated here assertEquals(testBean.amnt, null); assertEquals(testBean.quantity, (Object) 0); assertFalse(testBean.pending); assertEquals(testBean.commts, "\" someth"); assertEquals(amountBean.amnt, null); assertEquals(amountBean.commts, "\" SOMETHING \""); //upper cased assertEquals(quantityBean.quantity, Integer.valueOf(-1)); assertFalse(quantityBean.pending); } } ObjectColumnProcessorTest.java000077500000000000000000000050431475274123300374640ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.math.*; import java.util.*; import static org.testng.Assert.*; public class ObjectColumnProcessorTest { private static final String INPUT = "" + "A,B,C" + "\n1,true,C" + "\n2,false" + "\n3,,C" + "\n4,false,C,55.4"; @Test public void testColumnValues() { ObjectColumnProcessor processor = new ObjectColumnProcessor(); processor.convertFields(Conversions.toInteger()).add("A"); processor.convertFields(Conversions.toBoolean()).add("B"); processor.convertFields(Conversions.toChar()).add("C"); processor.convertIndexes(Conversions.toBigDecimal()).add(3); CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\n"); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); new CsvParser(settings).parse(new StringReader(INPUT)); Object[][] expectedValues = new Object[][]{ {1, 2, 3, 4}, {true, false, null, false}, {'C', null, 'C', 'C'}, {null, null, null, new BigDecimal("55.4")} }; List> columnValues = processor.getColumnValuesAsList(); Map> columnsByIndex = processor.getColumnValuesAsMapOfIndexes(); assertEquals(columnValues.size(), expectedValues.length); int i = 0; for (List column : columnValues) { assertEquals(column.toArray(), expectedValues[i]); assertEquals(columnsByIndex.get(i).toArray(), expectedValues[i]); i++; } try { processor.getColumnValuesAsMapOfNames(); fail("Expected exception. No name defined for 4th column"); } catch (Exception e) { //OK } assertEquals(processor.getHeaders(), new String[]{"A", "B", "C"}); } } ObjectRowListProcessorTest.java000077500000000000000000000127311475274123300376340ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.math.*; import java.util.*; import static com.univocity.parsers.conversions.Conversions.*; import static org.testng.Assert.*; public class ObjectRowListProcessorTest { protected CsvParserSettings newCsvInputSettings() { CsvParserSettings out = new CsvParserSettings(); out.getFormat().setLineSeparator("\n"); return out; } private String[] valuesForTrue = new String[]{"yes", "y"}; private String[] valuesForFalse = new String[]{"no", "n", null}; private String input = "date,amount,quantity,pending,comments\n" + "10-oct-2001,555.999,1,yEs,?\n" + "2001-10-10,,?,N,\" \"\" something \"\" \""; private List process(String input, ObjectRowListProcessor processor, CsvParserSettings settings) { StringReader reader = new StringReader(input); settings.setHeaderExtractionEnabled(true); settings.setRowProcessor(processor); CsvParser parser = new CsvParser(settings); parser.parse(reader); List rows = processor.getRows(); return rows; } private ObjectRowListProcessor newProcessorWithFieldNames() { ObjectRowListProcessor processor = new ObjectRowListProcessor(); Conversion toNull = toNull("", "?"); processor.convertFields(toNull).set("quantity", "amount"); processor.convertFields(toCalendar(Locale.ENGLISH,"dd-MMM-yyyy", "yyyy-MM-dd")).set("date"); processor.convertFields(toBigDecimal()).set("amount"); processor.convertFields(toInteger()).set("quantity"); processor.convertFields(toLowerCase(), toBoolean(valuesForTrue, valuesForFalse)).set("pending"); processor.convertFields(trim(), toNull).set("comments"); return processor; } private ObjectRowListProcessor newProcessorWithFieldIndexes() { ObjectRowListProcessor processor = new ObjectRowListProcessor(); Conversion toNull = toNull("", "?"); processor.convertIndexes(toNull).set(1, 2); processor.convertIndexes(toCalendar(Locale.ENGLISH, "dd-MMM-yyyy", "yyyy-MM-dd")).set(0); processor.convertIndexes(toBigDecimal()).set(1); processor.convertIndexes(toInteger()).set(2); processor.convertIndexes(toLowerCase(), toBoolean(valuesForTrue, valuesForFalse)).set(3); processor.convertIndexes(trim(), toNull).set(4); return processor; } @DataProvider(name = "processors") Object[][] getProcessors() { return new Object[][]{ {newProcessorWithFieldNames()}, {newProcessorWithFieldIndexes()} }; } @Test(dataProvider = "processors") public void conversionTest(ObjectRowListProcessor processor) { process(input, processor, newCsvInputSettings()); List rows = processor.getRows(); assertEquals(rows.size(), 2); Calendar date = new GregorianCalendar(2001, Calendar.OCTOBER, 10); Object[] row = rows.get(0); assertEquals(row[0], date); assertEquals(row[1], new BigDecimal("555.999")); assertEquals(row[2], 1); assertEquals(row[3], true); assertNull(row[4]); row = rows.get(1); assertEquals(row[0], date); assertEquals(row[1], null); assertEquals(row[2], null); assertEquals(row[3], false); assertEquals(row[4], "\" something \""); // trimmed } @Test(dataProvider = "processors") public void conversionTestOnSelectedColumnsWithReordering(ObjectRowListProcessor processor) { CsvParserSettings settings = newCsvInputSettings(); settings.setColumnReorderingEnabled(true); settings.selectIndexes(1, 0, 3); settings.getFormat().setLineSeparator("\n"); process(input, processor, settings); List rows = processor.getRows(); assertEquals(rows.size(), 2); Calendar date = new GregorianCalendar(2001, Calendar.OCTOBER, 10); Object[] row = rows.get(0); assertEquals(row[0], new BigDecimal("555.999")); assertEquals(row[1], date); assertEquals(row[2], true); row = rows.get(1); assertEquals(row[0], null); assertEquals(row[1], date); assertEquals(row[2], false); } @Test(dataProvider = "processors") public void conversionTestOnSelectedColumnsWithoutColumnReordering(ObjectRowListProcessor processor) { CsvParserSettings settings = newCsvInputSettings(); settings.selectIndexes(1, 0, 3); settings.setColumnReorderingEnabled(false); process(input, processor, settings); List rows = processor.getRows(); assertEquals(rows.size(), 2); Calendar date = new GregorianCalendar(2001, Calendar.OCTOBER, 10); Object[] row = rows.get(0); assertEquals(row[0], date); assertEquals(row[1], new BigDecimal("555.999")); assertNull(row[2]); assertEquals(row[3], true); assertNull(row[4]); row = rows.get(1); assertEquals(row[0], date); assertEquals(row[1], null); assertNull(row[2]); assertEquals(row[3], false); assertNull(row[2]); } } ObjectRowWriterProcessorTest.java000066400000000000000000000102661475274123300401730ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/processor/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.processor; import com.univocity.parsers.conversions.*; import org.testng.annotations.*; import java.math.*; import java.text.*; import java.util.*; import static com.univocity.parsers.conversions.Conversions.*; import static org.testng.Assert.*; public class ObjectRowWriterProcessorTest { private final SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); private final String[] headers = "date,amount,quantity,pending,comments".split(","); private final Object[][] values; { try { values = new Object[][]{ {format.parse("10-oct-2001"), new BigDecimal("555.999"), 1, true, null}, {format.parse("11-oct-2001"), null, null, false, " something "} }; } catch (ParseException e) { throw new IllegalStateException(e); } } private ObjectRowWriterProcessor newProcessorWithFieldNames() { ObjectRowWriterProcessor processor = new ObjectRowWriterProcessor(); Conversion toNull = toNull("?"); processor.convertFields(toNull).set("quantity", "amount"); processor.convertFields(toDate("dd-MM-yyyy")).set("date"); processor.convertFields(toBigDecimal()).set("amount"); processor.convertFields(toInteger()).set("quantity"); processor.convertFields(toBoolean("y", "n")).set("pending"); processor.convertFields(trim(), toNull).set("comments"); return processor; } private ObjectRowWriterProcessor newProcessorWithFieldIndexes() { ObjectRowWriterProcessor processor = new ObjectRowWriterProcessor(); Conversion toNull = toNull("?"); processor.convertIndexes(toNull).set(1, 2); processor.convertIndexes(toDate("dd-MM-yyyy")).set(0); processor.convertIndexes(toBigDecimal()).set(1); processor.convertIndexes(toInteger()).set(2); processor.convertIndexes(toBoolean("y", "n")).set(3); processor.convertIndexes(trim(), toNull).set(4); return processor; } @DataProvider(name = "processors") Object[][] getProcessors() { return new Object[][]{ {newProcessorWithFieldNames()}, {newProcessorWithFieldIndexes()} }; } @Test(dataProvider = "processors") public void conversionTest(ObjectRowWriterProcessor processor) { Object[] row; row = processor.write(values[0], headers, null); assertEquals(row[0], "10-10-2001"); assertEquals(row[1], "555.999"); assertEquals(row[2], "1"); assertEquals(row[3], "y"); assertEquals(row[4], "?"); row = processor.write(values[1], headers, null); assertEquals(row[0], "11-10-2001"); assertEquals(row[1], "?"); assertEquals(row[2], "?"); assertEquals(row[3], "n"); assertEquals(row[4], "something"); // trimmed } @Test public void testTypeConversion() { ObjectRowWriterProcessor processor = new ObjectRowWriterProcessor(); processor.convertType(Boolean.class, Conversions.string(), Conversions.toUpperCase()); processor.convertType(String.class, Conversions.toUpperCase(), Conversions.trim()); processor.convertType(Date.class, Conversions.toDate(Locale.ENGLISH,"yyyy-MMM-dd"), Conversions.toUpperCase()); Object[] row; row = processor.write(values[0], headers, null); assertEquals(row[0], "2001-OCT-10"); assertEquals(row[1], new BigDecimal("555.999")); assertEquals(row[2], 1); assertEquals(row[3], "TRUE"); assertEquals(row[4], null); row = processor.write(values[1], headers, null); assertEquals(row[0], "2001-OCT-11"); assertEquals(row[1], null); assertEquals(row[2], null); assertEquals(row[3], "FALSE"); assertEquals(row[4], "SOMETHING"); // trimmed } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/record/000077500000000000000000000000001475274123300310065ustar00rootroot00000000000000RecordImplTest.java000066400000000000000000000207151475274123300344770ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/record/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.record; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import com.univocity.parsers.tsv.*; import org.testng.annotations.*; import java.io.*; import java.math.*; import java.util.*; import static org.testng.Assert.*; public class RecordImplTest { private Record record; @BeforeClass public void setup() { TsvParserSettings settings = new TsvParserSettings(); settings.setHeaders("boolean,byte,short,int,long,bigint,float,double,bigdec,char,string,date,calendar".split(",")); TsvParser parser = new TsvParser(settings); record = parser.parseRecord("Y 1 2 4 5 6.6 7.7 $8.888 B blah 10/10/10 11/11/11"); assertNotNull(record); RecordMetaData md = record.getMetaData(); assertNotNull(md); md.setTypeOfColumns(BigInteger.class, E.bigint); md.convertFields(E.class, new DateConversion("dd/MM/yy")).add(E.date); md.setTypeOfColumns(Short.class, 2); md.setTypeOfColumns(float.class, 6); md.convertFields(new CalendarConversion("dd/MM/yy")).add("calendar"); } enum E { bigint, bigdec, date, calendar } @Test public void fillEnumMap() { EnumMap map = new EnumMap(E.class); record.fillEnumMap(map, E.date, E.bigint); assertEquals(map.size(), 2); assertEquals(map.get(E.date), "10/10/10"); assertEquals(map.get(E.bigint), "5"); } @Test public void fillEnumObjectMap() { EnumMap map = new EnumMap(E.class); record.fillEnumObjectMap(map, E.date, E.bigint); assertEquals(map.size(), 2); assertEquals((Date) map.get(E.date), new GregorianCalendar(2010, Calendar.OCTOBER, 10).getTime()); assertEquals((BigInteger) map.get(E.bigint), new BigInteger("5")); } @Test public void fillFieldMap() { Map map = new TreeMap(); record.fillFieldMap(map, "short", "float"); assertEquals(map.size(), 2); assertEquals(map.get("short"), "2"); assertEquals(map.get("float"), "6.6"); } @Test public void fillFieldObjectMap() { Map map = new TreeMap(); record.fillFieldObjectMap(map, "short", "float"); assertEquals(map.size(), 2); assertEquals((Short) map.get("short"), Short.valueOf((short) 2)); assertEquals((Float) map.get("float"), (float) 6.6); } @Test public void fillIndexMap() { Map map = new TreeMap(); record.fillIndexMap(map, 2, 6); assertEquals(map.size(), 2); assertEquals(map.get(2), "2"); assertEquals(map.get(6), "6.6"); } @Test public void fillIndexObjectMap() { Map map = new TreeMap(); record.fillIndexObjectMap(map, 2, 6); assertEquals(map.size(), 2); assertEquals((Short) map.get(2), Short.valueOf((short) 2)); assertEquals((Float) map.get(6), (float) 6.6); } @Test public void getBigDecimalStringStringString() { BigDecimal dec = record.getBigDecimal("bigdec", "$#0.00", "decimalSeparator=."); assertEquals(dec, new BigDecimal("8.888")); } @Test public void getBigDecimalEnumStringString() { BigDecimal dec = record.getBigDecimal(E.bigdec, "$#0.00", "decimalSeparator=."); assertEquals(dec, new BigDecimal("8.888")); } @Test public void getBigDecimalintStringString() { BigDecimal dec = record.getBigDecimal(8, "$#0.00", "decimalSeparator=."); assertEquals(dec, new BigDecimal("8.888")); } @Test public void getBigIntegerStringStringString() { BigInteger i = record.getBigInteger("bigint"); assertEquals(i, new BigInteger("5")); } @Test public void getBigIntegerEnumStringString() { BigInteger i = record.getBigInteger(E.bigint); assertEquals(i, new BigInteger("5")); } @Test public void getBigIntegerintStringString() { BigInteger i = record.getBigInteger(5); assertEquals(i, new BigInteger("5")); } @Test public void getBoolean() { assertTrue(record.getBoolean("boolean", "Y", "N")); assertFalse(record.getBoolean("boolean", "N", "Y")); } @Test public void getByte() { assertEquals((byte) record.getByte("byte"), (byte) 1); } @Test public void getCalendar() { Calendar cal = record.getCalendar(12, "hh/mm/ss");//ha! assertEquals(cal.get(Calendar.HOUR), 11); assertEquals(cal.get(Calendar.MINUTE), 11); assertEquals(cal.get(Calendar.SECOND), 11); cal = record.getCalendar("calendar");//format defined in metaData's column type - see @BeforeClass method. assertEquals(cal, new GregorianCalendar(2011, Calendar.NOVEMBER, 11)); } @Test public void getChar() { assertEquals(record.getChar("char"), Character.valueOf('B')); } @Test public void getDate() { Date dt = record.getDate("date", "hh/mm/ss");//ha! Calendar cal = Calendar.getInstance(); cal.setTime(dt); assertEquals(cal.get(Calendar.HOUR), 10); assertEquals(cal.get(Calendar.MINUTE), 10); assertEquals(cal.get(Calendar.SECOND), 10); dt = record.getDate(11);//format defined in metaData's column type - see @BeforeClass method. cal.setTime(dt); assertEquals(cal, new GregorianCalendar(2010, Calendar.OCTOBER, 10)); } @Test public void getDouble() { assertEquals(record.getDouble("double"), Double.valueOf(7.7)); } @Test public void getFloat() { assertEquals(record.getFloat("float"), Float.valueOf(6.6f)); } @Test public void getInt() { assertEquals(record.getInt("int"), null); } @Test public void getLong() { assertEquals(record.getLong("long"), Long.valueOf(4L)); } @Test public void getString() { assertEquals(record.getString("string"), "blah"); } @Test public void getValue() { assertEquals(record.getValue(E.bigdec, String.class), "$8.888"); assertEquals(record.getValue("int", Integer.class), null); assertEquals(record.getValue("int", Long.class), null); assertEquals(record.getValue("int", Long.valueOf(0L)), Long.valueOf(0L)); assertEquals(record.getValue("int", Integer.valueOf(100)), Integer.valueOf(100)); } @Test public void getValues() { assertEquals(record.getValues(E.bigdec, E.date), new String[]{"$8.888", "10/10/10"}); assertEquals(record.getValues("bigdec", "date"), new String[]{"$8.888", "10/10/10"}); assertEquals(record.getValues(8, 11), new String[]{"$8.888", "10/10/10"}); } @Test public void testUnivocityNull() { String data = "name,value\n'a',1\n'b',null\n"; CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setQuote('\''); settings.setHeaderExtractionEnabled(true); CsvParser parser = new CsvParser(settings); parser.beginParsing(new StringReader(data)); parser.getRecordMetadata().convertFields(Conversions.toNull("null")).set("value"); List records = parser.parseAllRecords(); assertEquals(records.get(0).getString("name"), "a"); assertEquals(records.get(0).getInt("value"), new Integer(1)); assertEquals(records.get(1).getString("name"), "b"); assertNull(records.get(1).getString("value")); } @Test public void testReuseAndHeaders() { String data1 = "name1,value1\n'a',1\n'b',null\n"; String data2 = "name2,value2\n'c',2\n'd',e\n"; CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setQuote('\''); settings.setHeaderExtractionEnabled(true); CsvParser parser = new CsvParser(settings); Record r1 = parseAndReturnRecord(parser, data1); assertEquals(Arrays.toString(r1.getMetaData().headers()), "[name1, value1]"); Record r2 = parseAndReturnRecord(parser, data2); assertEquals(Arrays.toString(r2.getMetaData().headers()), "[name2, value2]"); assertEquals(r1.getMetaData().indexOf("value1"), 1); assertEquals(Arrays.toString(r1.getMetaData().headers()), "[name1, value1]"); } private Record parseAndReturnRecord(CsvParser parser, String data) { parser.beginParsing(new StringReader(data)); parser.getRecordMetadata().convertFields(Conversions.toNull("null")).set("value"); List records = parser.parseAllRecords(); return records.get(0); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/routine/000077500000000000000000000000001475274123300312155ustar00rootroot00000000000000AbstractRoutinesTest.java000066400000000000000000000214241475274123300361400ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/common/routine/******************************************************************************* * Copyright 2016 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.common.routine; import com.univocity.parsers.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.conversions.*; import com.univocity.parsers.csv.*; import com.univocity.parsers.examples.*; import com.univocity.parsers.fixed.*; import com.univocity.parsers.tsv.*; import org.testng.annotations.*; import java.io.*; import java.sql.*; import java.util.*; import static org.testng.Assert.*; public class AbstractRoutinesTest { private CsvParserSettings getParserSettings() { CsvParserSettings out = new CsvParserSettings(); out.getFormat().setLineSeparator("\n"); return out; } private CsvWriterSettings getWriterSettings() { CsvWriterSettings out = new CsvWriterSettings(); out.getFormat().setLineSeparator("\n"); return out; } static class ResultSetTest { AbstractRoutines routineImpl; String result; ResultSetTest(AbstractRoutines routineImpl) { this.routineImpl = routineImpl; } void run(ResultSet rs) throws Exception { StringWriter output = new StringWriter(); routineImpl.setKeepResourcesOpen(true); routineImpl.write(rs, output); output.write("A random line"); assertFalse(rs.isClosed()); output.close(); result = output.toString(); rs.close(); } } @Test public void testWriteResultSet() throws Exception { ObjectRowWriterProcessor processor = new ObjectRowWriterProcessor(); processor.convertType(java.sql.Timestamp.class, Conversions.toDate("dd/MM/yyyy HH:mm")); CsvRoutines csvRoutine = new CsvRoutines(); csvRoutine.setWriterSettings(getWriterSettings()); csvRoutine.getWriterSettings().setRowWriterProcessor(processor); ResultSetTest csvTest = new ResultSetTest(csvRoutine); TsvRoutines tsvRoutine = new TsvRoutines(); tsvRoutine.setWriterSettings(new TsvWriterSettings()); tsvRoutine.getWriterSettings().getFormat().setLineSeparator("\n"); tsvRoutine.getWriterSettings().setRowWriterProcessor(processor); ResultSetTest tsvTest = new ResultSetTest(tsvRoutine); FixedWidthRoutines fixedWidthRoutine = new FixedWidthRoutines(); fixedWidthRoutine.setWriterSettings(new FixedWidthWriterSettings()); fixedWidthRoutine.getWriterSettings().getFormat().setLineSeparator("\n"); fixedWidthRoutine.getWriterSettings().getFormat().setPadding('.'); fixedWidthRoutine.getWriterSettings().setRowWriterProcessor(processor); ResultSetTest fixedWidthTest = new ResultSetTest(fixedWidthRoutine); testWriteResultSet(csvTest, tsvTest, fixedWidthTest); String randomLine = "A random line"; String expectedCsv = "" + "1234,Description 1,02/12/2015 10:35\n" + "2345,Description 2,25/11/2016 11:05\n" + "39,Description 3,31/05/2017 09:24\n"; String expectedTsv = "" + "1234\tDescription 1\t02/12/2015 10:35\n" + "2345\tDescription 2\t25/11/2016 11:05\n" + "39\tDescription 3\t31/05/2017 09:24\n"; String expectedFixedWidth = "" + "1234Description 1...................02/12/2015 10:35..................\n" + "2345Description 2...................25/11/2016 11:05..................\n" + "39..Description 3...................31/05/2017 09:24..................\n"; assertEquals(csvTest.result, expectedCsv + randomLine); assertEquals(tsvTest.result, expectedTsv + randomLine); assertEquals(fixedWidthTest.result, expectedFixedWidth + randomLine); } private void testWriteResultSet(ResultSetTest... tests) throws Exception { String createTable = "CREATE TABLE test(" + " id char(4) primary key," + " desc varchar(32) not null," + " some_date datetime not null" + ")"; Class.forName("org.hsqldb.jdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:run"); try { Statement statement = connection.createStatement(); try { try { statement.execute(createTable); statement.executeUpdate("INSERT INTO test (id, desc, some_date) VALUES ('1234', 'Description 1', '2015-12-02 10:35:12')"); statement.executeUpdate("INSERT INTO test (id, desc, some_date) VALUES ('2345', 'Description 2', '2016-11-25 11:05:32')"); statement.executeUpdate("INSERT INTO test (id, desc, some_date) VALUES ('39' , 'Description 3', '2017-05-31 09:24:45')"); } catch(Exception ex){ //ignore. Table exists already. } for (ResultSetTest test : tests) { ResultSet rs = statement.executeQuery("SELECT id, desc, some_date FROM test ORDER BY id"); try { test.run(rs); } finally { rs.close(); } } } finally { statement.close(); } } finally { connection.close(); } } @Test public void testParseAndWrite() throws Exception { CsvRoutines csvRoutines = new CsvRoutines(); CsvParserSettings parser = getParserSettings(); parser.setNumberOfRowsToSkip(2); parser.setHeaderExtractionEnabled(true); parser.selectFields("Description"); csvRoutines.setParserSettings(parser); CsvWriterSettings writer = new CsvWriterSettings(); writer.getFormat().setDelimiter('|'); writer.getFormat().setLineSeparator("\r\n"); writer.getFormat().setQuoteEscape('$'); writer.getFormat().setQuote('$'); writer.setSkipEmptyLines(true); csvRoutines.setWriterSettings(writer); StringWriter output = new StringWriter(); csvRoutines.parseAndWrite(ParserTestCase.newReader("/csv/essential.csv"), output); String expected = "ac, abs, moon\r\n" + "$MUST SELL!\r\n" + "air, moon roof, loaded$\r\n" + "ac, abs, moon\r\n" + "ac, abs, moon\r\n" + "ac, abs, moon\r\n" + "ac, abs, moon\r\n" + "\" ac, abs, moon \"\r\n" + "\" ac, abs, moon \"\r\n"; assertEquals(output.toString(), expected); } @Test public void testParseAllJavaBeans() throws Exception { List beans = new CsvRoutines(getParserSettings()).parseAll(TestBean.class, CsvParserTest.newReader("/examples/bean_test.csv")); assertNotNull(beans); assertFalse(beans.isEmpty()); } @Test public void testWriteAllJavaBeans() throws Exception { List beans = new CsvRoutines(getParserSettings()).parseAll(TestBean.class, CsvParserTest.newReader("/examples/bean_test.csv")); StringWriter output = new StringWriter(); CsvWriterSettings settings = getWriterSettings(); new CsvRoutines(settings).writeAll(beans, TestBean.class, output); assertEquals(output.toString(), "1,555.999,yes,,?\n0,,no,,\"\"\" something \"\"\"\n"); output = new StringWriter(); new CsvRoutines(settings).writeAll(beans, TestBean.class, output, "pending", "amount"); assertEquals(output.toString(), "pending,amount\nyes,555.999\nno,\n"); } @Test public void testIterateJavaBeans() throws Exception { List beans = new ArrayList(); for (TestBean bean : new CsvRoutines(getParserSettings()).iterate(TestBean.class, CsvParserTest.newReader("/examples/bean_test.csv"))) { beans.add(bean); } assertEquals(beans.size(), 2); assertEquals(beans.get(0).getQuantity(), Integer.valueOf(1)); assertEquals(beans.get(1).getComments(), "\" something \""); } @Test public void testResourcesOpenFlagWithOutputStream() throws Exception { final File tmp = File.createTempFile("test", ".csv"); testWriteResultSet(new ResultSetTest(null) { public void run(ResultSet rs) { CsvWriterSettings settings = new CsvWriterSettings(); CsvRoutines csvRoutines = new CsvRoutines(settings); csvRoutines.setKeepResourcesOpen(true); FileOutputStream fout = null; try { try { fout = new FileOutputStream(tmp); csvRoutines.write(rs, fout); } finally { fout.close(); } } catch (Exception e) { throw new IllegalStateException(e); } } }); List rows = new CsvParser(new CsvParserSettings()).parseAll(tmp); assertEquals(rows.size(), 3); } @Test public void testInputDimensionRoutine() { CsvParserSettings csvParserSettings = new CsvParserSettings(); csvParserSettings.getFormat().setLineSeparator("\n"); csvParserSettings.setHeaderExtractionEnabled(true); CsvRoutines csvRoutines = new CsvRoutines(csvParserSettings); InputDimension d = csvRoutines.getInputDimension(new StringReader("a\nb\nc\n")); assertEquals(d.rowCount(), 3L); assertEquals(d.columnCount(), 1); } }jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/csv/000077500000000000000000000000001475274123300270335ustar00rootroot00000000000000CsvFormatDetectorTest.java000077500000000000000000000123221475274123300340600ustar00rootroot00000000000000jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/csv/******************************************************************************* * Copyright 2015 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; public class CsvFormatDetectorTest { @DataProvider public Object[][] getInputsAndOutputs() { return new Object[][]{ {"A,B,C\n1,2,3\n1,2,3\n1,2,3", Arrays.asList(new String[]{"A", "B", "C"}, new String[]{"1", "2", "3"}, new String[]{"1", "2", "3"}, new String[]{"1", "2", "3"})}, {"\"A\";'B';\"C\"\n\"1\\\" and \\\"2\";\"3\\\"A\";'B';\"C\"\n\"A\";'B';\"C\"\n\"A\";'B';\"C\"\n", Arrays.asList(new String[]{"A", "'B'", "C"}, new String[]{"1\" and \"2", "3\"A", "'B'", "C"}, new String[]{"A", "'B'", "C"}, new String[]{"A", "'B'", "C"})}, {"\"A\";'B';\"C\"\n\"1\\\" and \\\"2\";\"3' and '4\";\"5\\\" and \\\"6\"\n\"A\";'B';\"C\"\n\"A\";'B';\"C\"\n", Arrays.asList(new String[]{"A", "'B'", "C"}, new String[]{"1\" and \"2", "3' and '4", "5\" and \"6"}, new String[]{"A", "'B'", "C"}, new String[]{"A", "'B'", "C"})}, {"1,2;2,3;3,4;a\n1,2;2,3;3,4;b\n1,2;2,3;3,4;c\n1,2;2,3;3,4;d\n", Arrays.asList(new String[]{"1,2", "2,3", "3,4", "a"}, new String[]{"1,2", "2,3", "3,4", "b"}, new String[]{"1,2", "2,3", "3,4", "c"}, new String[]{"1,2", "2,3", "3,4", "d"})}, {"A;B;C;D;E\n$1.2;$2.3;$3.4\n$1.2;$2.3;$3.4\n$1.2;$2.3;$3.4\n$1.2;$2.3;$3.4\n", Arrays.asList(new String[]{"A", "B", "C", "D", "E"}, new String[]{"$1.2", "$2.3", "$3.4"}, new String[]{"$1.2", "$2.3", "$3.4"}, new String[]{"$1.2", "$2.3", "$3.4"}, new String[]{"$1.2", "$2.3", "$3.4"})}, {"\"A'A\",\"BB\",\"CC\"\n\"11\",\"22\",\"33\"\n\"11\",\"22\",\"33\"\n\"11\",\"22\",\"33\"\n", Arrays.asList(new String[]{"A'A", "BB", "CC"}, new String[]{"11", "22", "33"}, new String[]{"11", "22", "33"}, new String[]{"11", "22", "33"})} }; } private CsvParserSettings newSettings() { CsvParserSettings settings = new CsvParserSettings(); settings.setDelimiterDetectionEnabled(true); settings.setQuoteDetectionEnabled(true); settings.setParseUnescapedQuotes(false); settings.getFormat().setLineSeparator("\n"); settings.getFormat().setDelimiter('x'); settings.getFormat().setQuote('x'); settings.getFormat().setQuoteEscape('x'); return settings; } @Test(dataProvider = "getInputsAndOutputs") public void testDelimiterDiscovery(String input, List expectedOutput) { CsvParserSettings settings = newSettings(); CsvParser parser = new CsvParser(settings); List rows = parser.parseAll(new StringReader(input)); assertEquals(rows.size(), expectedOutput.size()); for (int i = 0; i < rows.size(); i++) { assertEquals(expectedOutput.get(i), rows.get(i)); } } @Test public void testAutodetection() throws Exception { CsvParserSettings settings = new CsvParserSettings(); settings.detectFormatAutomatically(); CsvParser parser = new CsvParser(settings); String s = "" + "1;2001-01-01;First row;1.1\n" + "2;2002-02-02;Second row;2.2\n" + "3;2003-03-03;Third row;3.3\n" + "4;2004-04-04;Fourth row;4.4"; List rows = parser.parseAll(new StringReader(s)); CsvFormat format = parser.getDetectedFormat(); assertEquals(format.getDelimiter(), ';'); assertEquals(rows.size(), 4); s = "" + "1;2001-01-01;First row;1.1\n" + "2;2002-02-02;Second row;2\n" + "3;2003-03-03;Third row;3.3\n" + "4;2004-04-04;Fourth row;4.4"; rows = parser.parseAll(new StringReader(s)); format = parser.getDetectedFormat(); assertEquals(format.getDelimiter(), ';'); assertEquals(rows.size(), 4); } @Test public static void testDelimitersDetectedUsingOrderOfPreference() { String input = "HEADER1, HEADER2, HEADER3\n" + "11, 12, 13\n" + "21, 22, 23\n" + "31, 32, 33\n"; CsvParserSettings settings = new CsvParserSettings(); settings.setDelimiterDetectionEnabled(true, ',', ' '); CsvParser parser = new CsvParser(settings); parser.parseAll(new StringReader(input)); CsvFormat format = parser.getDetectedFormat(); assertEquals(format.getDelimiter(), ','); } @Test public static void testDelimitersDetectedUsingOrderOfPreference1() { String input = "HEADER 1,HEADER 2,HEADER 3\n" + "SOME TEXT 1,SOME TEXT 2,SOME TEXT 3,"; CsvParserSettings settings = new CsvParserSettings(); settings.setDelimiterDetectionEnabled(true, ',', ' '); settings.setFormatDetectorRowSampleCount(2); CsvParser parser = new CsvParser(settings); parser.parseAll(new StringReader(input)); CsvFormat format = parser.getDetectedFormat(); assertEquals(format.getDelimiter(), ','); } } jtreg7-7.5.1+1+ds1/univocity-parsers/src/test/java/com/univocity/parsers/csv/CsvParserTest.java000077500000000000000000001001431475274123300324500ustar00rootroot00000000000000/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.csv; import com.univocity.parsers.*; import com.univocity.parsers.common.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.common.record.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import java.util.concurrent.*; import static org.testng.Assert.*; public class CsvParserTest extends ParserTestCase { @DataProvider(name = "testProvider") public Object[][] testProvider() { return new Object[][]{ {"/csv/test.csv", new char[]{'\n'}}, {"/csv/test.csv", null} }; } @DataProvider(name = "csvProvider") public Object[][] csvProvider() { return new Object[][]{ {"/csv/essential.csv", new char[]{'\n'}}, {"/csv/essential-dos.csv", new char[]{'\r', '\n'}}, {"/csv/essential-mac.csv", new char[]{'\r'}}, {"/csv/essential.csv", null}, {"/csv/essential-dos.csv", null}, {"/csv/essential-mac.csv", null} }; } @Test(enabled = true, dataProvider = "csvProvider") public void parseIgnoringWhitespaces(String csvFile, char[] lineSeparator) throws Exception { CsvParserSettings settings = newCsvInputSettings(lineSeparator); settings.setCommentCollectionEnabled(true); settings.setRowProcessor(processor); settings.setHeaderExtractionEnabled(true); settings.setIgnoreLeadingWhitespaces(true); settings.setIgnoreTrailingWhitespaces(true); CsvParser parser = new CsvParser(settings); parser.parse(newReader(csvFile)); String[] expectedHeaders = new String[]{"Year", "Make", "Model", "Description", "Price"}; String[][] expectedResult = new String[][]{ {"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}, {"1999", "Chevy", "Venture \"Extended Edition\"", null, "4900.00"}, {"1996", "Jeep", "Grand Cherokee", "MUST SELL!\nair, moon roof, loaded", "4799.00"}, {"1999", "Chevy", "Venture \"Extended Edition, Very Large\"", null, "5000.00"}, {null, null, "Venture \"Extended Edition\"", null, "4900.00"}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, "5", null, null}, {"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}, {"1997", "Ford", "E350", " ac, abs, moon ", "3000.00"}, {"1997", "Ford", "E350", " ac, abs, moon ", "3000.00"}, {"19 97", "Fo rd", "E350", " ac, abs, moon ", "3000.00"}, {null, " ", null, " ", "30 00.00"}, {"1997", "Ford", "E350", " \" ac, abs, moon \" ", "3000.00"}, {"1997", "Ford", "E350", "\" ac, abs, moon \" ", "3000.00"}, }; assertHeadersAndValuesMatch(expectedHeaders, expectedResult); Map comments = parser.getContext().comments(); assertEquals(comments.size(), 1); assertEquals(comments.keySet().iterator().next().longValue(), 6L); assertEquals(comments.values().iterator().next(), parser.getContext().lastComment()); assertEquals(parser.getContext().lastComment(), "this is a comment and should be ignored"); } protected CsvParserSettings newCsvInputSettings(char[] lineSeparator) { CsvParserSettings out = new CsvParserSettings(); if (lineSeparator == null) { out.setLineSeparatorDetectionEnabled(true); } else { out.getFormat().setLineSeparator(lineSeparator); } out.getFormat().setNormalizedNewline('\n'); return out; } @Test(enabled = true, dataProvider = "csvProvider") public void parseUsingWhitespaces(String csvFile, char[] lineSeparator) throws Exception { CsvParserSettings settings = newCsvInputSettings(lineSeparator); settings.setRowProcessor(processor); settings.setHeaderExtractionEnabled(true); settings.setNullValue("?????"); settings.setEmptyValue("XXXXX"); settings.setIgnoreLeadingWhitespaces(false); settings.setIgnoreTrailingWhitespaces(false); CsvParser parser = new CsvParser(settings); parser.parse(newReader(csvFile)); String[] expectedHeaders = new String[]{"Year", "Make", "Model", "Description", "Price"}; String[][] expectedResult = new String[][]{ {"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}, {"1999", "Chevy", "Venture \"Extended Edition\"", "XXXXX", "4900.00"}, {"1996", "Jeep", "Grand Cherokee", "MUST SELL!\nair, moon roof, loaded", "4799.00"}, {"1999", "Chevy", "Venture \"Extended Edition, Very Large\"", "?????", "5000.00"}, {"?????", "?????", "Venture \"Extended Edition\"", "XXXXX", "4900.00"}, {"?????", "?????", "?????", "?????", "?????"}, {" ", " ", " ", " ", " "}, {"?????", "?????", " 5 ", "?????", "?????"}, {" "}, {"1997 ", " Ford ", "E350", "ac, abs, moon", " \"3000.00\" \t"}, {"1997", " Ford ", "E350", " ac, abs, moon ", "3000.00 \t"}, {" 1997", " Ford ", "E350", " ac, abs, moon ", "3000.00"}, {" 19 97 ", " Fo rd ", "E350", " ac, abs, moon ", "3000.00"}, {"\t\t", " ", " ", " \" \"\t", "30 00.00\t"}, {"1997", "Ford", "E350", " \" ac, abs, moon \" ", "3000.00"}, {"1997", "Ford", "E350", "\" ac, abs, moon \" ", "3000.00"}, }; assertHeadersAndValuesMatch(expectedHeaders, expectedResult); } @Test(enabled = true, dataProvider = "csvProvider") public void parseColumns(String csvFile, char[] lineSeparator) throws Exception { CsvParserSettings settings = newCsvInputSettings(lineSeparator); settings.setRowProcessor(processor); settings.setHeaderExtractionEnabled(true); settings.setIgnoreLeadingWhitespaces(true); settings.setIgnoreTrailingWhitespaces(true); settings.selectFields("Year"); settings.setColumnReorderingEnabled(false); CsvParser parser = new CsvParser(settings); parser.parse(newReader(csvFile)); String[] expectedHeaders = new String[]{"Year", "Make", "Model", "Description", "Price"}; String[][] expectedResult = new String[][]{ {"1997", null, null, null, null}, {"1999", null, null, null, null}, {"1996", null, null, null, null}, {"1999", null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {"1997", null, null, null, null}, {"1997", null, null, null, null}, {"1997", null, null, null, null}, {"19 97", null, null, null, null}, {null, null, null, null, null}, {"1997", null, null, null, null}, {"1997", null, null, null, null}, }; assertHeadersAndValuesMatch(expectedHeaders, expectedResult); } private String[] process(String input, Integer[] indexesToExclude, Integer[] indexesToSelect, String[] fieldsToExclude, String[] fieldsToSelect) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\n"); settings.setHeaderExtractionEnabled(fieldsToExclude != null || fieldsToSelect != null); if (indexesToExclude != null) { settings.excludeIndexes(indexesToExclude); } else if (fieldsToExclude != null) { settings.excludeFields(fieldsToExclude); } else if (indexesToSelect != null) { settings.selectIndexes(indexesToSelect); } else if (fieldsToSelect != null) { settings.selectFields(fieldsToSelect); } CsvParser parser = new CsvParser(settings); return parser.parseLine(input); } @Test public void columnSelectionTest() { String[] result; String input = "a,b,c,d,e"; Integer[] indexesToExclude = new Integer[]{0, 4}; result = process(input, indexesToExclude, null, null, null); assertEquals(result, new String[]{"b", "c", "d"}); Integer[] indexesToSelect = new Integer[]{0, 4}; result = process(input, null, indexesToSelect, null, null); assertEquals(result, new String[]{"a", "e"}); input = "ha,hb,hc,hd,he\na,b,c,d,e"; String[] fieldsToExclude = new String[]{"hb", "hd"}; result = process(input, null, null, fieldsToExclude, null); assertEquals(result, new String[]{"a", "c", "e"}); String[] fieldsToSelect = new String[]{"hb", "hd"}; result = process(input, null, null, null, fieldsToSelect); assertEquals(result, new String[]{"b", "d"}); } @Override protected RowListProcessor newRowListProcessor() { return new RowListProcessor() { @Override public void processStarted(ParsingContext context) { super.processStarted(context); context.skipLines(2); } @Override public void rowProcessed(String[] row, ParsingContext context) { super.rowProcessed(row, context); // for (int i = 0; i < row.length; i++) { // row[i] = ">>" + row[i] + "<<"; // } // System.out.println(context.currentLine() + " => " + Arrays.toString(row)); if (context.currentLine() == 9) { context.skipLines(1); } } }; } @Test(enabled = true, dataProvider = "csvProvider") public void parseOneByOne(String csvFile, char[] lineSeparator) throws Exception { CsvParserSettings settings = newCsvInputSettings(lineSeparator); settings.setRowProcessor(processor); settings.setHeaderExtractionEnabled(true); settings.setIgnoreLeadingWhitespaces(true); settings.setIgnoreTrailingWhitespaces(true); settings.setHeaders("YR", "MK", "MDL", "DSC", "PRC"); List results = new ArrayList(); CsvParser parser = new CsvParser(settings); try { parser.beginParsing(newReader(csvFile)); Object[] row; while ((row = parser.parseNext()) != null) { if (row.length == 5) { results.add(row); } } } finally { parser.stopParsing(); } String[] expectedHeaders = new String[]{"YR", "MK", "MDL", "DSC", "PRC"}; String[][] expectedResult = new String[][]{ {"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}, {"1999", "Chevy", "Venture \"Extended Edition\"", null, "4900.00"}, {"1996", "Jeep", "Grand Cherokee", "MUST SELL!\nair, moon roof, loaded", "4799.00"}, {"1999", "Chevy", "Venture \"Extended Edition, Very Large\"", null, "5000.00"}, {null, null, "Venture \"Extended Edition\"", null, "4900.00"}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, "5", null, null}, {"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}, {"1997", "Ford", "E350", " ac, abs, moon ", "3000.00"}, {"1997", "Ford", "E350", " ac, abs, moon ", "3000.00"}, {"19 97", "Fo rd", "E350", " ac, abs, moon ", "3000.00"}, {null, " ", null, " ", "30 00.00"}, {"1997", "Ford", "E350", " \" ac, abs, moon \" ", "3000.00"}, {"1997", "Ford", "E350", "\" ac, abs, moon \" ", "3000.00"}, }; Object[] headers = processor.getHeaders(); TestUtils.assertEquals(headers, expectedHeaders); assertEquals(results.size(), expectedResult.length); for (int i = 0; i < expectedResult.length; i++) { Object[] result = results.get(i); String[] expectedRow = expectedResult[i]; assertEquals(result, expectedRow); } } @Test(enabled = true, dataProvider = "csvProvider") public void parse3Records(String csvFile, char[] lineSeparator) throws Exception { CsvParserSettings settings = newCsvInputSettings(lineSeparator); settings.setRowProcessor(processor); settings.setHeaderExtractionEnabled(true); settings.setIgnoreLeadingWhitespaces(true); settings.setIgnoreTrailingWhitespaces(true); settings.setNumberOfRecordsToRead(3); CsvParser parser = new CsvParser(settings); parser.parse(newReader(csvFile)); String[] expectedHeaders = new String[]{"Year", "Make", "Model", "Description", "Price"}; String[][] expectedResult = new String[][]{ {"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}, {"1999", "Chevy", "Venture \"Extended Edition\"", null, "4900.00"}, {"1996", "Jeep", "Grand Cherokee", "MUST SELL!\nair, moon roof, loaded", "4799.00"}, }; assertHeadersAndValuesMatch(expectedHeaders, expectedResult); } @Test public void parseBrokenQuoteEscape() { CsvParserSettings settings = newCsvInputSettings(new char[]{'\n'}); settings.setParseUnescapedQuotesUntilDelimiter(false); settings.setHeaderExtractionEnabled(false); CsvParser parser = new CsvParser(settings); parser.beginParsing(new StringReader("" + "something,\"a quoted value \"with unescaped quotes\" can be parsed\", something\n" + "1997 , Ford ,E350,\"s, m\"\"\" , \"3000.00\"\n" + "1997 , Ford ,E350,\"ac, abs, moon\" , \"3000.00\" \n" + "something,\"a \"quoted\" \"\"value\"\" \"\"with unescaped quotes\"\" can be parsed\" , something\n")); String[] row = parser.parseNext(); assertEquals(row[0], "something"); assertEquals(row[2], "something"); assertEquals(row[1], "a quoted value \"with unescaped quotes\" can be parsed"); row = parser.parseNext(); assertEquals(row, new String[]{"1997", "Ford", "E350", "s, m\"", "3000.00"}); row = parser.parseNext(); assertEquals(row, new String[]{"1997", "Ford", "E350", "ac, abs, moon", "3000.00"}); row = parser.parseNext(); assertEquals(row[0], "something"); assertEquals(row[2], "something"); assertEquals(row[1], "a \"quoted\" \"value\" \"with unescaped quotes\" can be parsed"); } @Test public void testReadEmptyValue() { CsvParserSettings settings = newCsvInputSettings(new char[]{'\n'}); settings.setEmptyValue(""); settings.setHeaderExtractionEnabled(false); CsvParser parser = new CsvParser(settings); parser.beginParsing(new StringReader("a,b,,c,\"\",\r\n")); String[] row = parser.parseNext(); assertEquals(row[0], "a"); assertEquals(row[1], "b"); assertEquals(row[2], null); assertEquals(row[3], "c"); assertEquals(row[4], ""); assertEquals(row[5], null); } @DataProvider public Object[][] escapeHandlingProvider() { return new Object[][]{ //parsing a line with the following content: ||,|| |"," |" B |" "," |" ||" {false, false, new String[]{"||", "|| |\"", " \" B \" ", " \" |"}}, // process escapes on quoted values only: || , || |" , " B " , " | {false, true, new String[]{"|", "| \"", " \" B \" ", " \" |"}}, // process escapes quoted and unquoted: | , | " , " B " , " | {true, false, new String[]{"||", "|| |\"", " |\" B |\" ", " |\" ||"}}, // keep escape on quoted values only: || , || |" , " |" B |" " , |" ||" {true, true, new String[]{"||", "|| |\"", " |\" B |\" ", " |\" ||"}} // keep escape on everything: || , || |" , " |" B |" " , |" ||" }; } @Test(dataProvider = "escapeHandlingProvider") public void testHandlingOfEscapeSequences(boolean keepEscape, boolean escapeUnquoted, String[] expected) throws Exception { CsvParserSettings settings = new CsvParserSettings(); settings.setKeepEscapeSequences(keepEscape); settings.setEscapeUnquotedValues(escapeUnquoted); settings.getFormat().setCharToEscapeQuoteEscaping('|'); settings.getFormat().setQuoteEscape('|'); String line = "||,|| |\",\" |\" B |\" \",\" |\" ||\""; CsvParser parser = new CsvParser(settings); String[] result = parser.parseLine(line); // ||, || |", " |" B |" ", " |" ||" assertEquals(result, expected); } @Test public void testEscapedLineEndingsAreNotModified() { CsvParserSettings settings = new CsvParserSettings(); settings.setNormalizeLineEndingsWithinQuotes(false); settings.getFormat().setLineSeparator("\r\n"); CsvParser parser = new CsvParser(settings); String input = "1,\" Line1 \r\n Line2 \r Line3 \n Line4 \n\r \"\r\n" + "2,\" Line10 \r\n Line11 \""; List result = parser.parseAll(new StringReader(input)); // ||, || |", " |" B |" ", " |" ||" assertEquals(result.size(), 2); assertEquals(result.get(0).length, 2); assertEquals(result.get(1).length, 2); assertEquals(result.get(0), new String[]{"1", " Line1 \r\n Line2 \r Line3 \n Line4 \n\r "}); assertEquals(result.get(1), new String[]{"2", " Line10 \r\n Line11 "}); } public char[] getLineSeparator() { return new char[]{'\n'}; } @Test public void shouldNotAllowParseUnescapedQuotes() throws UnsupportedEncodingException { CsvParserSettings settings = newCsvInputSettings(getLineSeparator()); settings.setRowProcessor(new RowListProcessor()); //Default used by CsvParserTest skip 2 lines settings.setParseUnescapedQuotes(false); //To force exception CsvParser parser = new CsvParser(settings); try { parser.parse(new StringReader("1997,\"TV 29\"LED\"\n")); fail("Expected exception to be thrown here"); } catch (TextParsingException ex) { assertTrue(ex.getMessage().contains("Unescaped quote character")); } } @Test public void parseQuotedStringFollowedByBlankSpace() throws UnsupportedEncodingException { RowListProcessor processor = new RowListProcessor(); CsvParserSettings settings = newCsvInputSettings(getLineSeparator()); settings.setRowProcessor(processor); //Default used by CsvParserTest skip 2 lines settings.setParseUnescapedQuotes(true); settings.setParseUnescapedQuotesUntilDelimiter(false); CsvParser parser = new CsvParser(settings); parser.parse(new StringReader("1997,\"TV 29\" LED\"\n")); List rows = processor.getRows(); assertEquals(rows.size(), 1); String[] firstRow = rows.get(0); assertEquals(firstRow[0], "1997"); assertEquals(firstRow[1], "TV 29\" LED"); } @Test(dataProvider = "testProvider") public void shouldNotAllowUnexpectedCharacterAfterQuotedValue(String csvFile, char[] lineSeparator) throws UnsupportedEncodingException { CsvParserSettings settings = newCsvInputSettings(lineSeparator); settings.setParseUnescapedQuotes(false); CsvParser parser = new CsvParser(settings); try { parser.parseLine("1997,\"value\"x"); fail("Expected exception to be thrown here"); } catch (TextParsingException ex) { assertTrue(ex.getMessage().contains("Unescaped quote character '\"' inside quoted value of CSV field")); } } @Test public void parseValueProcessingEscapeNotIgnoringWhitespace() { RowListProcessor processor = new RowListProcessor(); CsvParserSettings settings = newCsvInputSettings(getLineSeparator()); settings.setRowProcessor(processor); //Default used by CsvParserTest skip 2 lines settings.setKeepEscapeSequences(true); settings.setIgnoreTrailingWhitespaces(false); settings.setEscapeUnquotedValues(true); CsvFormat format = new CsvFormat(); format.setQuoteEscape('\''); format.setCharToEscapeQuoteEscaping('\\'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); parser.parse(new StringReader("'\\\"a\n")); //goes into the else statement of CsvParser.parseValueProcessingEscape() method. List rows = processor.getRows(); assertEquals(rows.size(), 1); String[] firstRow = rows.get(0); assertEquals(firstRow[0], "\\\"a"); } @Test public void parseValueProcessingEscapeNotIgnoringWhitespacePrevQuoteEscape2() { RowListProcessor processor = new RowListProcessor(); CsvParserSettings settings = newCsvInputSettings(getLineSeparator()); settings.setRowProcessor(processor); //Default used by CsvParserTest skip 2 lines settings.setKeepEscapeSequences(true); settings.setIgnoreTrailingWhitespaces(false); settings.setEscapeUnquotedValues(true); CsvFormat format = new CsvFormat(); format.setQuoteEscape('\''); format.setCharToEscapeQuoteEscaping('\\'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); parser.parse(new StringReader("\\\'\n")); List rows = processor.getRows(); assertEquals(rows.size(), 1); String[] firstRow = rows.get(0); assertEquals(firstRow[0], "\\\\'"); } @Test public void parseValueProcessingEscapeNotIgnoringWhitespacePrevQuoteEscape() { RowListProcessor processor = new RowListProcessor(); CsvParserSettings settings = newCsvInputSettings(getLineSeparator()); settings.setRowProcessor(processor); //Default used by CsvParserTest skip 2 lines settings.setKeepEscapeSequences(true); settings.setIgnoreTrailingWhitespaces(false); settings.setEscapeUnquotedValues(true); CsvFormat format = new CsvFormat(); format.setQuoteEscape('\''); format.setCharToEscapeQuoteEscaping('\\'); settings.setFormat(format); CsvParser parser = new CsvParser(settings); parser.parse(new StringReader("'\"a\n")); List rows = processor.getRows(); assertEquals(rows.size(), 1); String[] firstRow = rows.get(0); assertEquals(firstRow[0], "'\"a"); } @DataProvider public Object[][] skipLinesProvider() { return new Object[][]{ {0, "1234"}, {1, "234"}, {2, "34"}, {3, "4"}, {4, null}, {5, "BOOM"}, }; } @Test(dataProvider = "skipLinesProvider") public void testSkipLines(int rowsToSkip, String expectedResult) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\n"); settings.setNumberOfRowsToSkip(rowsToSkip); CsvParser parser = new CsvParser(settings); String input = "1\n2\n3\n4\n"; List result = parser.parseAll(new StringReader(input)); StringBuilder out = null; for (String row[] : result) { if (out == null) { out = new StringBuilder(); } assertEquals(row.length, 1); out.append(row[0]); } if("BOOM".equals(expectedResult)){ expectedResult = null; } assertEquals(out == null ? null : out.toString(), expectedResult); } @Test public void testParseUnescapedQuotesWithStop() { CsvParserSettings settings = new CsvParserSettings(); settings.setParseUnescapedQuotesUntilDelimiter(true); settings.getFormat().setLineSeparator("\n"); CsvParser parser = new CsvParser(settings); String input = "field1,\"inner quote\" field2,\"12,34\",\",5\","; String[] values = parser.parseLine(input); assertEquals(values[0], "field1"); assertEquals(values[1], "\"inner quote\" field2"); assertEquals(values[2], "12,34"); assertEquals(values[3], ",5"); assertEquals(values[4], null); } @Test public void parseIgnoreTrailingWhitespace() { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setLineSeparator("\n"); settings.setIgnoreTrailingWhitespaces(true); CsvParser parser = new CsvParser(settings); String[] value = parser.parseLine("b "); assertEquals(value[0], "b"); } @Test public void parseWithAutoExpansion() { CsvParserSettings settings = new CsvParserSettings(); settings.setMaxCharsPerColumn(-1); StringBuilder in = new StringBuilder(100000); for (int i = 0; i < 100000; i++) { in.append(i % 10); if (i % 10000 == 0) { in.append(','); } } String[] result = new CsvParser(settings).parseLine(in.toString()); StringBuilder out = new StringBuilder(); for (String value : result) { if (out.length() > 0) { out.append(','); } out.append(value); } assertEquals(out.toString(), in.toString()); } @Test public void testErrorMessageRestrictions() { CsvParserSettings settings = new CsvParserSettings(); settings.setMaxCharsPerColumn(3); settings.setErrorContentLength(0); try { new CsvParser(settings).parseLine("abcde"); fail("Expecting an exception here"); } catch (TextParsingException ex) { assertFalse(ex.getMessage().contains("abc")); assertNull(ex.getParsedContent()); } settings.setErrorContentLength(2); try { new CsvParser(settings).parseLine("abcde"); fail("Expecting an exception here"); } catch (TextParsingException ex) { assertTrue(ex.getMessage().contains("...bc")); assertEquals(ex.getParsedContent(), "abc"); } } @Test public void testKeepQuotes() { CsvParserSettings settings = new CsvParserSettings(); settings.setKeepQuotes(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape('\''); CsvParser parser = new CsvParser(settings); String[] result = parser.parseLine("a,'b', '', '' c '', '' ' '', ''''"); assertEquals(result[0], "a"); assertEquals(result[1], "'b'"); assertEquals(result[2], "''"); assertEquals(result[3], "'' c ''"); assertEquals(result[4], "'' ' ''"); assertEquals(result[5], "'''"); } @Test public void testNullValue() { CsvParserSettings settings = new CsvParserSettings(); settings.setIgnoreLeadingWhitespaces(false); settings.setIgnoreTrailingWhitespaces(true); settings.setNullValue("NULL"); CsvParser parser = new CsvParser(settings); String[] result = parser.parseLine(", ,"); assertEquals(result.length, 3); assertEquals(result[0], "NULL"); assertEquals(result[1], "NULL"); assertEquals(result[2], "NULL"); } @Test public void testColumnReorderingWithUserProvidedHeaders() throws Exception { CsvParserSettings settings = new CsvParserSettings(); settings.setHeaders("a", "b", "c"); settings.setColumnReorderingEnabled(false); settings.selectFields("a", "c"); String[] values = new CsvParser(settings).parseLine("1,2,3"); assertEquals(values, new String[]{"1", null, "3"}); } @Test public void testEscapeCharacter() { CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.getFormat().setQuoteEscape('/'); CsvParser parser = new CsvParser(parserSettings); String[] line; line = parser.parseLine("\"a ,/,b/,\",c"); assertEquals(line.length, 2); assertEquals(line[0], "a ,/,b/,"); assertEquals(line[1], "c"); line = parser.parseLine("\"a ,//,b//,\",c"); assertEquals(line.length, 2); assertEquals(line[0], "a ,/,b/,"); assertEquals(line[1], "c"); } @Test public void testBitsAreNotDiscardedWhenParsing() { CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setSkipBitsAsWhitespace(false); CsvParser parser = new CsvParser(parserSettings); String[] line; line = parser.parseLine("\0 a, b"); assertEquals(line.length, 2); assertEquals(line[0], "\0 a"); assertEquals(line[1], "b"); line = parser.parseLine("\1 a, b \0"); assertEquals(line.length, 2); assertEquals(line[0], "\1 a"); assertEquals(line[1], "b \0"); line = parser.parseLine("\2 a, \"b, \1\""); assertEquals(line.length, 2); assertEquals(line[0], "a"); assertEquals(line[1], "b, \1"); } @Test public void testParserIteratorOnFile() throws Exception { CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setLineSeparatorDetectionEnabled(true); CsvParser parser = new CsvParser(parserSettings); String[][] correctRows = { {"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}, {"j", null}, {"k", "l"}, {"m", "n", "o", "p", "q", "r"} }; Reader input = newReader("/csv/iterating_test.csv"); int i = 0; for (String[] row : parser.iterate(input)) { assertEquals(row, correctRows[i++]); } input = newReader("/csv/iterating_test.csv"); i = 0; for (Record row : parser.iterateRecords(input)) { assertEquals(row.getValues(), correctRows[i++]); } for (Record row : parser.iterateRecords(new StringReader(""))) { fail("Empty input, should not get here"); } } private static void append4000Symbols(StringBuilder sb) { final long startTime = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(200); for (int i = 0; i < 200; i++) { sb.append(startTime + TimeUnit.SECONDS.toMillis(i)).append(",10000\n"); } } @Test public void testCollectCommentOnBufferUpdate() { final StringBuilder commentLine = new StringBuilder("#"); for (int i = 0; i < 100; i++) { commentLine.append(' ').append(i); } final StringBuilder csv = new StringBuilder("time,value\n"); append4000Symbols(csv); // now the comment processing will meet buffer update operation (if buffer size is 4096) csv.append(commentLine); final CsvParserSettings csvParserSettings = new CsvParserSettings(); csvParserSettings.setCommentCollectionEnabled(true); csvParserSettings.setReadInputOnSeparateThread(false); final CsvParser csvParser = new CsvParser(csvParserSettings); csvParser.parseAll(new StringReader(csv.toString())); final Map comments = csvParser.getContext().comments(); assertEquals(1, comments.size()); assertEquals(commentLine.substring(2), comments.values().iterator().next()); } @Test public void shouldPrintUserDefinedHeaders() { final String[] userDefinedHeader = {"timestamp", "memory_used"}; final CsvParserSettings settings = new CsvParserSettings(); settings.setHeaderExtractionEnabled(false); settings.setHeaders(userDefinedHeader); final String[][] headersFromContext = new String[][]{null}; settings.setProcessor(new AbstractRowProcessor() { @Override public void processStarted(ParsingContext context) { headersFromContext[0] = context.headers(); System.out.println("headers: " + Arrays.toString(context.headers())); } }); settings.setReadInputOnSeparateThread(false); final CsvParser csvParser = new CsvParser(settings); final String csv = "2018-11-22T17:53:19.446Z,1493984088\n" + "2018-11-22T17:53:34.447Z,865556632\n" + "2018-11-22T17:53:49.447Z,600667192"; csvParser.parse(new StringReader(csv)); assertEquals(headersFromContext[0], userDefinedHeader); } @Test public void shouldResolveSpaceAsColumnSeparator() { final Reader csv = new StringReader("