From d34d725a50c630ec15a795427931a7afb17e4a6e Mon Sep 17 00:00:00 2001 From: Nick Molcanov <32801560+nck-mlcnv@users.noreply.github.com> Date: Wed, 7 Aug 2024 18:15:49 +0200 Subject: [PATCH 1/8] Fix release version substitution (#264) --- mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mkdocs.yml b/mkdocs.yml index 85d6812be..724747808 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Iguana $VERSION Documentation +site_name: Iguana $RELEASE_VERSION Documentation extra: version: $RELEASE_VERSION From 2d495e5d52aba1c9213814c88e46c4712555c145 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Aug 2024 17:32:42 +0200 Subject: [PATCH 2/8] Bump com.github.tomakehurst:wiremock-jre8-standalone (#262) Bumps [com.github.tomakehurst:wiremock-jre8-standalone](https://github.com/wiremock/wiremock) from 2.35.0 to 2.35.1. - [Release notes](https://github.com/wiremock/wiremock/releases) - [Commits](https://github.com/wiremock/wiremock/compare/2.35.0...2.35.1) --- updated-dependencies: - dependency-name: com.github.tomakehurst:wiremock-jre8-standalone dependency-type: direct:development ... Signed-off-by: dependabot[bot] Co-authored-by: Alexander Bigerl Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0d15dbecd..9728d96ec 100644 --- a/pom.xml +++ b/pom.xml @@ -127,7 +127,7 @@ com.github.tomakehurst wiremock-jre8-standalone - 2.35.0 + 2.35.1 test From cecf7261501c31bb98151b4083ec467486f8791a Mon Sep 17 00:00:00 2001 From: Nick Molcanov <32801560+nck-mlcnv@users.noreply.github.com> Date: Fri, 16 Aug 2024 15:09:39 +0200 Subject: [PATCH 3/8] Fix the response body processor timeout message (#267) * Fix the response body processor timeout message --- .../org/aksw/iguana/cc/worker/ResponseBodyProcessor.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/aksw/iguana/cc/worker/ResponseBodyProcessor.java b/src/main/java/org/aksw/iguana/cc/worker/ResponseBodyProcessor.java index 6dcec479d..af3e297a1 100644 --- a/src/main/java/org/aksw/iguana/cc/worker/ResponseBodyProcessor.java +++ b/src/main/java/org/aksw/iguana/cc/worker/ResponseBodyProcessor.java @@ -72,7 +72,10 @@ public List getResponseDataMetrics() { return responseDataMetrics; } - LOGGER.info(MessageFormat.format("Shutting down ResponseBodyProcessor with {0} min timeout to finish processing. {1} tasks remaining.", timeout.toMinutes() + "." + (timeout.toSecondsPart() / (double) 60), executor.getQueue().size())); + LOGGER.info(MessageFormat.format("Shutting down ResponseBodyProcessor with {0}min {1}s timeout to finish processing. {2} tasks remaining.", + timeout.toMinutes(), + String.format("%02d", timeout.toSecondsPart()), + executor.getQueue().size())); boolean noTimeout; try { executor.shutdown(); From 12816354c8ca792c5eae3afe950d508d100b62ea Mon Sep 17 00:00:00 2001 From: Nick Molcanov <32801560+nck-mlcnv@users.noreply.github.com> Date: Fri, 16 Aug 2024 18:20:00 +0200 Subject: [PATCH 4/8] Change licenses (#268) * Change licenses * Update LICENSE-MIT Co-authored-by: Alexander Bigerl * Change owner and formatting --------- Co-authored-by: Alexander Bigerl --- LICENSE | 661 --------------------------------------------- LICENSE-APACHE-2.0 | 204 ++++++++++++++ LICENSE-MIT | 24 ++ 3 files changed, 228 insertions(+), 661 deletions(-) delete mode 100644 LICENSE create mode 100644 LICENSE-APACHE-2.0 create mode 100644 LICENSE-MIT diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 6826266b1..000000000 --- a/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - 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 -them 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. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey 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; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If 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 convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - 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. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -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. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - 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 -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - IGUANA is a benchmark execution framework for triple stores, - Copyright (C) 2012 - today Data Science Research Group at http://dice-research.org/ - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/LICENSE-APACHE-2.0 b/LICENSE-APACHE-2.0 new file mode 100644 index 000000000..b5422b5cd --- /dev/null +++ b/LICENSE-APACHE-2.0 @@ -0,0 +1,204 @@ + 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 2024 - Data Science Research Group - + Faculty of Computer Science, Electrical Engineering and Mathematics - + Universität Paderborn, Warburger Str. 100, 33098 Paderborn + (https://dice-research.org/ and https://en.cs.uni-paderborn.de/ds) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 000000000..7d5f55aa3 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,24 @@ +MIT License + +Copyright (c) 2024 - Data Science Research Group - + Faculty of Computer Science, Electrical Engineering and Mathematics - + Universität Paderborn, Warburger Str. 100, 33098 Paderborn + (https://dice-research.org/ and https://en.cs.uni-paderborn.de/ds) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 0314a6894cbf5fb64dd34aaec9efc4f167927c44 Mon Sep 17 00:00:00 2001 From: Nick Molcanov <32801560+nck-mlcnv@users.noreply.github.com> Date: Fri, 6 Sep 2024 09:18:03 +0200 Subject: [PATCH 5/8] Add XML, CSV and TSV result counting parser (#270) * Add xml parser * Add link and ask * Add csv and tsv parser --- docs/configuration/response_body_processor.md | 17 +- .../iguana/cc/lang/LanguageProcessor.java | 5 +- .../cc/lang/impl/BooleanResultData.java | 60 ++++ .../iguana/cc/lang/impl/ResultCountData.java | 67 ++++ .../SaxSparqlJsonResultCountingParser.java | 105 +++--- .../SaxSparqlXmlResultCountingParser.java | 330 ++++++++++++++++++ .../impl/SparqlCsvResultCountingParser.java | 56 +++ .../impl/SparqlTsvResultCountingParser.java | 63 ++++ .../org/aksw/iguana/commons/rdf/IPROP.java | 2 + ...SaxSparqlJsonResultCountingParserTest.java | 157 +++++++++ .../SaxSparqlXmlResultCountingParserTest.java | 142 ++++++++ .../SparqlCsvResultCountingParserTest.java | 36 ++ .../SparqlTsvResultCountingParserTest.java | 35 ++ 13 files changed, 1006 insertions(+), 69 deletions(-) create mode 100644 src/main/java/org/aksw/iguana/cc/lang/impl/BooleanResultData.java create mode 100644 src/main/java/org/aksw/iguana/cc/lang/impl/ResultCountData.java create mode 100644 src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParser.java create mode 100644 src/main/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParser.java create mode 100644 src/main/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParser.java create mode 100644 src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParserTest.java create mode 100644 src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParserTest.java create mode 100644 src/test/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParserTest.java create mode 100644 src/test/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParserTest.java diff --git a/docs/configuration/response_body_processor.md b/docs/configuration/response_body_processor.md index 5b4cc7259..caa463555 100644 --- a/docs/configuration/response_body_processor.md +++ b/docs/configuration/response_body_processor.md @@ -6,9 +6,20 @@ The processing is done to extract relevant information from the responses and st Iguana supports multiple response body processors that are defined by the content type of the response body they process. -Currently only the `application/sparql-results+json` content type is supported, -and it only uses the `SaxSparqlJsonResultCountingParser` language processor -to extract simple information from the responses. +The following content types are supported: +- `application/sparql-results+json` +- `application/sparql-results+xml` +- `text/csv` +- `text/tab-separated-values` + + +For the `json` and `xml` content types, +the response body processor counts for `SELECT` queries +the number of results and bindings and lists all variables and link attributes. +If the requested query was a `ASK` query, the response body processor stores the boolean result. + +For the `csv` and `tsv` content types, only `SELECT` queries are supported. +The response body processor counts the number of results and bindings and lists all variables. Workers send the response bodies to the response body processors, after receiving the full response bodies from the HTTP requests. diff --git a/src/main/java/org/aksw/iguana/cc/lang/LanguageProcessor.java b/src/main/java/org/aksw/iguana/cc/lang/LanguageProcessor.java index ee8868528..8c46e7596 100644 --- a/src/main/java/org/aksw/iguana/cc/lang/LanguageProcessor.java +++ b/src/main/java/org/aksw/iguana/cc/lang/LanguageProcessor.java @@ -33,7 +33,7 @@ public abstract class LanguageProcessor { public interface LanguageProcessingData extends Storable { long hash(); - Class processor(); + Exception exception(); } public abstract LanguageProcessingData process(InputStream inputStream, long hash); @@ -45,6 +45,9 @@ public interface LanguageProcessingData extends Storable { // Register all available LanguageProcessors here. static { processors.put("application/sparql-results+json", org.aksw.iguana.cc.lang.impl.SaxSparqlJsonResultCountingParser.class); + processors.put("application/sparql-results+xml", org.aksw.iguana.cc.lang.impl.SaxSparqlXmlResultCountingParser.class); + processors.put("text/tab-separated-values", org.aksw.iguana.cc.lang.impl.SparqlTsvResultCountingParser.class); + processors.put("text/csv", org.aksw.iguana.cc.lang.impl.SparqlCsvResultCountingParser.class); } public static LanguageProcessor getInstance(String contentType) { diff --git a/src/main/java/org/aksw/iguana/cc/lang/impl/BooleanResultData.java b/src/main/java/org/aksw/iguana/cc/lang/impl/BooleanResultData.java new file mode 100644 index 000000000..746042d3f --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/lang/impl/BooleanResultData.java @@ -0,0 +1,60 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.aksw.iguana.cc.lang.LanguageProcessor; +import org.aksw.iguana.cc.storage.Storable; +import org.aksw.iguana.commons.rdf.IPROP; +import org.aksw.iguana.commons.rdf.IRES; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.ResourceFactory; + +import java.util.List; + +public record BooleanResultData( + long hash, + Boolean result, + List links, + Exception exception + ) implements LanguageProcessor.LanguageProcessingData, Storable.AsCSV, Storable.AsRDF { + final static String[] header = new String[]{ "responseBodyHash", "boolean", "links", "exception" }; + + @Override + public Storable.CSVData toCSV() { + String resultString = ""; + String exceptionString = ""; + String linksString = ""; + if (result != null) + resultString = result.toString(); + if (exception != null) + exceptionString = exception().toString(); + if (links != null) + linksString = String.join("; ", links); + + String[] content = new String[]{ String.valueOf(hash), resultString, linksString, exceptionString }; + String[][] data = new String[][]{ header, content }; + + String folderName = "sparql-ask-result-data"; + List files = List.of(new Storable.CSVData.CSVFileData("sparql-ask-result.csv", data)); + return new Storable.CSVData(folderName, files); + } + + @Override + public Model toRDF() { + Model m = ModelFactory.createDefaultModel(); + Resource responseBodyRes = IRES.getResponsebodyResource(this.hash); + if (this.result != null) { + m.add(responseBodyRes, IPROP.askBoolean, ResourceFactory.createTypedLiteral(this.result)); + } + if (this.links != null) { + for (String link : this.links) { + m.add(responseBodyRes, IPROP.link, ResourceFactory.createTypedLiteral(link)); + } + } + if (this.exception != null) { + m.add(responseBodyRes, IPROP.exception, ResourceFactory.createTypedLiteral(this.exception.toString())); + } + + return m; + } +} diff --git a/src/main/java/org/aksw/iguana/cc/lang/impl/ResultCountData.java b/src/main/java/org/aksw/iguana/cc/lang/impl/ResultCountData.java new file mode 100644 index 000000000..d2e05454f --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/lang/impl/ResultCountData.java @@ -0,0 +1,67 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.aksw.iguana.cc.lang.LanguageProcessor; +import org.aksw.iguana.cc.storage.Storable; +import org.aksw.iguana.commons.rdf.IPROP; +import org.aksw.iguana.commons.rdf.IRES; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.ResourceFactory; + +import java.util.List; + +public record ResultCountData ( + long hash, + long results, + long bindings, + List variables, + List links, + Exception exception +) implements LanguageProcessor.LanguageProcessingData, Storable.AsCSV, Storable.AsRDF { + final static String[] header = new String[]{ "responseBodyHash", "results", "bindings", "variables", "links", "exception" }; + + @Override + public Storable.CSVData toCSV() { + String variablesString = ""; + String exceptionString = ""; + String linksString = ""; + if (variables != null) + variablesString = String.join("; ", variables); + if (exception != null) + exceptionString = exception().toString(); + if (links != null) + linksString = String.join("; ", links); + + String[] content = new String[]{ String.valueOf(hash), String.valueOf(results), String.valueOf(bindings), variablesString, linksString, exceptionString }; + String[][] data = new String[][]{ header, content }; + + String folderName = "result-count-data"; + List files = List.of(new Storable.CSVData.CSVFileData("result-count.csv", data)); + return new Storable.CSVData(folderName, files); + } + + @Override + public Model toRDF() { + Model m = ModelFactory.createDefaultModel(); + Resource responseBodyRes = IRES.getResponsebodyResource(this.hash); + m.add(responseBodyRes, IPROP.results, ResourceFactory.createTypedLiteral(this.results)) + .add(responseBodyRes, IPROP.bindings, ResourceFactory.createTypedLiteral(this.bindings)); + + if (this.variables != null) { + for (String variable : this.variables) { + m.add(responseBodyRes, IPROP.variable, ResourceFactory.createTypedLiteral(variable)); + } + } + if (this.links != null) { + for (String link : this.links) { + m.add(responseBodyRes, IPROP.link, ResourceFactory.createTypedLiteral(link)); + } + } + if (this.exception != null) { + m.add(responseBodyRes, IPROP.exception, ResourceFactory.createTypedLiteral(this.exception.toString())); + } + + return m; + } +} diff --git a/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParser.java b/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParser.java index 42a8a4eaf..94277c065 100644 --- a/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParser.java +++ b/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParser.java @@ -1,16 +1,10 @@ package org.aksw.iguana.cc.lang.impl; import org.aksw.iguana.cc.lang.LanguageProcessor; -import org.aksw.iguana.cc.storage.Storable; -import org.aksw.iguana.commons.rdf.IPROP; -import org.aksw.iguana.commons.rdf.IRES; -import org.apache.jena.rdf.model.Model; -import org.apache.jena.rdf.model.ModelFactory; -import org.apache.jena.rdf.model.Resource; -import org.apache.jena.rdf.model.ResourceFactory; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; +import org.slf4j.Logger; import java.io.BufferedReader; import java.io.IOException; @@ -24,79 +18,34 @@ /** * SAX Parser for SPARQL JSON Results. - * For correct SPARQL JSON Results it returns the number of solutions, bound values and the names of the variables. + * For correct SPARQL JSON results, it returns the number of solutions, bound values and the names of the variables. * For malformed results it may or may not fail. For malformed JSON it fails if the underlying json.simple.parser fails. + *

+ * Specification: https://www.w3.org/TR/sparql11-results-json/ */ @LanguageProcessor.ContentType("application/sparql-results+json") public class SaxSparqlJsonResultCountingParser extends LanguageProcessor { + private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SaxSparqlJsonResultCountingParser.class); + @Override public LanguageProcessingData process(InputStream inputStream, long hash) { var parser = new JSONParser(); var handler = new SaxSparqlJsonResultContentHandler(); try { parser.parse(new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)), handler); - return new SaxSparqlJsonResultData(hash, handler.solutions(), handler.boundValues(), handler.variables(), null); + if (handler.isAskResult()) + return new BooleanResultData(hash, handler.booleanResult(), handler.links(), null); + return new ResultCountData(hash, handler.solutions(), handler.boundValues(), handler.variables(), handler.links(), null); } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { - return new SaxSparqlJsonResultData(hash, -1, -1, null, e); - } - } - - record SaxSparqlJsonResultData( - long hash, - long results, - long bindings, - List variables, - Exception exception - ) implements LanguageProcessingData, Storable.AsCSV, Storable.AsRDF { - final static String[] header = new String[]{ "responseBodyHash", "results", "bindings", "variables", "exception" }; - - @Override - public Class processor() { - return SaxSparqlJsonResultCountingParser.class; - } - - @Override - public CSVData toCSV() { - String variablesString = ""; - String exceptionString = ""; - if (variables != null) - variablesString = String.join("; ", variables); - if (exception != null) - exceptionString = exception().toString(); - - String[] content = new String[]{ String.valueOf(hash), String.valueOf(results), String.valueOf(bindings), variablesString, exceptionString}; - String[][] data = new String[][]{ header, content }; - - String folderName = "application-sparql+json"; - List files = List.of(new CSVData.CSVFileData("sax-sparql-result-data.csv", data)); - return new Storable.CSVData(folderName, files); - } - - @Override - public Model toRDF() { - Model m = ModelFactory.createDefaultModel(); - Resource responseBodyRes = IRES.getResponsebodyResource(this.hash); - m.add(responseBodyRes, IPROP.results, ResourceFactory.createTypedLiteral(this.results)) - .add(responseBodyRes, IPROP.bindings, ResourceFactory.createTypedLiteral(this.bindings)); - - if (this.variables != null) { - for (String variable : this.variables) { - m.add(responseBodyRes, IPROP.variable, ResourceFactory.createTypedLiteral(variable)); - } - } - if (this.exception != null) { - m.add(responseBodyRes, IPROP.exception, ResourceFactory.createTypedLiteral(this.exception.toString())); - } - - return m; + LOGGER.error("Error while parsing SPARQL XML Results.", e); + return new ResultCountData(hash, -1, -1, null, null, e); } } private static class SaxSparqlJsonResultContentHandler implements ContentHandler { - // TODO: add support for ask queries and link // TODO: code is unnecessary complicated private boolean headFound = false; @@ -106,12 +55,14 @@ private static class SaxSparqlJsonResultContentHandler implements ContentHandler private boolean inBindings = false; private boolean inBindingsArray = false; private boolean inVars = false; + private boolean inLink = false; + private boolean inBoolean = false; private long boundValues = 0; - private long solutions = 0; - + private Boolean booleanResult = null; private final List variables = new ArrayList<>(); + private final List links = new ArrayList<>(); @Override @@ -165,6 +116,8 @@ public boolean startArray() { public boolean endArray() { if (inVars) inVars = false; + if (inLink) + inLink = false; if (objectDepth == 2 && inResults && inBindings && inBindingsArray) { inBindingsArray = false; } @@ -182,6 +135,10 @@ public boolean startObjectEntry(String key) { if (headFound) inResults = true; } + case "boolean" -> { + if (headFound) + inBoolean = true; + } } } case 2 -> { @@ -191,6 +148,9 @@ public boolean startObjectEntry(String key) { if ("vars".compareTo(key) == 0) { inVars = true; } + if ("link".compareTo(key) == 0) { + inLink = true; + } } } return true; @@ -204,7 +164,10 @@ public boolean endObjectEntry() { public boolean primitive(Object value) { if (inVars) variables.add(value.toString()); - + if (inLink) + links.add(value.toString()); + if (inBoolean && value instanceof Boolean val) + booleanResult = val; return true; } @@ -219,5 +182,17 @@ public long solutions() { public List variables() { return variables; } + + public List links() { + return links; + } + + public Boolean booleanResult() { + return booleanResult; + } + + public boolean isAskResult() { + return booleanResult != null; + } } } \ No newline at end of file diff --git a/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParser.java b/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParser.java new file mode 100644 index 000000000..afde5513a --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParser.java @@ -0,0 +1,330 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.aksw.iguana.cc.lang.LanguageProcessor; +import org.aksw.iguana.cc.storage.Storable; +import org.aksw.iguana.commons.rdf.IPROP; +import org.aksw.iguana.commons.rdf.IRES; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.ResourceFactory; +import org.slf4j.Logger; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import java.io.IOException; +import java.io.InputStream; +import java.nio.CharBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.json.simple.parser.ParseException.ERROR_UNEXPECTED_EXCEPTION; + +/** + * SAX Parser for SPARQL XML Results. + * For correct SPARQL XML Results it returns the number of solutions, bound values, the names of the variables and links. + * Fails for malformed SPARQL XML Results. + *

+ * Specification: https://www.w3.org/TR/rdf-sparql-XMLres/ + */ +@LanguageProcessor.ContentType("application/sparql-results+xml") +public class SaxSparqlXmlResultCountingParser extends LanguageProcessor { + + private final static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SaxSparqlXmlResultCountingParser.class); + + private final static SAXParserFactory factory = SAXParserFactory.newInstance(); + + @Override + public LanguageProcessingData process(InputStream inputStream, long hash) { + try { + final var parser = factory.newSAXParser(); + final var handler = new SaxSparqlXmlResultContentHandler(); + parser.parse(inputStream, handler); + if (handler.isAskResult()) { + return new BooleanResultData(hash, handler.askResult(), handler.links(), null); + } + return new ResultCountData(hash, handler.solutions(), handler.boundValues(), handler.variables(), handler.links(), null); + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.error("Error while parsing SPARQL XML Results.", e); + return new ResultCountData(hash, -1, -1, null, null, e); // default to result count data + } + } + + private static class SaxSparqlXmlResultContentHandler extends DefaultHandler { + /* + * The parser uses a state machine to parse the XML. + * The state machine for the parser is as follows: + * + * ┌─────┐ ┌──────────────┐ ┌──────┐ + * ────►│Start├──────────────►│SPARQL-Element├───────►│Header│ + * └─────┘ └──────────────┘ └─┬─┬─┬┘ + * │ │ │ + * ┌─────────────────────────────┘ │ │ + * │ │ │ + * │ ┌─────────────┘ │ + * │ │ │ + * │ │ ┌─────┘ + * │ │ │ + * ▼ │ │ + * ┌──────┐ │ │ + * ┌───┤SELECT│ │ │ + * └──►│Header│ │ │ + * ┌───┐ └──┬─┬─┘ │ │ + * │ │ │ │ │ │ + * ▼ │ │ │ │ ▼ + * ┌─────┴───────┐ │ │ │ ┌──────┐ + * │SELECT Header│◄────┘ │ │ │ ASK │──┐ + * │ Links ├─────┐ │ │ │Header│◄─┘ + * └─────────────┘ │ │ │ └──┬───┘ + * │ │ │ │ + * ▼ ▼ ▼ │ + * ┌─────────────┐ ┌──────────┐ │ + * │SELECT Header│ │ASK Header│◄──┘ + * │ End │ │ End │ + * └────────┬────┘ └────┬─────┘ + * ┌───────┐ │ │ + * │Binding│ │ │ + * │ End ├─────────────┐ │ ▼ + * └───────┘ │ │ ┌──────────┐ true | false + * ▲ │ │ │ASK Result├───┐ + * │ ||│ │ └────┬─────┘◄──┘ + * │ │ │ │ + * ┌──┴──┐◄─┐ │ │ │ + * │Value├──┘ │ │ │ + * └─────┘ value │ │ │ + * ▲ │ │ │ + * │ │ │ │ + * │ || ▼ │ │ + * │ ▼ │ + * ┌───┴───┐ ┌──────┐ ┌───────┐ │ + * │Binding│◄──────────┤SELECT│◄──────────┤SELECT │ │ + * └───────┘ │Result├──────────►│Results│ │ + * └──────┘ └───┬───┘ │ + * │ │ + * │ │ + * ▼ │ + * ┌───────┐ │ + * │Results│ │ + * │ End │◄───────────┘ + * └───┬───┘ + * ▼ + * ┌─────┐ + * │┌───┐│ + * ││End││ + * │└───┘│ + * └─────┘ + */ + private enum State { + START, + SPARQL, + HEADER_START, + HEADER_SELECT, + HEADER_ASK, + HEADER_SELECT_LINK, + HEADER_SELECT_END, + HEADER_ASK_END, + ASK_RESULT, + SELECT_RESULTS, + SELECT_SINGLE_RESULT, + SELECT_BINDING, + SELECT_BINDING_VALUE, + SELECT_BINDING_END, + RESULTS_END, + END + } + + + private long boundValues = 0; + private long solutions = 0; + private final List variables = new ArrayList<>(); + private final List links = new ArrayList<>(); + + private final CharBuffer charBuffer = CharBuffer.allocate(5); // to store the string "true" or "false" for ask results + private Boolean askResult = null; + + private State state = State.START; + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + switch (state) { + case START -> { + if (qName.equals("sparql") && attributes.getValue("xmlns").equals("http://www.w3.org/2005/sparql-results#")) { + state = State.SPARQL; + } else { + throw new SAXException("First element must be . Found <" + qName + "> instead."); + } + } + case SPARQL -> { + if (qName.equals("head")) { + state = State.HEADER_START; + } else { + throw new SAXException("First element inside the -element must be . Found <" + qName + "> instead."); + } + } + case HEADER_START -> { + switch (qName) { + case "variable" -> { + state = State.HEADER_SELECT; + final var name = attributes.getValue("name"); + if (name == null) + throw new SAXException("No name attribute found for inside ."); + variables.add(name); + } + case "link" -> { + state = State.HEADER_ASK; + final var href = attributes.getValue("href"); + if (href == null) + throw new SAXException("No href attribute found for inside ."); + links.add(href); + } + default -> throw new SAXException("Unexpected element <" + qName + "> inside ."); + } + } + case HEADER_SELECT -> { + if (qName.equals("variable")) { + final var name = attributes.getValue("name"); + if (name == null) + throw new SAXException("No name attribute found for inside ."); + variables.add(name); + } else if (qName.equals("link")) { + state = State.HEADER_SELECT_LINK; + final var href = attributes.getValue("href"); + if (href == null) + throw new SAXException("No href attribute found for inside ."); + links.add(href); + } else { + throw new SAXException("Unexpected element <" + qName + "> inside ."); + } + } + case HEADER_SELECT_LINK -> { + if (qName.equals("link")) { + state = State.HEADER_SELECT_END; + } else { + throw new SAXException("Unexpected element <" + qName + "> inside after -elements."); + } + } + case HEADER_SELECT_END -> { + if (qName.equals("results")) { + state = State.SELECT_RESULTS; + } else { + throw new SAXException("Unexpected element <" + qName + "> inside after for SELECT results."); + } + } + case HEADER_ASK_END -> { + if (qName.equals("boolean")) { + state = State.ASK_RESULT; + } else { + throw new SAXException("Unexpected element <" + qName + "> inside after for ASK results."); + } + } + case SELECT_RESULTS -> { + if (qName.equals("result")) { + state = State.SELECT_SINGLE_RESULT; + solutions += 1; + } else { + throw new SAXException("Unexpected element <" + qName + "> inside ."); + } + } + case SELECT_SINGLE_RESULT -> { + if (qName.equals("binding")) { + state = State.SELECT_BINDING; + boundValues += 1; + } else { + throw new SAXException("Unexpected element <" + qName + "> inside ."); + } + } + case SELECT_BINDING -> { + if (qName.equals("uri") || qName.equals("bnode") || qName.equals("literal")) { + state = State.SELECT_BINDING_VALUE; + } else { + throw new SAXException("Unexpected element <" + qName + "> inside ."); + } + } + default -> throw new SAXException("Unexpected element <" + qName + ">. Found in state " + state + "."); + } + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + switch (state) { + case HEADER_START, HEADER_ASK -> { + if (qName.equals("head")) state = State.HEADER_ASK_END; + } + case HEADER_SELECT, HEADER_SELECT_LINK -> { + if (qName.equals("head")) state = State.HEADER_SELECT_END; + } + case SELECT_BINDING_VALUE -> { + if (qName.equals("uri") || qName.equals("bnode") || qName.equals("literal")) state = State.SELECT_BINDING_END; + } + case SELECT_BINDING_END -> { + if (qName.equals("binding")) state = State.SELECT_SINGLE_RESULT; + } + case SELECT_SINGLE_RESULT -> { + if (qName.equals("result")) state = State.SELECT_RESULTS; + } + case SELECT_RESULTS -> { + if (qName.equals("results")) state = State.RESULTS_END; + } + case ASK_RESULT -> { + if (qName.equals("boolean")) state = State.RESULTS_END; + } + case RESULTS_END -> { + if (qName.equals("sparql")) state = State.END; + } + } + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + if (Objects.requireNonNull(state) == State.ASK_RESULT) { + charBuffer.put(ch, start, Math.min(charBuffer.remaining(), length)); + if (charBuffer.position() == 4) { + final var temp = charBuffer.asReadOnlyBuffer(); + temp.flip(); + String value = temp.toString(); + if (value.equals("true")) { + askResult = true; + } + } else if (charBuffer.position() == 5) { + final var temp = charBuffer.asReadOnlyBuffer(); + temp.flip(); + String value = temp.toString(); + if (value.equals("false")) { + askResult = false; + } else { + throw new SAXException("Unexpected value for : " + value); + } + } + } + } + + public long boundValues() { + return boundValues; + } + + public long solutions() { + return solutions; + } + + public List variables() { + return variables; + } + + public List links() { + return links; + } + + public boolean isAskResult() { + return askResult != null; + } + + public Boolean askResult() { + return askResult; + } + } + +} diff --git a/src/main/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParser.java b/src/main/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParser.java new file mode 100644 index 000000000..2147ee36a --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParser.java @@ -0,0 +1,56 @@ +package org.aksw.iguana.cc.lang.impl; + +import com.opencsv.*; +import com.opencsv.exceptions.CsvValidationException; +import org.aksw.iguana.cc.lang.LanguageProcessor; +import org.slf4j.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * CSV Parser for SPARQL CSV Results. + * For correct SPARQL CSV results, it returns the number of solutions, bound values and the names of the variables. + *

+ * Specification: https://www.w3.org/TR/sparql11-results-csv-tsv/ + */ +@LanguageProcessor.ContentType("text/csv") +public class SparqlCsvResultCountingParser extends LanguageProcessor { + + private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SparqlCsvResultCountingParser.class); + + @Override + public LanguageProcessingData process(InputStream inputStream, long hash) { + + try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + ICSVParser parser = new RFC4180Parser(); + CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader); + try (CSVReader csvReader = csvReaderBuilder.withCSVParser(parser).build()) { + String[] line = csvReader.readNext(); + if (line == null) { + return new ResultCountData(hash, 0, 0, null, null, null); + } + final var variables = List.of(line); // the first line is always header with variables + long solutions = 0; + long boundValues = 0; + while ((line = csvReader.readNext()) != null) { + solutions++; + for (String value : line) { + if (!value.isEmpty()) boundValues++; // empty string values and empty cells are not differentiated + } + } + return new ResultCountData(hash, solutions, boundValues, variables, null, null); + } catch (CsvValidationException e) { + LOGGER.error("Error while parsing SPARQL CSV Results.", e); + return new ResultCountData(hash, -1, -1, null, null, e); + } + } catch (IOException e) { + LOGGER.error("Error while parsing SPARQL CSV Results.", e); + return new ResultCountData(hash, -1, -1, null, null, e); + } + } +} diff --git a/src/main/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParser.java b/src/main/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParser.java new file mode 100644 index 000000000..46d134d83 --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParser.java @@ -0,0 +1,63 @@ +package org.aksw.iguana.cc.lang.impl; + +import com.opencsv.*; +import com.opencsv.enums.CSVReaderNullFieldIndicator; +import com.opencsv.exceptions.CsvValidationException; +import org.aksw.iguana.cc.lang.LanguageProcessor; +import org.slf4j.Logger; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.List; + + +/** + * TSV Parser for SPARQL TSV Results. + * For correct SPARQL TSV results, it returns the number of solutions, bound values and the names of the variables. + *

+ * Specification: https://www.w3.org/TR/sparql11-results-csv-tsv/ + */ +@LanguageProcessor.ContentType("text/tab-separated-values") +public class SparqlTsvResultCountingParser extends LanguageProcessor { + + private final static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SparqlTsvResultCountingParser.class); + + @Override + public LanguageProcessingData process(InputStream inputStream, long hash) { + + try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + CSVParserBuilder builder = new CSVParserBuilder(); + CSVParser parser = builder.withSeparator('\t') + .withIgnoreQuotations(true) + .withEscapeChar('\\') + .withStrictQuotes(false) + .withIgnoreLeadingWhiteSpace(false) + .withQuoteChar('#') + .withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS) + .build(); + CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader); + try (CSVReader csvReader = csvReaderBuilder.withCSVParser(parser).build()) { + String[] line = csvReader.readNext(); + if (line == null) { + return new ResultCountData(hash, 0, 0, null, null, null); + } + final var variables = List.of(line); // the first line is always header with variables + long solutions = 0; + long boundValues = 0; + while ((line = csvReader.readNext()) != null) { + solutions++; + for (String value : line) { + if (value != null) boundValues++; + } + } + return new ResultCountData(hash, solutions, boundValues, variables, null, null); + } catch (CsvValidationException e) { + LOGGER.error("Error while parsing SPARQL TSV Results.", e); + return new ResultCountData(hash, -1, -1, null, null, e); + } + } catch (IOException e) { + LOGGER.error("Error while parsing SPARQL TSV Results.", e); + return new ResultCountData(hash, -1, -1, null, null, e); + } + } +} diff --git a/src/main/java/org/aksw/iguana/commons/rdf/IPROP.java b/src/main/java/org/aksw/iguana/commons/rdf/IPROP.java index 298f9b06d..705513651 100644 --- a/src/main/java/org/aksw/iguana/commons/rdf/IPROP.java +++ b/src/main/java/org/aksw/iguana/commons/rdf/IPROP.java @@ -49,6 +49,8 @@ public static Property createMetricProperty(Metric metric) { public static final Property bindings = ResourceFactory.createProperty(NS, "bindings"); public static final Property variable = ResourceFactory.createProperty(NS, "variable"); public static final Property exception = ResourceFactory.createProperty(NS, "exception"); + public static final Property link = ResourceFactory.createProperty(NS, "link"); + public static final Property askBoolean = ResourceFactory.createProperty(NS, "askBoolean"); // Query Stats diff --git a/src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParserTest.java b/src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParserTest.java new file mode 100644 index 000000000..23f7c2c56 --- /dev/null +++ b/src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlJsonResultCountingParserTest.java @@ -0,0 +1,157 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; + +import static org.junit.jupiter.api.Assertions.*; + +public class SaxSparqlJsonResultCountingParserTest { + + private final String SELECT_RESULT_WITHOUT_LINKS = """ + { + "head": { "vars": [ "book" , "title" ] + } , + "results": { + "bindings": [ + { + "book": { "type": "uri" , "value": "http://example.org/book/book6" } , + "title": { "type": "literal" , "value": "Harry Potter and the Half-Blood Prince" } + } , + { + "book": { "type": "uri" , "value": "http://example.org/book/book7" } , + "title": { "type": "literal" , "value": "Harry Potter and the Deathly Hallows" } + } , + { + "book": { "type": "uri" , "value": "http://example.org/book/book5" } , + "title": { "type": "literal" , "value": "Harry Potter and the Order of the Phoenix" } + } , + { + "book": { "type": "uri" , "value": "http://example.org/book/book4" } , + "title": { "type": "literal" , "value": "Harry Potter and the Goblet of Fire" } + } , + { + "book": { "type": "uri" , "value": "http://example.org/book/book2" } , + "title": { "type": "literal" , "value": "Harry Potter and the Chamber of Secrets" } + } , + { + "book": { "type": "uri" , "value": "http://example.org/book/book3" } , + "title": { "type": "literal" , "value": "Harry Potter and the Prisoner Of Azkaban" } + } , + { + "book": { "type": "uri" , "value": "http://example.org/book/book1" } , + "title": { "type": "literal" , "value": "Harry Potter and the Philosopher's Stone" } + } + ] + } + } + """; // 7 results, 14 bindings + + private final String SELECT_RESULT = """ + { + "head": { + "link": ["http://www.w3.org/TR/rdf-sparql-XMLres/example.rq"], + "vars": [ + "x", + "hpage", + "name", + "mbox", + "age", + "blurb", + "friend" + ] + }, + "results": { + "bindings": [ + { + "x" : { "type": "bnode", "value": "r1" }, + "hpage" : { "type": "uri", "value": "http://work.example.org/alice/" }, + "name" : { "type": "literal", "value": "Alice" } , + "mbox" : { "type": "literal", "value": "" } , + "blurb" : { + "datatype": "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral", + "type": "literal", + "value": "

My name is alice

" + }, + "friend" : { "type": "bnode", "value": "r2" } + }, + { + "x" : { "type": "bnode", "value": "r2" }, + "hpage" : { "type": "uri", "value": "http://work.example.org/bob/" }, + "name" : { "type": "literal", "value": "Bob", "xml:lang": "en" }, + "mbox" : { "type": "uri", "value": "mailto:bob@work.example.org" }, + "friend" : { "type": "bnode", "value": "r1" } + } + ] + } + } + """; // 2 results, 11 bindings + + private final String ASK_RESULT_WIHTOUT_LINKS = """ + { + "head": { } , + "boolean": true + } + """; + + private final String ASK_RESULT = """ + { + "head": { "link": ["http://www.w3.org/TR/rdf-sparql-XMLres/example.rq"] } , + "boolean": true + } + """; + + @Test + public void testSelectWithLink() { + final SaxSparqlJsonResultCountingParser parser = new SaxSparqlJsonResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(SELECT_RESULT.getBytes()), 0); + assertInstanceOf(ResultCountData.class, data); + final var result = (ResultCountData) data; + assertEquals(2, result.results()); + assertEquals(11, result.bindings()); + assertEquals(7, result.variables().size()); + assertEquals(1, result.links().size()); + assertEquals("x", result.variables().get(0)); + assertEquals("hpage", result.variables().get(1)); + assertEquals("name", result.variables().get(2)); + assertEquals("mbox", result.variables().get(3)); + assertEquals("age", result.variables().get(4)); + assertEquals("blurb", result.variables().get(5)); + assertEquals("friend", result.variables().get(6)); + assertEquals("http://www.w3.org/TR/rdf-sparql-XMLres/example.rq", result.links().get(0)); + } + + @Test + public void testSelectWithoutLink() { + final SaxSparqlJsonResultCountingParser parser = new SaxSparqlJsonResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(SELECT_RESULT_WITHOUT_LINKS.getBytes()), 0); + assertInstanceOf(ResultCountData.class, data); + final var result = (ResultCountData) data; + assertEquals(7, result.results()); + assertEquals(14, result.bindings()); + assertEquals(2, result.variables().size()); + assertEquals(0, result.links().size()); + assertEquals("book", result.variables().get(0)); + assertEquals("title", result.variables().get(1)); + } + + @Test + public void testAskWithLink() { + final SaxSparqlJsonResultCountingParser parser = new SaxSparqlJsonResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(ASK_RESULT.getBytes()), 0); + assertInstanceOf(BooleanResultData.class, data); + final var result = (BooleanResultData) data; + assertTrue(result.result()); + assertEquals("http://www.w3.org/TR/rdf-sparql-XMLres/example.rq", result.links().get(0)); + } + + @Test + public void testAskWithoutLink() { + final SaxSparqlJsonResultCountingParser parser = new SaxSparqlJsonResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(ASK_RESULT_WIHTOUT_LINKS.getBytes()), 0); + assertInstanceOf(BooleanResultData.class, data); + final var result = (BooleanResultData) data; + assertTrue(result.result()); + assertEquals(0, result.links().size()); + } +} \ No newline at end of file diff --git a/src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParserTest.java b/src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParserTest.java new file mode 100644 index 000000000..82589a061 --- /dev/null +++ b/src/test/java/org/aksw/iguana/cc/lang/impl/SaxSparqlXmlResultCountingParserTest.java @@ -0,0 +1,142 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; + +import static org.junit.jupiter.api.Assertions.*; + +public class SaxSparqlXmlResultCountingParserTest { + + private final String SELECT_RESULT = """ + + + + + + + + + + + + + + + + r2 + http://work.example.org/bob/ + Bob + 30 + mailto:bob@work.example.org + + + + + """; + + private final String SELECT_RESULT_WITHOUT_LINK = """ + + + + + + + + + + + + + + + r2 + http://work.example.org/bob/ + Bob + 30 + mailto:bob@work.example.org + + + + + """; + + private final String ASK_RESULT = """ + + + + + + + + true + + """; + + private final String ASK_RESULT_WITHOUT_LINK = """ + + + + + + + true + + """; + + @Test + public void testSelectResult() { + final var parser = new SaxSparqlXmlResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(SELECT_RESULT.getBytes()), 0); + final var result = (ResultCountData) data; + assertEquals(1, result.results()); + assertEquals(5, result.bindings()); + assertEquals(6, result.variables().size()); + assertEquals(1, result.links().size()); + assertTrue(result.variables().contains("x")); + assertTrue(result.variables().contains("hpage")); + assertTrue(result.variables().contains("name")); + assertTrue(result.variables().contains("age")); + assertTrue(result.variables().contains("mbox")); + assertTrue(result.variables().contains("friend")); + assertTrue(result.links().contains("http://www.w3.org/TR/rdf-sparql-XMLres")); + } + + @Test + public void testSelectResultWithoutLink() { + final var parser = new SaxSparqlXmlResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(SELECT_RESULT_WITHOUT_LINK.getBytes()), 0); + final var result = (ResultCountData) data; + assertEquals(1, result.results()); + assertEquals(5, result.bindings()); + assertEquals(6, result.variables().size()); + assertTrue(result.variables().contains("x")); + assertTrue(result.variables().contains("hpage")); + assertTrue(result.variables().contains("name")); + assertTrue(result.variables().contains("age")); + assertTrue(result.variables().contains("mbox")); + assertTrue(result.variables().contains("friend")); + assertTrue(result.links().isEmpty()); + } + + @Test + public void testAskResult() { + final var parser = new SaxSparqlXmlResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(ASK_RESULT.getBytes()), 0); + assertInstanceOf(BooleanResultData.class, data); + final var result = (BooleanResultData) data; + assertTrue(result.result()); + assertTrue(result.links().contains("http://www.w3.org/TR/rdf-sparql-XMLres")); + assertEquals(1, result.links().size()); + } + + @Test + public void testAskResultWithoutLink() { + final var parser = new SaxSparqlXmlResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(ASK_RESULT_WITHOUT_LINK.getBytes()), 0); + assertInstanceOf(BooleanResultData.class, data); + final var result = (BooleanResultData) data; + assertTrue(result.result()); + assertTrue(result.links().isEmpty()); + } +} \ No newline at end of file diff --git a/src/test/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParserTest.java b/src/test/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParserTest.java new file mode 100644 index 000000000..5cde83dd8 --- /dev/null +++ b/src/test/java/org/aksw/iguana/cc/lang/impl/SparqlCsvResultCountingParserTest.java @@ -0,0 +1,36 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +public class SparqlCsvResultCountingParserTest { + + private static final String TEST_STRING = """ + x,literal\r + http://example/x,String\r + http://example/x,"String-with-dquote""\"\r + _:b0,Blank node\r + ,Missing 'x'\r + ,\r + http://example/x,\r + _:b1,String-with-lang\r + _:b1,123\r + """; + + @Test + public void test() { + final SparqlCsvResultCountingParser parser = new SparqlCsvResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(TEST_STRING.getBytes()), 0); + assertInstanceOf(ResultCountData.class, data); + final var result = (ResultCountData) data; + assertEquals(8, result.results()); + assertEquals(12, result.bindings()); + assertEquals(2, result.variables().size()); + assertEquals("x", result.variables().get(0)); + assertEquals("literal", result.variables().get(1)); + } +} diff --git a/src/test/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParserTest.java b/src/test/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParserTest.java new file mode 100644 index 000000000..2fcd481a6 --- /dev/null +++ b/src/test/java/org/aksw/iguana/cc/lang/impl/SparqlTsvResultCountingParserTest.java @@ -0,0 +1,35 @@ +package org.aksw.iguana.cc.lang.impl; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; + +import static org.junit.jupiter.api.Assertions.*; + +public class SparqlTsvResultCountingParserTest { + + private static final String TEST_STRING = """ + ?x\t?literal + \t"String" + \t"String-with-dquote\\"" + _:blank0\t"Blank node" + \t"Missing 'x'" + \t + \t + _:blank1\t"String-with-lang"@en + _:blank1\t123 + """; + + @Test + public void test() { + final SparqlTsvResultCountingParser parser = new SparqlTsvResultCountingParser(); + final var data = parser.process(new ByteArrayInputStream(TEST_STRING.getBytes()), 0); + assertInstanceOf(ResultCountData.class, data); + final var result = (ResultCountData) data; + assertEquals(8, result.results()); + assertEquals(12, result.bindings()); + assertEquals(2, result.variables().size()); + assertEquals("?x", result.variables().get(0)); + assertEquals("?literal", result.variables().get(1)); + } +} \ No newline at end of file From 38064d9f451853cd0614f6a3d10128d9348d7db6 Mon Sep 17 00:00:00 2001 From: Nick Molcanov <32801560+nck-mlcnv@users.noreply.github.com> Date: Fri, 13 Sep 2024 16:38:42 +0200 Subject: [PATCH 6/8] Fix issues with queries that are bigger than 2GB (#274, original PR: #266) --- docs/configuration/queries.md | 5 + .../iguana/cc/query/handler/QueryHandler.java | 2 +- .../cc/query/list/impl/InMemQueryList.java | 36 ++++- .../query/source/impl/FolderQuerySource.java | 2 +- .../aksw/iguana/cc/utils/files/FileUtils.java | 146 +++++++++++++----- .../cc/utils/files/IndexedQueryReader.java | 25 +-- .../iguana/cc/utils/files/QueryIndex.java | 4 + .../iguana/cc/utils/http/RequestFactory.java | 110 ++++++++----- .../cc/utils/http/StreamEntityProducer.java | 36 +++-- .../cc/worker/impl/SPARQLProtocolWorker.java | 52 ++----- .../commons/io/BigByteArrayInputStream.java | 104 ++++++++----- .../commons/io/BigByteArrayOutputStream.java | 2 +- .../commons/io/ByteArrayListInputStream.java | 44 +++++- .../aksw/iguana/cc/utils/FileUtilsTest.java | 28 +++- .../worker/impl/SPARQLProtocolWorkerTest.java | 14 +- .../io/ByteArrayListInputStreamTest.java | 13 +- 16 files changed, 402 insertions(+), 221 deletions(-) create mode 100644 src/main/java/org/aksw/iguana/cc/utils/files/QueryIndex.java diff --git a/docs/configuration/queries.md b/docs/configuration/queries.md index 262f1b98c..cef21494b 100644 --- a/docs/configuration/queries.md +++ b/docs/configuration/queries.md @@ -77,6 +77,11 @@ WHERE { ``` The `separator` property should be set to `"\n###\n"`. (be aware of different line endings on different operating systems) +## Huge Query Strings +When working with large queries (Queries that are larger than 2³¹ Bytes or ~2GB), +it is important to consider that only the request types `post query` and `update query` +support large queries. + ## Example ```yaml tasks: diff --git a/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java b/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java index ceea25660..8332d094e 100644 --- a/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java +++ b/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java @@ -178,7 +178,7 @@ public QueryStringWrapper getNextQuery(QuerySelector querySelector) throws IOExc return new QueryStringWrapper(queryIndex, queryList.getQuery(queryIndex)); } - public QueryStreamWrapper getNextQueryStream(QuerySelector querySelector) throws IOException { + public QueryStreamWrapper getNextQueryStream(QuerySelector querySelector) { final var queryIndex = querySelector.getNextIndex(); return new QueryStreamWrapper(queryIndex, config.caching(), () -> { try { diff --git a/src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java b/src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java index 7e6d30a37..e8b5ac086 100644 --- a/src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java +++ b/src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java @@ -2,13 +2,15 @@ import org.aksw.iguana.cc.query.list.QueryList; import org.aksw.iguana.cc.query.source.QuerySource; +import org.aksw.iguana.commons.io.ByteArrayListInputStream; +import org.aksw.iguana.commons.io.ByteArrayListOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; /** @@ -21,21 +23,45 @@ public class InMemQueryList extends QueryList { private static final Logger LOGGER = LoggerFactory.getLogger(InMemQueryList.class); - private final List queries; + private final List queries = new ArrayList<>(); public InMemQueryList(QuerySource querySource) throws IOException { super(querySource); - queries = this.querySource.getAllQueries().stream().map(s -> s.getBytes(StandardCharsets.UTF_8)).toList(); + LOGGER.info("Reading queries from the source with the hash code {} into memory.", querySource.hashCode()); + for (int i = 0; i < querySource.size(); i++) { + try (InputStream queryStream = querySource.getQueryStream(i)) { + ByteArrayListOutputStream balos = new ByteArrayListOutputStream(); + byte[] currentBuffer; + do { + currentBuffer = queryStream.readNBytes(Integer.MAX_VALUE / 2); + balos.write(currentBuffer); + } while (currentBuffer.length == Integer.MAX_VALUE / 2); + balos.close(); + queries.add(balos); + } + } } @Override public String getQuery(int index) { - return new String(this.queries.get(index), StandardCharsets.UTF_8); + final var queryStream = queries.get(index); + if (queryStream.size() > Integer.MAX_VALUE - 8) { + throw new OutOfMemoryError("Query is too large to be read into a string object."); + } + + byte[] buffer; + try { + buffer = queryStream.toInputStream().readNBytes(Integer.MAX_VALUE - 8); + } catch (IOException ignored) { + LOGGER.error("Could not read query into string."); + return ""; + } + return new String(buffer, StandardCharsets.UTF_8); } @Override public InputStream getQueryStream(int index) { - return new ByteArrayInputStream(this.queries.get(index)); + return new ByteArrayListInputStream(queries.get(index).getBuffers()); } @Override diff --git a/src/main/java/org/aksw/iguana/cc/query/source/impl/FolderQuerySource.java b/src/main/java/org/aksw/iguana/cc/query/source/impl/FolderQuerySource.java index be71ccec8..00d4f6734 100644 --- a/src/main/java/org/aksw/iguana/cc/query/source/impl/FolderQuerySource.java +++ b/src/main/java/org/aksw/iguana/cc/query/source/impl/FolderQuerySource.java @@ -74,6 +74,6 @@ public List getAllQueries() throws IOException { @Override public int hashCode() { - return FileUtils.getHashcodeFromFileContent(this.files[0]); + return FileUtils.getHashcodeFromDirectory(this.path); } } diff --git a/src/main/java/org/aksw/iguana/cc/utils/files/FileUtils.java b/src/main/java/org/aksw/iguana/cc/utils/files/FileUtils.java index cea3b542f..e00f30238 100644 --- a/src/main/java/org/aksw/iguana/cc/utils/files/FileUtils.java +++ b/src/main/java/org/aksw/iguana/cc/utils/files/FileUtils.java @@ -1,6 +1,11 @@ package org.aksw.iguana.cc.utils.files; +import net.jpountz.xxhash.StreamingXXHash64; +import net.jpountz.xxhash.XXHashFactory; + import java.io.*; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -14,20 +19,62 @@ * */ public class FileUtils { + private static final XXHashFactory hasherFactory = XXHashFactory.fastestJavaInstance(); + private static final int BUFFER_SIZE = 8192; + /** + * This method calculates the hashcode of the content of a file.
+ * The hashcode is calculated using the XXHash64 algorithm. + * + * @param filepath the path of the file + * @return the hashcode of the file content + */ public static int getHashcodeFromFileContent(Path filepath) { int hashcode; - try { - String fileContents = readFile(filepath); - hashcode = Math.abs(fileContents.hashCode()); + try (StreamingXXHash64 hasher = hasherFactory.newStreamingHash64(0); + InputStream is = new BufferedInputStream(Files.newInputStream(filepath), BUFFER_SIZE)) { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = (is.read(buffer))) != -1) { + hasher.update(buffer, 0, bytesRead); + } + hashcode = (int) hasher.getValue(); } catch (IOException e) { - hashcode = 0; + return 0; } + return hashcode; } - public static String readFile(Path path) throws IOException { - return Files.readString(path, StandardCharsets.UTF_8); + /** + * This method calculated the hashcode of a directory by hashing the content of all files in the directory.
+ * Only top-level files are considered, subdirectories are ignored.
+ * The hashcode is calculated using the XXHash64 algorithm. + * + * @param directory the path of the directory + * @return the hashcode of the directory content + */ + public static int getHashcodeFromDirectory(Path directory) { + + int hashcode; + try (StreamingXXHash64 hasher = hasherFactory.newStreamingHash64(0)) { + for (Path file : Files.list(directory).sorted().toArray(Path[]::new)) { + if (Files.isRegularFile(file)) { + try (InputStream is = new BufferedInputStream(Files.newInputStream(file), BUFFER_SIZE)) { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = (is.read(buffer))) != -1) { + hasher.update(buffer, 0, bytesRead); + } + } + } + } + hashcode = (int) hasher.getValue(); + } catch (IOException e) { + return 0; + } + + return hashcode; } /** @@ -48,16 +95,24 @@ public static String readFile(Path path) throws IOException { public static String getLineEnding(Path filepath) throws IOException { if (filepath == null) throw new IllegalArgumentException("Filepath must not be null."); - try(BufferedReader br = Files.newBufferedReader(filepath)) { + try (BufferedReader br = Files.newBufferedReader(filepath)) { + CharBuffer buffer = CharBuffer.allocate(8192); char c; - while ((c = (char) br.read()) != (char) -1) { - if (c == '\n') - return "\n"; - else if (c == '\r') { - if ((char) br.read() == '\n') - return "\r\n"; - return "\r"; + while (br.read(buffer) != -1) { + buffer.flip(); + while (buffer.hasRemaining()) { + c = buffer.get(); + if (c == '\n') + return "\n"; + else if (c == '\r') { + if (!buffer.hasRemaining() && br.read(buffer) == -1) + return "\r"; + if (buffer.hasRemaining() && buffer.get() == '\n') + return "\r\n"; + return "\r"; + } } + buffer.clear(); } } @@ -84,45 +139,56 @@ private static int[] computePrefixTable(byte[] pattern) { return prefixTable; } - public static List indexStream(String separator, InputStream is) throws IOException { + public static List indexStream(String separator, InputStream is) throws IOException { // basically Knuth-Morris-Pratt - List indices = new ArrayList<>(); + List indices = new ArrayList<>(); final byte[] sepArray = separator.getBytes(StandardCharsets.UTF_8); final int[] prefixTable = computePrefixTable(sepArray); long itemStart = 0; - long byteOffset = 0; int patternIndex = 0; - byte[] currentByte = new byte[1]; - while (is.read(currentByte) == 1) { - // skipping fast-forward with the prefixTable - while (patternIndex > 0 && currentByte[0] != sepArray[patternIndex]) { - patternIndex = prefixTable[patternIndex - 1]; - } - - if (currentByte[0] == sepArray[patternIndex]) { - patternIndex++; - - if (patternIndex == sepArray.length) { // match found - patternIndex = 0; - final long itemEnd = byteOffset - sepArray.length + 1; - final long len = itemEnd - itemStart; - indices.add(new long[]{itemStart, len}); - - itemStart = byteOffset + 1; - } - } - - byteOffset++; - } + // read from the stream in chunks, because the BufferedInputStream is synchronized, so single byte reads are + // slow, which is especially bad for large files + byte[] buffer = new byte[8192]; + ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); + byte currentByte; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + byteBuffer.limit(bytesRead); + while (byteBuffer.hasRemaining()) { + currentByte = byteBuffer.get(); + // skipping fast-forward with the prefixTable + while (patternIndex > 0 && currentByte != sepArray[patternIndex]) { + patternIndex = prefixTable[patternIndex - 1]; + } + + + if (currentByte == sepArray[patternIndex]) { + patternIndex++; + + if (patternIndex == sepArray.length) { // match found + patternIndex = 0; + final long itemEnd = byteOffset - sepArray.length + 1; + final long len = itemEnd - itemStart; + indices.add(new QueryIndex(itemStart, len)); + + itemStart = byteOffset + 1; + } + } + + byteOffset++; + } + byteBuffer.clear(); + + } final long itemEnd = byteOffset; final long len = itemEnd - itemStart; - indices.add(new long[]{itemStart, len}); + indices.add(new QueryIndex(itemStart, len)); return indices; } diff --git a/src/main/java/org/aksw/iguana/cc/utils/files/IndexedQueryReader.java b/src/main/java/org/aksw/iguana/cc/utils/files/IndexedQueryReader.java index 2e9c84f46..ed0206de3 100644 --- a/src/main/java/org/aksw/iguana/cc/utils/files/IndexedQueryReader.java +++ b/src/main/java/org/aksw/iguana/cc/utils/files/IndexedQueryReader.java @@ -27,7 +27,7 @@ public class IndexedQueryReader { /** * This list stores the start position and the length of each indexed content. */ - private final List indices; + private final List indices; /** * The file whose content should be indexed. @@ -96,12 +96,19 @@ private IndexedQueryReader(Path filepath, String separator) throws IOException { * @throws IOException */ public String readQuery(int index) throws IOException { + final int size; + try { + size = Math.toIntExact(indices.get(index).queryLength()); + } catch (Exception e) { + throw new OutOfMemoryError("Can't read a Query to a string, that's bigger than 2^31 Bytes (~2GB)"); + } // Indexed queries can't be larger than ~2GB try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) { - final ByteBuffer buffer = ByteBuffer.allocate((int) indices.get(index)[1]); - final var read = channel.read(buffer, indices.get(index)[0]); - assert read == indices.get(index)[1]; - return new String(buffer.array(), StandardCharsets.UTF_8); + final byte[] buffer = new byte[size]; // it's supposedly faster to manually create a byte array than a ByteBuffer + final ByteBuffer bufferWrapper = ByteBuffer.wrap(buffer); + final var read = channel.read(bufferWrapper, indices.get(index).filePosition()); + assert read == indices.get(index).queryLength(); + return new String(buffer, StandardCharsets.UTF_8); } } @@ -111,8 +118,8 @@ public InputStream streamQuery(int index) throws IOException { new BoundedInputStream( Channels.newInputStream( FileChannel.open(path, StandardOpenOption.READ) - .position(this.indices.get(index)[0] /* offset */)), - this.indices.get(index)[1] /* length */))); + .position(this.indices.get(index).filePosition() /* offset */)), + this.indices.get(index).queryLength() /* length */))); } /** @@ -146,11 +153,11 @@ public int size() { * @return the Indexes * @throws IOException */ - private static List indexFile(Path filepath, String separator) throws IOException { + private static List indexFile(Path filepath, String separator) throws IOException { try (InputStream fi = Files.newInputStream(filepath, StandardOpenOption.READ); BufferedInputStream bis = new BufferedInputStream(fi)) { return FileUtils.indexStream(separator, bis) - .stream().filter((long[] e) -> e[1] > 0 /* Only elements with length > 0 */).collect(Collectors.toList()); + .stream().filter(e -> e.queryLength() > 0 /* Only elements with length > 0 */).collect(Collectors.toList()); } } } diff --git a/src/main/java/org/aksw/iguana/cc/utils/files/QueryIndex.java b/src/main/java/org/aksw/iguana/cc/utils/files/QueryIndex.java new file mode 100644 index 000000000..40968e386 --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/utils/files/QueryIndex.java @@ -0,0 +1,4 @@ +package org.aksw.iguana.cc.utils.files; + +public record QueryIndex(long filePosition, long queryLength) { +} diff --git a/src/main/java/org/aksw/iguana/cc/utils/http/RequestFactory.java b/src/main/java/org/aksw/iguana/cc/utils/http/RequestFactory.java index 6966f87f4..e29fc5331 100644 --- a/src/main/java/org/aksw/iguana/cc/utils/http/RequestFactory.java +++ b/src/main/java/org/aksw/iguana/cc/utils/http/RequestFactory.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import org.aksw.iguana.cc.config.elements.ConnectionConfig; import org.aksw.iguana.cc.query.handler.QueryHandler; +import org.aksw.iguana.cc.query.selector.impl.LinearQuerySelector; import org.aksw.iguana.cc.worker.HttpWorker; import org.aksw.iguana.cc.worker.impl.SPARQLProtocolWorker; import org.apache.hc.core5.http.HttpHeaders; @@ -11,6 +12,8 @@ import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer; import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder; import org.apache.hc.core5.net.URIBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; @@ -26,7 +29,7 @@ * The factory can create requests for different types of HTTP methods and different types of SPARQL queries. * The factory can also cache requests to avoid creating the same request multiple times. */ -public final class RequestFactory { +public class RequestFactory { public enum RequestType { GET_QUERY("get query"), POST_URL_ENC_QUERY("post url-enc query"), @@ -47,11 +50,25 @@ public String value() { } } + Logger LOGGER = LoggerFactory.getLogger(RequestFactory.class); + + private final ConnectionConfig connectionConfig; + private final String acceptHeader; private final RequestType requestType; + private final boolean caching; private final Map cache = new HashMap<>(); - public RequestFactory(RequestType requestType) { - this.requestType = requestType; + + /** + * Creates a new request factory for the given worker configuration. + * + * @param workerConfig the worker configuration + */ + public RequestFactory(SPARQLProtocolWorker.Config workerConfig) { + this.connectionConfig = workerConfig.connection(); + this.acceptHeader = workerConfig.acceptHeader(); + this.requestType = workerConfig.requestType(); + this.caching = workerConfig.queries().getConfig().caching(); } private static String urlEncode(List parameters) { @@ -66,24 +83,24 @@ private static String urlEncode(String name, String value) { /** * Builds an HTTP request for a given query. - * If the query has been cached by the query handler, its content will be fully read by the entity producer into a - * byte buffer, which will then be reused on consecutive request executions. - * Cached requests will be sent non-chunked. + * The request is built according to the request type and the query type that was set in the constructor. + * If the query is cached, the cached data will be used to build the request. + * Cached requests will also be sent non-chunked. * If the query has not been cached by the query handler, the entity producer will use the query stream supplier to * send the query in chunks. + * All Requests will also be cached, and they will not be rebuilt if they are requested again. * - * @param queryHandle the query handle containing the query and its index - * @param connection the connection to send the request to - * @param requestHeader the request header + * @param queryHandle the query handle to build the request for * @return the request as an AsyncRequestProducer * @throws URISyntaxException if the URI is invalid * @throws IOException if the query stream cannot be read */ - public AsyncRequestProducer buildHttpRequest(QueryHandler.QueryStreamWrapper queryHandle, - ConnectionConfig connection, - String requestHeader) throws URISyntaxException, IOException { - if (queryHandle.cached() && cache.containsKey(queryHandle.index())) - return cache.get(queryHandle.index()); + public AsyncRequestProducer buildHttpRequest(QueryHandler.QueryStreamWrapper queryHandle) throws IOException, URISyntaxException { + final var index = queryHandle.index(); + + // get cached request + if (caching && cache.containsKey(index)) + return cache.get(index); AsyncRequestBuilder asyncRequestBuilder; Supplier queryStreamSupplier; @@ -91,54 +108,65 @@ public AsyncRequestProducer buildHttpRequest(QueryHandler.QueryStreamWrapper que try { queryStreamSupplier = queryHandle.queryInputStreamSupplier(); - queryStream = queryStreamSupplier.get(); + queryStream = queryStreamSupplier.get(); // the queryStreamSupplier may throw an RuntimeException } catch (RuntimeException e) { throw new IOException(e); } - switch (this.requestType) { - case GET_QUERY -> asyncRequestBuilder = AsyncRequestBuilder.get(new URIBuilder(connection.endpoint()) + // If the query is bigger than 2^31 bytes (2GB) and the request type is set to GET_QUERY, POST_URL_ENC_QUERY or + // POST_URL_ENC_UPDATE, the following code will throw an exception. + switch (requestType) { + case GET_QUERY -> asyncRequestBuilder = AsyncRequestBuilder.get(new URIBuilder(connectionConfig.endpoint()) .addParameter("query", new String(queryStream.readAllBytes(), StandardCharsets.UTF_8)) .build() ); - case POST_URL_ENC_QUERY -> asyncRequestBuilder = AsyncRequestBuilder.post(connection.endpoint()) + case POST_URL_ENC_QUERY -> asyncRequestBuilder = AsyncRequestBuilder.post(connectionConfig.endpoint()) // manually set content type, because otherwise the // entity producer would set it to "application/x-www-form-urlencoded; charset=ISO-8859-1" .setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") - .setEntity(new BasicAsyncEntityProducer(urlEncode("query", new String(queryStream.readAllBytes(), StandardCharsets.UTF_8)), null, !queryHandle.cached())); - case POST_QUERY -> asyncRequestBuilder = AsyncRequestBuilder.post(connection.endpoint()) - .setEntity(new StreamEntityProducer(queryStreamSupplier, !queryHandle.cached(), "application/sparql-query")); - case POST_URL_ENC_UPDATE -> asyncRequestBuilder = AsyncRequestBuilder.post(connection.endpoint()) + .setEntity(new BasicAsyncEntityProducer(urlEncode("query", new String(queryStream.readAllBytes(), StandardCharsets.UTF_8)), null, false)); + case POST_QUERY -> asyncRequestBuilder = AsyncRequestBuilder.post(connectionConfig.endpoint()) + .setEntity(new StreamEntityProducer(queryStreamSupplier, !caching, "application/sparql-query")); + case POST_URL_ENC_UPDATE -> asyncRequestBuilder = AsyncRequestBuilder.post(connectionConfig.endpoint()) .setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") - .setEntity(new BasicAsyncEntityProducer(urlEncode("update", new String(queryStream.readAllBytes(), StandardCharsets.UTF_8)), null, !queryHandle.cached())); - case POST_UPDATE -> asyncRequestBuilder = AsyncRequestBuilder.post(connection.endpoint()) - .setEntity(new StreamEntityProducer(queryStreamSupplier, !queryHandle.cached(), "application/sparql-update")); - default -> throw new IllegalStateException("Unexpected value: " + this.requestType); + .setEntity(new BasicAsyncEntityProducer(urlEncode("update", new String(queryStream.readAllBytes(), StandardCharsets.UTF_8)), null, false)); + case POST_UPDATE -> asyncRequestBuilder = AsyncRequestBuilder.post(connectionConfig.endpoint()) + .setEntity(new StreamEntityProducer(queryStreamSupplier, !caching, "application/sparql-update")); + default -> throw new IllegalStateException("Unexpected value: " + requestType); } - if (requestHeader != null) - asyncRequestBuilder.addHeader("Accept", requestHeader); - if (connection.authentication() != null && connection.authentication().user() != null) + // set additional headers + if (acceptHeader != null) + asyncRequestBuilder.addHeader("Accept", acceptHeader); + if (connectionConfig.authentication() != null && connectionConfig.authentication().user() != null) asyncRequestBuilder.addHeader("Authorization", - HttpWorker.basicAuth(connection.authentication().user(), - Optional.ofNullable(connection.authentication().password()).orElse(""))); + HttpWorker.basicAuth(connectionConfig.authentication().user(), + Optional.ofNullable(connectionConfig.authentication().password()).orElse(""))); - if (queryHandle.cached()) - cache.put(queryHandle.index(), asyncRequestBuilder.build()); + // cache request + if (caching) + cache.put(index, asyncRequestBuilder.build()); return asyncRequestBuilder.build(); } /** - * Get a cached request by the index of the query. - * If the request is not in the cache, an IllegalArgumentException is thrown. + * Builds every request once, so that the requests can be loaded into the cache, if the queries themselves are + * cached. + * This is done to avoid the overhead of building (url-encoding) the requests during the benchmark. * - * @param index the index of the query - * @return the request as an AsyncRequestProducer + * @param queryHandler the query handler to preload requests for */ - public AsyncRequestProducer getCachedRequest(int index) { - if (!cache.containsKey(index)) - throw new IllegalArgumentException("No request with index " + index + " found in cache."); - return cache.get(index); + public void preloadRequests(QueryHandler queryHandler) { + final var selector = new LinearQuerySelector(queryHandler.getQueryCount()); + for (int i = 0; i < queryHandler.getQueryCount(); i++) { + try { + // build request and discard it + buildHttpRequest(queryHandler.getNextQueryStream(selector)); + } catch (IOException | URISyntaxException e) { + LOGGER.error("Failed to preload request.", e); + } + } + } } diff --git a/src/main/java/org/aksw/iguana/cc/utils/http/StreamEntityProducer.java b/src/main/java/org/aksw/iguana/cc/utils/http/StreamEntityProducer.java index f05c1c191..5996d2b9e 100644 --- a/src/main/java/org/aksw/iguana/cc/utils/http/StreamEntityProducer.java +++ b/src/main/java/org/aksw/iguana/cc/utils/http/StreamEntityProducer.java @@ -1,5 +1,6 @@ package org.aksw.iguana.cc.utils.http; +import org.aksw.iguana.commons.io.ByteArrayListInputStream; import org.apache.hc.core5.http.nio.AsyncEntityProducer; import org.apache.hc.core5.http.nio.DataStreamChannel; import org.slf4j.Logger; @@ -14,7 +15,8 @@ /** * An entity producer that produces the entity data from an input stream supplier. * The entity data can optionally be sent in chunks. - * If the entity data is supposed to be sent non-chunked, the whole stream will be read into a byte buffer. + * If the entity data is supposed to be sent non-chunked, + * it is assumed that the query is stored in a ByteArrayListInputStream. * The stream supplier should be repeatable, as this producer might be reused multiple times to create the entity data. */ public class StreamEntityProducer implements AsyncEntityProducer { @@ -25,12 +27,11 @@ public class StreamEntityProducer implements AsyncEntityProducer { private final boolean chunked; private final String contentType; - private ByteBuffer content; // used for non-chunked request, stores the whole content in reusable buffer - private final static int BUFFER_SIZE = 8192; private final byte[] buffer = new byte[BUFFER_SIZE]; - private InputStream currentStream; // used for chunked request, stores the current stream to read from + private InputStream currentStream; + private ByteArrayListInputStream content; /** * Creates a new entity producer that produces the entity data from the given input stream supplier. @@ -42,9 +43,8 @@ public StreamEntityProducer(Supplier streamSupplier, boolean chunke this.streamSupplier = streamSupplier; this.chunked = chunked; this.contentType = contentType; - if (!chunked) { - content = ByteBuffer.wrap(streamSupplier.get().readAllBytes()); + content = (streamSupplier.get() instanceof ByteArrayListInputStream) ? (ByteArrayListInputStream) streamSupplier.get() : null; } } @@ -77,9 +77,9 @@ public Set getTrailerNames() { @Override public long getContentLength() { - // if the content length is known (non-chunked request), return it + // if the content length is known (non-chunked request), return the length if (content != null) { - return content.limit(); + return content.availableLong(); } // if the content length is unknown (chunked request), return -1 @@ -99,7 +99,7 @@ public String getContentEncoding() { @Override public void releaseResources() { if (content != null) { - content.clear(); + content = null; } if (currentStream != null) { @@ -113,11 +113,8 @@ public void releaseResources() { @Override public int available() { - // If content is not null, it means the whole entity data has been read into the buffer from a stream that was - // taken from the stream supplier and that the content will be sent non-chunked. - // In this case, the remaining bytes in the buffer are returned. if (content != null) { - return content.remaining(); + return content.available(); } // Otherwise, the data is sent in chunks. If there is currently a stream open, from which the data is being read @@ -136,9 +133,16 @@ public int available() { public void produce(DataStreamChannel channel) throws IOException { // handling of non-chunked request if (content != null) { - channel.write(content); - if (!content.hasRemaining()) { - channel.endStream(); + ByteBuffer buffer = content.getCurrentBuffer(); + while (channel.write(buffer) > 0) { + if (!buffer.hasRemaining()) { + buffer = content.getCurrentBuffer(); + } + if (buffer == null) { + // no more data to send + channel.endStream(); + break; + } } return; } diff --git a/src/main/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorker.java b/src/main/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorker.java index 7745ddb96..565763f68 100644 --- a/src/main/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorker.java +++ b/src/main/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorker.java @@ -5,7 +5,6 @@ import net.jpountz.xxhash.XXHashFactory; import org.aksw.iguana.cc.config.elements.ConnectionConfig; import org.aksw.iguana.cc.query.handler.QueryHandler; -import org.aksw.iguana.cc.query.selector.impl.LinearQuerySelector; import org.aksw.iguana.cc.utils.http.RequestFactory; import org.aksw.iguana.cc.worker.ResponseBodyProcessor; import org.aksw.iguana.cc.worker.HttpWorker; @@ -115,7 +114,7 @@ public SPARQLProtocolWorker(long workerId, ResponseBodyProcessor responseBodyPro super(workerId, responseBodyProcessor, config); this.responseBodyProcessor = responseBodyProcessor; this.executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1); - this.requestFactory = new RequestFactory(config().requestType()); + this.requestFactory = new RequestFactory(this.config()); } /** @@ -157,22 +156,6 @@ public static void closeHttpClient() { } } - /** - * Builds every request once, so that the requests can be loaded into the cache, if the queries themselves are - * cached. - * This is done to avoid the overhead of building (url-encoding) the requests during the benchmark. - */ - private void preloadRequests() { - final var selector = new LinearQuerySelector(config().queries().getQueryCount()); - for (int i = 0; i < config().queries().getQueryCount(); i++) { - try { - // build request and discard it - requestFactory.buildHttpRequest(config().queries().getNextQueryStream(selector), config().connection(), config().acceptHeader()); - } catch (IOException | URISyntaxException e) { - LOGGER.error("Failed to preload request.", e); - } - } - } /** * Starts the worker and returns a CompletableFuture, which will be completed, when the worker has finished the @@ -185,7 +168,7 @@ private void preloadRequests() { * @return the CompletableFuture the contains the results of the worker. */ public CompletableFuture start() { - preloadRequests(); + requestFactory.preloadRequests(config().queries()); return CompletableFuture.supplyAsync(() -> { ZonedDateTime startTime = ZonedDateTime.now(); List executionStats = new ArrayList<>(); @@ -280,31 +263,14 @@ private ExecutionStats executeQuery(Duration timeout, boolean discardOnFailure) */ private HttpExecutionResult executeHttpRequest(Duration timeout) { // get the next query and request - final AsyncRequestProducer request; - final int queryIndex; - if (config().queries().getConfig().caching()) { - queryIndex = querySelector.getNextIndex(); - request = requestFactory.getCachedRequest(queryIndex); - } else { - final QueryHandler.QueryStreamWrapper queryHandle; - try { - queryHandle = config().queries().getNextQueryStream(this.querySelector); - } catch (IOException e) { - return createFailedResultBeforeRequest(this.querySelector.getCurrentIndex(), e); - } - - try { - request = requestFactory.buildHttpRequest( - queryHandle, - config().connection(), - config().acceptHeader() - ); - } catch (IOException | URISyntaxException e) { - return createFailedResultBeforeRequest(queryHandle.index(), e); - } + final var queryHandle = config().queries().getNextQueryStream(querySelector); + final int queryIndex = queryHandle.index(); - // set queryIndex to the index of the queryHandle, so that the result can be associated with the query - queryIndex = queryHandle.index(); + final AsyncRequestProducer request; + try { + request = requestFactory.buildHttpRequest(queryHandle); + } catch (IOException | URISyntaxException e) { + return createFailedResultBeforeRequest(config.queries().getQuerySelectorInstance().getCurrentIndex(), e); } // execute the request diff --git a/src/main/java/org/aksw/iguana/commons/io/BigByteArrayInputStream.java b/src/main/java/org/aksw/iguana/commons/io/BigByteArrayInputStream.java index 1559fd7f1..f6c124162 100644 --- a/src/main/java/org/aksw/iguana/commons/io/BigByteArrayInputStream.java +++ b/src/main/java/org/aksw/iguana/commons/io/BigByteArrayInputStream.java @@ -2,20 +2,28 @@ import java.io.IOException; import java.io.InputStream; +import java.nio.ByteBuffer; import java.util.Objects; import static java.lang.Math.min; public class BigByteArrayInputStream extends InputStream { + private final static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; + final private BigByteArrayOutputStream bbaos; - private byte[] currentBuffer; - private int currentBufferSize = -1; - private int posInCurrentBuffer = 0; + private ByteBuffer currentBuffer; private boolean ended = true; + /** + * Creates a new BigByteArrayInputStream. + * The given byte array will be copied to the internal buffers. + * + * @param bytes the byte array to read from + * @throws IOException if an I/O error occurs + */ public BigByteArrayInputStream(byte[] bytes) throws IOException { bbaos = new BigByteArrayOutputStream(); bbaos.write(bytes); @@ -38,10 +46,10 @@ public int read() throws IOException { this.bbaos.close(); if (ended) return -1; - final var ret = currentBuffer[posInCurrentBuffer++]; - if (availableBytes() == 0) - activateNextBuffer(); - return ret & 0xFF; // convert byte (-128...127) to (0...255) + if (currentBuffer.remaining() == 0 && !activateNextBuffer()) + return -1; + + return currentBuffer.get() & 0xFF; // convert byte (-128...127) to (0...255) } @Override @@ -51,28 +59,35 @@ public int read(byte[] b, int off, int len) throws IOException { if (ended) return -1; - final var copyLength1 = min(availableBytes(), len); - System.arraycopy(currentBuffer, posInCurrentBuffer, b, off, copyLength1); - posInCurrentBuffer += copyLength1; + final var copyLength1 = min(currentBuffer.remaining(), len); + currentBuffer.get(b, off, copyLength1); off += copyLength1; - if (availableBytes() == 0) + if (currentBuffer.remaining() == 0) activateNextBuffer(); // check if b is already filled up or if there is nothing left to read if (copyLength1 == len || ended) return copyLength1; - // there might be the rare case, where reading one additional baos might not be enough to fill the buffer, - // because there are different array size limitations across different JVMs - final var copyLength2 = min(availableBytes(), len - copyLength1); - System.arraycopy(currentBuffer, posInCurrentBuffer, b, off, copyLength2); - posInCurrentBuffer += copyLength2; + // read again if there is still something to read + final var copyLength2 = min(currentBuffer.remaining(), len - copyLength1); + currentBuffer.get(b, off, copyLength2); - if (availableBytes() == 0) + if (currentBuffer.remaining() == 0) activateNextBuffer(); return copyLength1 + copyLength2; } + @Override + public byte[] readNBytes(int n) throws IOException { + if (n < 0) throw new IllegalArgumentException("n must be non-negative"); + if (currentBuffer == null && !activateNextBuffer()) return new byte[0]; + int read = Math.min(n, available()); + byte[] b = new byte[read]; + readNBytes(b, 0, read); + return b; + } + @Override public int readNBytes(byte[] b, int off, int len) throws IOException { this.bbaos.close(); @@ -80,23 +95,20 @@ public int readNBytes(byte[] b, int off, int len) throws IOException { if (ended) return 0; - final var copyLength1 = min(availableBytes(), len); - System.arraycopy(currentBuffer, posInCurrentBuffer, b, off, copyLength1); - posInCurrentBuffer += copyLength1; + final var copyLength1 = min(currentBuffer.remaining(), len); + currentBuffer.get(b, off, copyLength1); off += copyLength1; - if (availableBytes() == 0) + if (currentBuffer.remaining() == 0) activateNextBuffer(); // check if b is already filled up or if there is nothing left to read if (copyLength1 == len || ended) return copyLength1; - // there might be the rare case, where reading one additional baos might not be enough to fill the buffer, - // because there are different array size limitations across different JVMs - final var copyLength2 = min(availableBytes(), len - copyLength1); - System.arraycopy(currentBuffer, posInCurrentBuffer, b, off, copyLength2); - posInCurrentBuffer += copyLength2; + // read again if there is still something to read + final var copyLength2 = min(currentBuffer.remaining(), len - copyLength1); + currentBuffer.get(b, off, copyLength2); - if (availableBytes() == 0) + if (currentBuffer.remaining() == 0) activateNextBuffer(); return copyLength1 + copyLength2; @@ -104,18 +116,24 @@ public int readNBytes(byte[] b, int off, int len) throws IOException { @Override public byte[] readAllBytes() throws IOException { - throw new IOException("Reading all bytes from a BigByteArrayInputStream is prohibited because it might exceed the array capacity"); + if (currentBuffer == null && !activateNextBuffer()) return new byte[0]; + if (availableLong() > MAX_BUFFER_SIZE) + throw new IOException("Reading all bytes from a BigByteArrayInputStream is prohibited because it might exceed the array capacity"); + byte[] b = new byte[available()]; + readNBytes(b, 0, b.length); + return b; } @Override public long skip(long n) throws IOException { if (n <= 0) return 0; + if (currentBuffer == null && !activateNextBuffer()) return 0; long skipped = 0; while (skipped < n) { - long thisSkip = min(availableBytes(), n - skipped); + int thisSkip = (int) min(currentBuffer.remaining(), n - skipped); // conversion to int is lossless, because skipped is at maximum INT_MAX big skipped += thisSkip; - posInCurrentBuffer += (int) thisSkip; // conversion to int is lossless, because skipped is at maximum INT_MAX big - if (availableBytes() == 0) + currentBuffer.position(currentBuffer.position() + thisSkip); + if (currentBuffer.remaining() == 0) if (!activateNextBuffer()) return skipped; } @@ -131,33 +149,35 @@ private boolean activateNextBuffer() { // check if another buffer is available if (bbaos.getBaos().isEmpty()) { currentBuffer = null; // release memory - currentBufferSize = 0; - posInCurrentBuffer = 0; ended = true; return false; } // activate next buffer - currentBuffer = bbaos.getBaos().get(0).getBuffer(); - currentBufferSize = bbaos.getBaos().get(0).size(); - posInCurrentBuffer = 0; + currentBuffer = ByteBuffer.wrap(bbaos.getBaos().get(0).getBuffer()); + currentBuffer.limit(bbaos.getBaos().get(0).size()); // set limit to the actual size of the buffer // remove the current buffer from the list to save memory bbaos.getBaos().remove(0); // check if the new buffer contains anything - if (currentBuffer.length == 0) - return ended = activateNextBuffer(); + if (currentBuffer.remaining() == 0) + return ended = !activateNextBuffer(); ended = false; return true; } + @Override + public int available() { + return (int) Math.min(availableLong(), MAX_BUFFER_SIZE); + } + /** - * Returns the number of available bytes in the current buffer. + * Returns the number of bytes available in the stream as long type. * - * @return the number of available bytes in the current buffer + * @return the number of bytes available in the stream */ - private int availableBytes() { - return currentBufferSize - posInCurrentBuffer; + public long availableLong() { + return bbaos.size() + currentBuffer.remaining(); } } diff --git a/src/main/java/org/aksw/iguana/commons/io/BigByteArrayOutputStream.java b/src/main/java/org/aksw/iguana/commons/io/BigByteArrayOutputStream.java index 02ee4f446..633fae2b9 100644 --- a/src/main/java/org/aksw/iguana/commons/io/BigByteArrayOutputStream.java +++ b/src/main/java/org/aksw/iguana/commons/io/BigByteArrayOutputStream.java @@ -207,4 +207,4 @@ public void close() throws IOException { public InputStream toInputStream() { return new BigByteArrayInputStream(this); } -} \ No newline at end of file +} diff --git a/src/main/java/org/aksw/iguana/commons/io/ByteArrayListInputStream.java b/src/main/java/org/aksw/iguana/commons/io/ByteArrayListInputStream.java index 813e77161..627385ba4 100644 --- a/src/main/java/org/aksw/iguana/commons/io/ByteArrayListInputStream.java +++ b/src/main/java/org/aksw/iguana/commons/io/ByteArrayListInputStream.java @@ -13,6 +13,8 @@ */ public class ByteArrayListInputStream extends InputStream { + private final static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; + private final List data; private Iterator iterator; private ByteBuffer currentBuffer; @@ -86,7 +88,11 @@ public int read(byte[] b, int off, int len) throws IOException { @Override public byte[] readAllBytes() throws IOException { - throw new UnsupportedOperationException(); + checkNotClosed(); + if (availableLong() > MAX_BUFFER_SIZE) { + throw new OutOfMemoryError("Data is too large to be read into a byte array"); + } + return readNBytes(MAX_BUFFER_SIZE); } @Override @@ -95,6 +101,18 @@ public int readNBytes(byte[] b, int off, int len) throws IOException { return read(b, off, len, 0); } + @Override + public byte[] readNBytes(int len) throws IOException { + checkNotClosed(); + if (len < 0) { + throw new IllegalArgumentException("len < 0"); + } + final var actualLength = Math.min(len, this.available()); + byte[] b = new byte[actualLength]; + read(b, 0, actualLength, 0); + return b; + } + @Override public long skip(long n) throws IOException { checkNotClosed(); @@ -125,12 +143,16 @@ public void skipNBytes(long n) throws IOException { } @Override - public int available() throws IOException { - return (int) Math.min(Integer.MAX_VALUE, availableLong()); + public int available() { + return (int) Math.min(MAX_BUFFER_SIZE, availableLong()); } - public long availableLong() throws IOException { - checkNotClosed(); + /** + * Returns the number of bytes available to read from the stream. + * + * @return the number of bytes available + */ + public long availableLong() { if (!checkBuffer()) return 0; long sum = 0; @@ -160,4 +182,16 @@ public int read() throws IOException { return -1; return currentBuffer.get() & 0xFF; } + + /** + * Returns the current buffer that is being read from. + * + * @return the current buffer + */ + public ByteBuffer getCurrentBuffer() { + if (!checkBuffer()) { + return null; + } + return currentBuffer; + } } diff --git a/src/test/java/org/aksw/iguana/cc/utils/FileUtilsTest.java b/src/test/java/org/aksw/iguana/cc/utils/FileUtilsTest.java index b18d52704..7137ce9c2 100644 --- a/src/test/java/org/aksw/iguana/cc/utils/FileUtilsTest.java +++ b/src/test/java/org/aksw/iguana/cc/utils/FileUtilsTest.java @@ -1,6 +1,8 @@ package org.aksw.iguana.cc.utils; +import net.jpountz.xxhash.XXHashFactory; import org.aksw.iguana.cc.utils.files.FileUtils; +import org.aksw.iguana.cc.utils.files.QueryIndex; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -8,6 +10,7 @@ import java.io.*; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; @@ -65,22 +68,39 @@ public static Collection data() { @ParameterizedTest @MethodSource("data") public void testIndexingStrings(IndexTestData data) throws IOException { - List index = FileUtils.indexStream(data.separator, new ByteArrayInputStream(data.content.getBytes())); + List index = FileUtils.indexStream(data.separator, new ByteArrayInputStream(data.content.getBytes())); assertEquals(data.indices.size(), index.size()); for (int i = 0; i < index.size(); i++) { - assertArrayEquals(data.indices.get(i), index.get(i)); + assertEquals(data.indices.get(i)[0], index.get(i).filePosition()); + assertEquals(data.indices.get(i)[1], index.get(i).queryLength()); } } @Test public void getHashTest() throws IOException { + final var hasherFactory = XXHashFactory.fastestJavaInstance(); for (int i = 0; i < 10; i++) { String content = UUID.randomUUID().toString(); final var file = createTestFileWithContent(content); - final int expected = Math.abs(content.hashCode()); + final var data = content.getBytes(StandardCharsets.UTF_8); + final var hasher = hasherFactory.hash64(); + final int expected = (int) hasher.hash(data, 0, data.length, 0); + final int actual = FileUtils.getHashcodeFromFileContent(file); - assertTrue(actual >= 0); assertEquals(expected, actual); + + final int actual2 = FileUtils.getHashcodeFromFileContent(file); + assertEquals(expected, actual2); + } + + final var directory = Files.createTempDirectory("getHashTest"); + for (int i = 0; i < 10; i++) { + final var file = createTestFileWithContent(UUID.randomUUID().toString()); + Files.move(file, directory.resolve(file.getFileName())); } + final int actual = FileUtils.getHashcodeFromDirectory(directory); + final int actual2 = FileUtils.getHashcodeFromDirectory(directory); + assertEquals(actual, actual2); + org.apache.commons.io.FileUtils.deleteDirectory(directory.toFile()); } } diff --git a/src/test/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorkerTest.java b/src/test/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorkerTest.java index f7955b947..b7d4daf71 100644 --- a/src/test/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorkerTest.java +++ b/src/test/java/org/aksw/iguana/cc/worker/impl/SPARQLProtocolWorkerTest.java @@ -12,6 +12,7 @@ import org.aksw.iguana.cc.utils.http.RequestFactory; import org.aksw.iguana.cc.worker.HttpWorker; import org.aksw.iguana.cc.worker.ResponseBodyProcessor; +import org.apache.commons.lang3.function.TriFunction; import org.junit.jupiter.api.*; import org.junit.jupiter.api.condition.DisabledInNativeImage; import org.junit.jupiter.api.extension.RegisterExtension; @@ -34,7 +35,6 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; -import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; @@ -140,8 +140,8 @@ public static List completionTargets() { @MethodSource("requestFactoryData") @DisplayName("Test Request Factory") public void testRequestFactory(SPARQLProtocolWorker worker, boolean cached) { - BiFunction encoding = (builder, size) -> { - if (!cached) { + TriFunction encoding = (builder, size, chunked) -> { + if (chunked) { return builder.withHeader("Transfer-Encoding", equalTo("chunked")); } else { return builder.withHeader("Content-Length", equalTo(String.valueOf(size))); @@ -161,7 +161,7 @@ public void testRequestFactory(SPARQLProtocolWorker worker, boolean cached) { .withBasicAuth("testUser", "password") .withRequestBody(equalTo(QUERY)) .willReturn(aResponse().withStatus(200).withBody("Non-Empty-Body")); - encoding.apply(temp, QUERY.length()); + encoding.apply(temp, QUERY.length(), !cached); wm.stubFor(temp); } case POST_UPDATE -> { @@ -170,7 +170,7 @@ public void testRequestFactory(SPARQLProtocolWorker worker, boolean cached) { .withBasicAuth("testUser", "password") .withRequestBody(equalTo(QUERY)) .willReturn(aResponse().withStatus(200).withBody("Non-Empty-Body")); - encoding.apply(temp, QUERY.length()); + encoding.apply(temp, QUERY.length(), !cached); wm.stubFor(temp); } @@ -180,7 +180,7 @@ public void testRequestFactory(SPARQLProtocolWorker worker, boolean cached) { .withBasicAuth("testUser", "password") .withRequestBody(equalTo("query=" + URLEncoder.encode(QUERY, StandardCharsets.UTF_8))) .willReturn(aResponse().withStatus(200).withBody("Non-Empty-Body")); - encoding.apply(temp, 43); + encoding.apply(temp, 43, false); wm.stubFor(temp); } case POST_URL_ENC_UPDATE -> { @@ -189,7 +189,7 @@ public void testRequestFactory(SPARQLProtocolWorker worker, boolean cached) { .withBasicAuth("testUser", "password") .withRequestBody(equalTo("update=" + URLEncoder.encode(QUERY, StandardCharsets.UTF_8))) .willReturn(aResponse().withStatus(200).withBody("Non-Empty-Body")); - encoding.apply(temp, 44); + encoding.apply(temp, 44, false); wm.stubFor(temp); } } diff --git a/src/test/java/org/aksw/iguana/commons/io/ByteArrayListInputStreamTest.java b/src/test/java/org/aksw/iguana/commons/io/ByteArrayListInputStreamTest.java index bf841d0db..b5c675c73 100644 --- a/src/test/java/org/aksw/iguana/commons/io/ByteArrayListInputStreamTest.java +++ b/src/test/java/org/aksw/iguana/commons/io/ByteArrayListInputStreamTest.java @@ -41,11 +41,12 @@ void testReadSingle() throws IOException { @Test void testReadAllBytes() throws IOException { - final var data = createByteArrayListInputStream(BUFFER_SIZE, NUM_BUFFERS); + final var data = createByteArrayListInputStream(Integer.MAX_VALUE / 2, 2); final var stream = new ByteArrayListInputStream(data); - assertEquals(BUFFER_SIZE * NUM_BUFFERS, stream.availableLong()); - assertThrows(UnsupportedOperationException.class, stream::readAllBytes); - assertEquals(BUFFER_SIZE * NUM_BUFFERS, stream.availableLong()); + // there is actually a byte missing because Integer.MAX_VALUE is uneven + assertEquals(Integer.MAX_VALUE - 1, stream.availableLong()); + assertThrows(OutOfMemoryError.class, stream::readAllBytes); // should only throw if the stream is too large + assertEquals(Integer.MAX_VALUE - 1, stream.availableLong()); } @Test @@ -157,7 +158,7 @@ void testClose() { assertThrows(IOException.class, () -> stream.readNBytes(buffer, 0, BUFFER_SIZE * NUM_BUFFERS)); assertThrows(IOException.class, () -> stream.skip(1)); assertThrows(IOException.class, () -> stream.skipNBytes(1)); - assertThrows(IOException.class, stream::availableLong); + // assertThrows(IOException.class, stream::availableLong); is actually not required } @@ -169,6 +170,6 @@ void testAvailableLong() throws IOException { combined.addAll(data2); final var stream = new ByteArrayListInputStream(combined); assertEquals(Integer.MAX_VALUE - 8 + (long) BUFFER_SIZE, stream.availableLong()); - assertEquals(Integer.MAX_VALUE, stream.available()); + assertEquals(Integer.MAX_VALUE - 8, stream.available()); } } \ No newline at end of file From 956a59d488c82b0e882179bbc3b957765a7456a9 Mon Sep 17 00:00:00 2001 From: Nick Molcanov <32801560+nck-mlcnv@users.noreply.github.com> Date: Fri, 13 Sep 2024 21:02:30 +0200 Subject: [PATCH 7/8] Add query patterns (#273) * Add new QuerySource * Add pattern queries * Update tests * Update schema * Update test file * Update documentation * Fix default value of config * Remove exception * Fix hashcode * Revert "Fix hashcode" This reverts commit 8e2a09c4c5fb2475a54cb9df24da614b25565947. * Revert "Remove exception" This reverts commit f9ce17a86e08207bd8b184c6e5e181bd4d5fa18e. * Refactoring of QueryList * QueryList is now an interface * added new abstract class FileBasedQueryList * old FileBasedQueryList is now FileReadingQueryList * InMemQueryList.java is no FileCachingQueryList * add StringListQueryList * remove StringListQuerySource.java * Remove logging statement * Update doc * Update graalvm suite * Fix native compilation * Update logging statement * Rename query pattern caching to save * Update doc * Update doc * Fix most change requests * Fix test * Enable stdout for graal script * Fix schema * Fix schema 2 * Cleanup * Add detection of normal queries * Update doc * Generate random variable if it already exists * Add additional variable prefix Co-authored-by: Alexander Bigerl * Change placeholder pattern * Add hash to instance file * Update doc * don't mengle file and limit filename identifier --------- Co-authored-by: Alexander Bigerl --- docs/configuration/queries.md | 52 +++++ example-suite.yml | 6 +- graalvm/queries.txt | 2 +- graalvm/suite.yml | 4 + pom.xml | 2 + schema/iguana-schema.json | 29 ++- .../iguana/cc/query/handler/QueryHandler.java | 189 ++++++++++++++++-- .../cc/query/list/FileBasedQueryList.java | 55 +++++ .../aksw/iguana/cc/query/list/QueryList.java | 26 +-- ...eryList.java => FileCachingQueryList.java} | 8 +- ...eryList.java => FileReadingQueryList.java} | 6 +- .../query/list/impl/StringListQueryList.java | 37 ++++ .../iguana/cc/query/source/QuerySource.java | 9 + src/main/resources/iguana-schema.json | 23 +++ .../query/handler/QueryHandlerConfigTest.java | 18 +- .../cc/query/handler/QueryHandlerTest.java | 1 + .../cc/query/handler/TemplateQueriesTest.java | 107 ++++++++++ ...tTest.java => FileBasedQueryListTest.java} | 12 +- .../suite-configs/valid/config-full.yaml | 4 + 19 files changed, 529 insertions(+), 61 deletions(-) create mode 100644 src/main/java/org/aksw/iguana/cc/query/list/FileBasedQueryList.java rename src/main/java/org/aksw/iguana/cc/query/list/impl/{InMemQueryList.java => FileCachingQueryList.java} (90%) rename src/main/java/org/aksw/iguana/cc/query/list/impl/{FileBasedQueryList.java => FileReadingQueryList.java} (75%) create mode 100644 src/main/java/org/aksw/iguana/cc/query/list/impl/StringListQueryList.java create mode 100644 src/test/java/org/aksw/iguana/cc/query/handler/TemplateQueriesTest.java rename src/test/java/org/aksw/iguana/cc/query/list/{QueryListTest.java => FileBasedQueryListTest.java} (94%) diff --git a/docs/configuration/queries.md b/docs/configuration/queries.md index cef21494b..ffb3bf90a 100644 --- a/docs/configuration/queries.md +++ b/docs/configuration/queries.md @@ -16,6 +16,7 @@ The `queries` property is an object that contains the following properties: | order | no | `linear` | The order in which the queries are executed. If set to `linear` the queries will be executed in their order inside the file. If `format` is set to `folder`, queries will be sorted by their file name first. | `random` or `linear` | | seed | no | `0` | The seed for the random number generator that selects the queries. If multiple workers use the same query handler, their seed will be the sum of the given seed and their worker id. | `12345` | | lang | no | `SPARQL` | Not used for anything at the moment. | | +| template | no | | If set, queries from `path` will be treated as query templates. See [Query Templates](#query-templates) for more information. | | ## Format @@ -98,3 +99,54 @@ tasks: lang: "SPARQL" # ... additional worker properties ``` + +## Query Templates +Query templates are queries containing placeholders for some terms. +Replacement candidates are identified by querying a given endpoint. +This is done in a way that the resulting queries will yield results against endpoints with the same data. + +The placeholders are written in the form of `%%[a-zA-Z0-9_]+%%`, which means that any character sequence consisting +of letters, numbers, and underscores, enclosed by `%%` will be interpreted as a placeholder. +The query templates originated from WatDiv, +where the placeholders are of [similar form](https://dsg.uwaterloo.ca/watdiv/basic-testing.shtml). +If the placeholder name is equal to a variable name in the query, the placeholder will not be assigned +the same variable name during candidate generation. + +Query templates and normal queries can be mixed in the same file or folder. + +An exemplary template: +`SELECT * WHERE {?s %%var1%% ?o . ?o %%var2%%}` + +This template will then be converted to: +`SELECT ?var1 ?var2 WHERE {?s ?var1 ?o . ?o ?var2}` + +The SELECT query will then be requested from the given sparql endpoint (e.g DBpedia). +The solutions for this query are used to instantiate the template. +The results may look like the following: +- `SELECT * WHERE {?s ?o . ?o "123"}` +- `SELECT * WHERE {?s ?o . ?o "12"}` +- `SELECT * WHERE {?s ?o . ?o "1234"}` + +### Configuration +The `template` attribute has the following properties: + +| property | required | default | description | example | +|----------|----------|---------|---------------------------------------------------------------------|-----------------------------| +| endpoint | yes | | The endpoint to query. | `http://dbpedia.org/sparql` | +| limit | no | `2000` | The maximum number of instances per query template. | `100` | +| save | no | `true` | If set to `true`, query instances will be saved in a separate file. | `false` | + +If the `save` attribute is set to `true`, +the instances will be saved in a separate file in the same directory as the query templates. +If the query templates are stored in a folder, the instances will be saved in the parent directory. + +Example of query configuration with query templates: +```yaml +queries: + path: "./example/suite/queries/" + format: "folder" + template: + endpoint: "http://dbpedia.org/sparql" + limit: 100 + save: true +``` diff --git a/example-suite.yml b/example-suite.yml index 00c50eb5e..c4b3d2803 100644 --- a/example-suite.yml +++ b/example-suite.yml @@ -74,7 +74,11 @@ tasks: number: 16 requestType: post query queries: - path: "./example/queries.txt" + path: "./example/query_pattern.txt" + pattern: + endpoint: "https://dbpedia.org/sparql" + limit: 1000 + save: false timeout: 180s completionTarget: duration: 1000s diff --git a/graalvm/queries.txt b/graalvm/queries.txt index b3a425249..eb289ae2f 100644 --- a/graalvm/queries.txt +++ b/graalvm/queries.txt @@ -1 +1 @@ -placeholder \ No newline at end of file +SELECT * WHERE {?s %%var1%% ?o . ?o %%var3%% %%var2%%} \ No newline at end of file diff --git a/graalvm/suite.yml b/graalvm/suite.yml index 243127d1f..75c9bd4c7 100644 --- a/graalvm/suite.yml +++ b/graalvm/suite.yml @@ -59,6 +59,10 @@ tasks: order: "random" seed: 123 lang: "SPARQL" + template: + endpoint: "http://dbpedia.org/sparql" + limit: 1 + save: false timeout: 2s connection: Blazegraph completionTarget: diff --git a/pom.xml b/pom.xml index 9728d96ec..8024e52cd 100644 --- a/pom.xml +++ b/pom.xml @@ -315,6 +315,8 @@ -O3 -H:-UseCompressedReferences -H:+UnlockExperimentalVMOptions + --enable-http + --enable-https true diff --git a/schema/iguana-schema.json b/schema/iguana-schema.json index e0a821c39..0ad54c1b7 100644 --- a/schema/iguana-schema.json +++ b/schema/iguana-schema.json @@ -183,8 +183,8 @@ } }, "required": [ - "type", - "directory" + "type", + "directory" ], "title": "CSVStorage" }, @@ -335,9 +335,29 @@ "type": "object", "unevaluatedProperties": false, "required": [ - "duration" + "duration" ] }, + "Template": { + "type": "object", + "additionalProperties": false, + "properties": { + "endpoint": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1 + }, + "save": { + "type": "boolean" + } + }, + "required": [ + "endpoint" + ], + "title": "Template" + }, "QueryMixes": { "properties": { "number": { @@ -379,6 +399,9 @@ "lang": { "type": "string", "enum": [ "", "SPARQL" ] + }, + "template": { + "$ref": "#/definitions/Template" } }, "required": [ diff --git a/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java b/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java index 8332d094e..6930d3f18 100644 --- a/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java +++ b/src/main/java/org/aksw/iguana/cc/query/handler/QueryHandler.java @@ -5,28 +5,36 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import org.aksw.iguana.cc.query.list.impl.StringListQueryList; import org.aksw.iguana.cc.query.selector.QuerySelector; import org.aksw.iguana.cc.query.selector.impl.LinearQuerySelector; import org.aksw.iguana.cc.query.selector.impl.RandomQuerySelector; import org.aksw.iguana.cc.query.list.QueryList; -import org.aksw.iguana.cc.query.list.impl.FileBasedQueryList; -import org.aksw.iguana.cc.query.list.impl.InMemQueryList; +import org.aksw.iguana.cc.query.list.impl.FileReadingQueryList; +import org.aksw.iguana.cc.query.list.impl.FileCachingQueryList; +import org.aksw.iguana.cc.query.source.QuerySource; import org.aksw.iguana.cc.query.source.impl.FileLineQuerySource; import org.aksw.iguana.cc.query.source.impl.FileSeparatorQuerySource; import org.aksw.iguana.cc.query.source.impl.FolderQuerySource; +import org.apache.jena.query.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; +import java.net.URI; +import java.nio.file.Files; import java.nio.file.Path; -import java.util.HashMap; -import java.util.Objects; +import java.util.*; import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * The QueryHandler is used by every worker that extends the AbstractWorker. - * It initializes the QuerySource, QuerySelector, QueryList and, if needed, PatternHandler. + * It initializes the QuerySource, QuerySelector, QueryList and, if needed, TemplateHandler. * After the initialization, it provides the next query to the worker using the generated QuerySource * and the order given by the QuerySelector. * @@ -61,9 +69,10 @@ public record Config ( Boolean caching, Order order, Long seed, - Language lang + Language lang, + Template template ) { - public Config(@JsonProperty(required = true) String path, Format format, String separator, Boolean caching, Order order, Long seed, Language lang) { + public Config(@JsonProperty(required = true) String path, Format format, String separator, Boolean caching, Order order, Long seed, Language lang, Template template) { this.path = path; this.format = (format == null ? Format.ONE_PER_LINE : format); this.caching = (caching == null || caching); @@ -71,6 +80,11 @@ public Config(@JsonProperty(required = true) String path, Format format, String this.seed = (seed == null ? 0 : seed); this.lang = (lang == null ? Language.SPARQL : lang); this.separator = (separator == null ? "" : separator); + this.template = template; + } + + public Config(@JsonProperty(required = true) String path, Format format, String separator, Boolean caching, Order order, Long seed, Language lang) { + this(path, format, separator, caching, order, seed, lang, null); } public enum Format { @@ -121,13 +135,21 @@ public String value() { return value; } } + + public record Template(@JsonProperty(required = true) URI endpoint, Long limit, Boolean save) { + public Template(URI endpoint, Long limit, Boolean save) { + this.endpoint = endpoint; + this.limit = limit == null ? 2000 : limit; + this.save = save == null || save; + } + } } public record QueryStringWrapper(int index, String query) {} public record QueryStreamWrapper(int index, boolean cached, Supplier queryInputStreamSupplier) {} - protected final Logger LOGGER = LoggerFactory.getLogger(QueryHandler.class); + protected static final Logger LOGGER = LoggerFactory.getLogger(QueryHandler.class); @JsonValue final protected Config config; @@ -150,18 +172,68 @@ protected QueryHandler() { @JsonCreator public QueryHandler(Config config) throws IOException { - final var querySource = switch (config.format()) { - case ONE_PER_LINE -> new FileLineQuerySource(Path.of(config.path())); - case SEPARATOR -> new FileSeparatorQuerySource(Path.of(config.path()), config.separator); - case FOLDER -> new FolderQuerySource(Path.of(config.path())); - }; + this.config = config; + var querySource = createQuerySource(Path.of(config.path)); + + // initialize queryList based on the given configuration + if (config.template() != null) { + queryList = initializeTemplateQueryHandler(querySource); + } else { + queryList = (config.caching()) ? + new FileCachingQueryList(querySource) : + new FileReadingQueryList(querySource); + } + this.hashCode = queryList.hashCode(); + } - queryList = (config.caching()) ? - new InMemQueryList(querySource) : - new FileBasedQueryList(querySource); + private QueryList initializeTemplateQueryHandler(QuerySource templateSource) throws IOException { + QuerySource querySource = templateSource; + final var originalPath = templateSource.getPath(); + final var postfix = String.format("_instances_f%s_l%s.txt", + Integer.toUnsignedString(this.config.template.endpoint.hashCode()), Integer.toUnsignedString((int) this.config.template.limit.longValue())); + final Path instancePath = Files.isDirectory(originalPath) ? + originalPath.resolveSibling(originalPath.getFileName() + postfix) : // if the source of the query templates is a folder, the instances will be saved in a file with the same name as the folder + originalPath.resolveSibling(originalPath.getFileName().toString().split("\\.")[0] + postfix); // if the source of the query templates is a file, the instances will be saved in a file with the same name as the file + if (Files.exists(instancePath)) { + LOGGER.info("Already existing query template instances have been found and will be reused. Delete the following file to regenerate them: {}", instancePath.toAbsolutePath()); + querySource = createQuerySource(instancePath); // if the instances already exist, use them + } else { + final List instances = instantiateTemplateQueries(querySource, config.template); + if (config.template.save) { + // save the instances to a file + Files.createFile(instancePath); + try (var writer = Files.newBufferedWriter(instancePath)) { + for (String instance : instances) { + writer.write(instance); + writer.newLine(); + } + } + // create a new query source based on the new instance file + querySource = createQuerySource(instancePath); + } else { + // query source isn't necessary, because queries aren't stored in a file, + // directly return a list of the instances instead + return new StringListQueryList(instances); + } + } + return (config.caching()) ? + new FileCachingQueryList(querySource) : // if caching is enabled, cache the instances + new FileReadingQueryList(querySource); // if caching is disabled, read the instances from the file every time + } - this.config = config; - hashCode = queryList.hashCode(); + /** + * Creates a QuerySource based on the given path and the format in the configuration. + * + * @param path the path to the query file or folder + * @return the QuerySource + * @throws IOException if the QuerySource could not be created + */ + private QuerySource createQuerySource(Path path) throws IOException { + return switch (config.format()) { + case ONE_PER_LINE -> new FileLineQuerySource(path); + case SEPARATOR -> new FileSeparatorQuerySource(path, config.separator); + case FOLDER -> new FolderQuerySource(path); + }; } public QuerySelector getQuerySelectorInstance() { @@ -224,4 +296,85 @@ public String[] getAllQueryIds() { public Config getConfig() { return config; } + + + /** + * Query templates are queries containing placeholders for some terms. + * Replacement candidates are identified by querying a given endpoint. + * This is done in a way that the resulting queries will yield results against endpoints with the same data. + * The placeholders are written in the form of %%var[0-9]+%%, where [0-9]+ + * represents any number. + *

+ * Exemplary template:
+ * SELECT * WHERE {?s %%var1%% ?o . ?o <http://exa.com> %%var2%%}
+ * This template will then be converted to:
+ * SELECT ?var1 ?var2 {?s ?var1 ?o . ?o <http://exa.com> ?var2}
+ * and will request query solutions from the given sparql endpoint (e.g DBpedia).
+ * The solutions will then be instantiated into the template. + * The result may look like the following:
+ * SELECT * WHERE {?s <http://prop/1> ?o . ?o <http://exa.com> "123"}
+ * SELECT * WHERE {?s <http://prop/1> ?o . ?o <http://exa.com> "12"}
+ * SELECT * WHERE {?s <http://prop/2> ?o . ?o <http://exa.com> "1234"}
+ */ + private static List instantiateTemplateQueries(QuerySource querySource, Config.Template config) throws IOException { + // charset for generating random varia ble names + final String charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + final Random random = new Random(); + + final var templateQueries = new FileCachingQueryList(querySource); + final Pattern template = Pattern.compile("%%[a-zA-Z0-9_]+%%"); + final var instances = new ArrayList(); + for (int i = 0; i < templateQueries.size(); i++) { + // replace all variables in the query template with SPARQL variables + // and store the variable names + var templateQueryString = templateQueries.getQuery(i); + final Matcher matcher = template.matcher(templateQueryString); + final var variables = new LinkedHashMap(); // a set, that preserves insertion order + while (matcher.find()) { + final var match = matcher.group(); + if (variables.containsKey(match)) continue; + String variableName = match.replaceAll("%%", ""); + while (templateQueryString.contains("?" + variableName) || templateQueryString.contains("$" + variableName)) { // generate random variable name with 20 characters until it is unique + variableName = IntStream.range(0, 20).mapToObj(m -> String.valueOf(charset.charAt(random.nextInt(charset.length())))).collect(Collectors.joining()); + } + final var variable = "?" + variableName; + variables.put(match, variable); + templateQueryString = templateQueryString.replaceAll(match, variable); + } + + // if no placeholders are found, the query is already a valid SPARQL query + if (variables.isEmpty()) { + instances.add(templateQueryString); + continue; + } + + // build SELECT query for finding bindings for the variables + final var templateQuery = QueryFactory.create(templateQueryString); + final var whereClause = "WHERE " + templateQuery.getQueryPattern(); + final var selectQueryString = new ParameterizedSparqlString(); + selectQueryString.setCommandText("SELECT DISTINCT " + String.join(" ", variables.values())); + selectQueryString.append(" " + whereClause); + selectQueryString.append(" LIMIT " + config.limit()); + selectQueryString.setNsPrefixes(templateQuery.getPrefixMapping()); + + // send request to SPARQL endpoint and instantiate the template based on results + try (QueryExecution exec = QueryExecutionFactory.createServiceRequest(config.endpoint().toString(), selectQueryString.asQuery())) { + ResultSet resultSet = exec.execSelect(); + if (!resultSet.hasNext()) { + LOGGER.warn("No results for query template: {}", templateQueryString); + } + int count = 0; + while (resultSet.hasNext() && count++ < config.limit()) { + var instance = new ParameterizedSparqlString(templateQueryString); + QuerySolution solution = resultSet.next(); + for (String var : resultSet.getResultVars()) { + instance.clearParam(var); + instance.setParam(var, solution.get(var)); + } + instances.add(instance.toString()); + } + } + } + return instances; + } } diff --git a/src/main/java/org/aksw/iguana/cc/query/list/FileBasedQueryList.java b/src/main/java/org/aksw/iguana/cc/query/list/FileBasedQueryList.java new file mode 100644 index 000000000..0256fee53 --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/query/list/FileBasedQueryList.java @@ -0,0 +1,55 @@ +package org.aksw.iguana.cc.query.list; + +import org.aksw.iguana.cc.query.source.QuerySource; + +import java.io.IOException; +import java.io.InputStream; + +/** + * The abstract class for a QueryList. A query list provides the queries to the QueryHandler. + * + * @author frensing + */ +public abstract class FileBasedQueryList implements QueryList{ + + /** + * This is the QuerySource from which the queries should be retrieved. + */ + final protected QuerySource querySource; + + public FileBasedQueryList(QuerySource querySource) { + if (querySource == null) { + throw new IllegalArgumentException("QuerySource must not be null"); + } + this.querySource = querySource; + } + + /** + * This method returns the amount of queries in the query list. + * + * @return The amount of queries in the query list + */ + public int size() { + return querySource.size(); + } + + /** + * This method returns the hashcode of the query list which is the hashcode of the query source. + * + * @return The hashcode of the query list + */ + @Override + public int hashCode() { + return querySource.hashCode(); + } + + /** + * This method returns a query at the given index. + * + * @param index Index of the query in the list + * @return The query at the given index + */ + public abstract String getQuery(int index) throws IOException; + + public abstract InputStream getQueryStream(int index) throws IOException; +} diff --git a/src/main/java/org/aksw/iguana/cc/query/list/QueryList.java b/src/main/java/org/aksw/iguana/cc/query/list/QueryList.java index df9cd83ef..623a8c67f 100644 --- a/src/main/java/org/aksw/iguana/cc/query/list/QueryList.java +++ b/src/main/java/org/aksw/iguana/cc/query/list/QueryList.java @@ -10,37 +10,21 @@ * * @author frensing */ -public abstract class QueryList { - - /** - * This is the QuerySource from which the queries should be retrieved. - */ - final protected QuerySource querySource; - - public QueryList(QuerySource querySource) { - if (querySource == null) - throw new IllegalArgumentException("QuerySource must not be null."); - this.querySource = querySource; - } +public interface QueryList { /** * This method returns the amount of queries in the query list. * * @return The amount of queries in the query list */ - public int size() { - return querySource.size(); - } + int size(); /** * This method returns the hashcode of the query list which is the hashcode of the query source. * * @return The hashcode of the query list */ - @Override - public int hashCode() { - return querySource.hashCode(); - } + int hashCode(); /** * This method returns a query at the given index. @@ -48,7 +32,7 @@ public int hashCode() { * @param index Index of the query in the list * @return The query at the given index */ - public abstract String getQuery(int index) throws IOException; + String getQuery(int index) throws IOException; - public abstract InputStream getQueryStream(int index) throws IOException; + InputStream getQueryStream(int index) throws IOException; } diff --git a/src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java b/src/main/java/org/aksw/iguana/cc/query/list/impl/FileCachingQueryList.java similarity index 90% rename from src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java rename to src/main/java/org/aksw/iguana/cc/query/list/impl/FileCachingQueryList.java index e8b5ac086..8f6c3a38d 100644 --- a/src/main/java/org/aksw/iguana/cc/query/list/impl/InMemQueryList.java +++ b/src/main/java/org/aksw/iguana/cc/query/list/impl/FileCachingQueryList.java @@ -1,6 +1,6 @@ package org.aksw.iguana.cc.query.list.impl; -import org.aksw.iguana.cc.query.list.QueryList; +import org.aksw.iguana.cc.query.list.FileBasedQueryList; import org.aksw.iguana.cc.query.source.QuerySource; import org.aksw.iguana.commons.io.ByteArrayListInputStream; import org.aksw.iguana.commons.io.ByteArrayListOutputStream; @@ -19,13 +19,13 @@ * * @author frensing */ -public class InMemQueryList extends QueryList { +public class FileCachingQueryList extends FileBasedQueryList { - private static final Logger LOGGER = LoggerFactory.getLogger(InMemQueryList.class); + private static final Logger LOGGER = LoggerFactory.getLogger(FileCachingQueryList.class); private final List queries = new ArrayList<>(); - public InMemQueryList(QuerySource querySource) throws IOException { + public FileCachingQueryList(QuerySource querySource) throws IOException { super(querySource); LOGGER.info("Reading queries from the source with the hash code {} into memory.", querySource.hashCode()); for (int i = 0; i < querySource.size(); i++) { diff --git a/src/main/java/org/aksw/iguana/cc/query/list/impl/FileBasedQueryList.java b/src/main/java/org/aksw/iguana/cc/query/list/impl/FileReadingQueryList.java similarity index 75% rename from src/main/java/org/aksw/iguana/cc/query/list/impl/FileBasedQueryList.java rename to src/main/java/org/aksw/iguana/cc/query/list/impl/FileReadingQueryList.java index f01c3ab63..e3074be04 100644 --- a/src/main/java/org/aksw/iguana/cc/query/list/impl/FileBasedQueryList.java +++ b/src/main/java/org/aksw/iguana/cc/query/list/impl/FileReadingQueryList.java @@ -1,6 +1,6 @@ package org.aksw.iguana.cc.query.list.impl; -import org.aksw.iguana.cc.query.list.QueryList; +import org.aksw.iguana.cc.query.list.FileBasedQueryList; import org.aksw.iguana.cc.query.source.QuerySource; import java.io.IOException; @@ -11,9 +11,9 @@ * * @author frensing */ -public class FileBasedQueryList extends QueryList { +public class FileReadingQueryList extends FileBasedQueryList { - public FileBasedQueryList(QuerySource querySource) { + public FileReadingQueryList(QuerySource querySource) { super(querySource); } diff --git a/src/main/java/org/aksw/iguana/cc/query/list/impl/StringListQueryList.java b/src/main/java/org/aksw/iguana/cc/query/list/impl/StringListQueryList.java new file mode 100644 index 000000000..1d448940e --- /dev/null +++ b/src/main/java/org/aksw/iguana/cc/query/list/impl/StringListQueryList.java @@ -0,0 +1,37 @@ +package org.aksw.iguana.cc.query.list.impl; + +import org.aksw.iguana.cc.query.list.QueryList; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +public class StringListQueryList implements QueryList { + + private final List queries; + + public StringListQueryList(List queries) { + this.queries = queries; + } + + @Override + public String getQuery(int index) throws IOException { + return queries.get(index); + } + + @Override + public InputStream getQueryStream(int index) throws IOException { + return new ByteArrayInputStream(queries.get(index).getBytes()); + } + + @Override + public int size() { + return queries.size(); + } + + @Override + public int hashCode() { + return queries.hashCode(); + } +} diff --git a/src/main/java/org/aksw/iguana/cc/query/source/QuerySource.java b/src/main/java/org/aksw/iguana/cc/query/source/QuerySource.java index 59285cfee..430a024c0 100644 --- a/src/main/java/org/aksw/iguana/cc/query/source/QuerySource.java +++ b/src/main/java/org/aksw/iguana/cc/query/source/QuerySource.java @@ -58,6 +58,15 @@ public QuerySource(Path path) { */ public abstract List getAllQueries() throws IOException; + /** + * This method returns the path of the file or folder, that contains the queries. + * + * @return the path of the file or folder, that contains the queries + */ + public Path getPath() { + return path; + } + @Override public int hashCode() { return hashCode; diff --git a/src/main/resources/iguana-schema.json b/src/main/resources/iguana-schema.json index 4750e59df..d92fb8d67 100644 --- a/src/main/resources/iguana-schema.json +++ b/src/main/resources/iguana-schema.json @@ -338,6 +338,26 @@ "duration" ] }, + "Template": { + "type": "object", + "additionalProperties": false, + "properties": { + "endpoint": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1 + }, + "save": { + "type": "boolean" + } + }, + "required": [ + "endpoint" + ], + "title": "Template" + }, "QueryMixes": { "properties": { "number": { @@ -379,6 +399,9 @@ "lang": { "type": "string", "enum": [ "", "SPARQL" ] + }, + "template": { + "$ref": "#/definitions/Template" } }, "required": [ diff --git a/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerConfigTest.java b/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerConfigTest.java index ace718d9f..71e256055 100644 --- a/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerConfigTest.java +++ b/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerConfigTest.java @@ -2,11 +2,11 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import java.net.URI; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; @@ -65,6 +65,19 @@ private static Stream testDeserializationData() { """ {"path":"some.queries","format":"separator", "separator": "\\n", "caching":true,"order":"random","seed":42,"lang":"SPARQL"} """ + ), + Arguments.of(new QueryHandler.Config("some.queries", + QueryHandler.Config.Format.SEPARATOR, + "\n", + true, + QueryHandler.Config.Order.RANDOM, + 42L, + QueryHandler.Config.Language.SPARQL, + new QueryHandler.Config.Template(URI.create("http://example.org/sparql"), 2000L, true) + ), + """ + {"path":"some.queries","format":"separator", "separator": "\\n", "caching":true,"order":"random","seed":42,"lang":"SPARQL","template": {"endpoint": "http://example.org/sparql"}} + """ ) ); } @@ -125,9 +138,7 @@ private static Stream testSerializationData() { @ParameterizedTest @MethodSource("testSerializationData") public void testSerialisation(QueryHandler.Config config, String expectedJson) throws Exception { - final String actual = mapper.writeValueAsString(config); - System.out.println(actual); assertEquals(mapper.readTree(expectedJson), mapper.readTree(actual)); } @@ -135,7 +146,6 @@ public void testSerialisation(QueryHandler.Config config, String expectedJson) t @MethodSource("testDeserializationData") public void testDeserialization(QueryHandler.Config expected, String json) throws Exception { final var actual = mapper.readValue(json, QueryHandler.Config.class); - assertEquals(expected, actual); } } \ No newline at end of file diff --git a/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerTest.java b/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerTest.java index 152fe2c7b..aa0832311 100644 --- a/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerTest.java +++ b/src/test/java/org/aksw/iguana/cc/query/handler/QueryHandlerTest.java @@ -9,6 +9,7 @@ import org.aksw.iguana.cc.query.source.impl.FolderQuerySource; import org.aksw.iguana.cc.query.source.impl.FolderQuerySourceTest; import org.junit.jupiter.api.*; +import org.junit.jupiter.api.condition.DisabledInNativeImage; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; diff --git a/src/test/java/org/aksw/iguana/cc/query/handler/TemplateQueriesTest.java b/src/test/java/org/aksw/iguana/cc/query/handler/TemplateQueriesTest.java new file mode 100644 index 000000000..2beb8bf19 --- /dev/null +++ b/src/test/java/org/aksw/iguana/cc/query/handler/TemplateQueriesTest.java @@ -0,0 +1,107 @@ +package org.aksw.iguana.cc.query.handler; + +import com.github.tomakehurst.wiremock.common.ConsoleNotifier; +import com.github.tomakehurst.wiremock.core.Options; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import org.apache.jena.query.QueryParseException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledInNativeImage; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; + +@DisabledInNativeImage // WireMock is not supported in native image +public class TemplateQueriesTest extends QueryHandlerTest { + + public static Path tempTemplateFile; + + private static final String RESPONSE_JSON = """ + { + "head": { + "vars": [ "var0", "var1", "var2" ] + }, + "results": { + "bindings": [ + { + "var0": { "type": "uri", "value": "http://www.w3.org/2002/07/owl#Class" }, + "var1": { "type": "uri", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" }, + "var2": { "type": "uri", "value": "http://www.w3.org/2002/07/owl#Thing" } + }, + { + "var0": { "type": "uri", "value": "http://www.w3.org/2002/07/owl#Class" }, + "var1": { "type": "uri", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" }, + "var2": { "type": "uri", "value": "http://www.w3.org/2002/07/owl#Thing" } + } + ] + } + } + """; + + @RegisterExtension + public static WireMockExtension wm = WireMockExtension.newInstance() + .options(new WireMockConfiguration() + .useChunkedTransferEncoding(Options.ChunkedEncodingPolicy.NEVER) + .dynamicPort() + .notifier(new ConsoleNotifier(false)) + .jettyIdleTimeout(2000L) + .jettyStopTimeout(2000L) + .timeout(2000)) + .build(); + + @Test + public void testTemplateQueries() throws IOException { + String templateQuery = "PREFIX rdf: SELECT * WHERE {?s rdf:type %%var0%% ; %%var1%% %%var2%%. %%var2%% ?p }"; + tempTemplateFile = Files.createTempFile(parentFolder, "Template", ".txt"); + Files.writeString(tempTemplateFile, templateQuery, StandardCharsets.UTF_8); + final var queryHandlerConfig = new QueryHandler.Config( + tempTemplateFile.toString(), + QueryHandler.Config.Format.ONE_PER_LINE, + null, + true, + QueryHandler.Config.Order.LINEAR, + null, + QueryHandler.Config.Language.SPARQL, + new QueryHandler.Config.Template(URI.create("http://localhost:" + wm.getPort()), 2000L, false) + ); + wm.stubFor(get(anyUrl()) + .withQueryParam("query", matching("PREFIX\\s+rdf:\\s+\\s+SELECT\\s+DISTINCT\\s+\\?var0\\s+\\?var1\\s+\\?var2\\s+WHERE\\s+\\{\\s*\\?s\\s+rdf:type\\s+\\?var0\\s*;\\s*\\?var1\\s+\\?var2\\s*\\.\\s*\\?var2\\s+\\?p\\s+\\s*}\\s+LIMIT\\s+2000\\s*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/sparql-results+json") + .withBody(RESPONSE_JSON))); + final var queryHandler = new QueryHandler(queryHandlerConfig); + final var selector = queryHandler.getQuerySelectorInstance(); + Assertions.assertEquals(2, queryHandler.getQueryCount()); + for (int i = 0; i < 2; i++) { + final var query = queryHandler.getNextQuery(selector); + Assertions.assertEquals("PREFIX rdf: SELECT * WHERE {?s rdf:type ; . ?p }", query.query()); + } + } + + @Test + public void testMalformedTemplateQuery() throws IOException { + String template = "SELECT * WHERE {%%var0%% %%var0%% %%var0%% %%var0%%}"; + tempTemplateFile = Files.createTempFile(parentFolder, "Template", ".txt"); + Files.writeString(tempTemplateFile, template, StandardCharsets.UTF_8); + final var queryHandlerConfig = new QueryHandler.Config( + tempTemplateFile.toString(), + QueryHandler.Config.Format.ONE_PER_LINE, + null, + true, + QueryHandler.Config.Order.LINEAR, + null, + QueryHandler.Config.Language.SPARQL, + new QueryHandler.Config.Template(URI.create("http://localhost:" + wm.getPort()), 2000L, false) + ); + Assertions.assertThrows(QueryParseException.class, () -> new QueryHandler(queryHandlerConfig)); + } + +} diff --git a/src/test/java/org/aksw/iguana/cc/query/list/QueryListTest.java b/src/test/java/org/aksw/iguana/cc/query/list/FileBasedQueryListTest.java similarity index 94% rename from src/test/java/org/aksw/iguana/cc/query/list/QueryListTest.java rename to src/test/java/org/aksw/iguana/cc/query/list/FileBasedQueryListTest.java index 92c5ad6d2..1025f72f8 100644 --- a/src/test/java/org/aksw/iguana/cc/query/list/QueryListTest.java +++ b/src/test/java/org/aksw/iguana/cc/query/list/FileBasedQueryListTest.java @@ -1,7 +1,7 @@ package org.aksw.iguana.cc.query.list; -import org.aksw.iguana.cc.query.list.impl.FileBasedQueryList; -import org.aksw.iguana.cc.query.list.impl.InMemQueryList; +import org.aksw.iguana.cc.query.list.impl.FileReadingQueryList; +import org.aksw.iguana.cc.query.list.impl.FileCachingQueryList; import org.aksw.iguana.cc.query.source.QuerySource; import org.aksw.iguana.cc.query.source.impl.FileLineQuerySource; import org.aksw.iguana.cc.query.source.impl.FileSeparatorQuerySource; @@ -26,7 +26,7 @@ import static org.junit.jupiter.api.Assertions.*; -class QueryListTest { +public class FileBasedQueryListTest { private enum QuerySourceType { FILE_LINE, FILE_SEPARATOR, @@ -58,7 +58,7 @@ public static List data() throws IOException { if (cachedArguments != null) return cachedArguments; - final var queryListClasses = List.of(InMemQueryList.class, FileBasedQueryList.class); + final var queryListClasses = List.of(FileCachingQueryList.class, FileReadingQueryList.class); final var querySources = List.of(QuerySourceType.FILE_SEPARATOR, QuerySourceType.FILE_LINE, QuerySourceType.FOLDER); final var sizes = List.of(1, 2, 10, 100, 1000); @@ -104,8 +104,8 @@ public static List data() throws IOException { @Test public void testIllegalArguments() { - assertThrows(IllegalArgumentException.class, () -> new InMemQueryList(null)); - assertThrows(IllegalArgumentException.class, () -> new FileBasedQueryList(null)); + assertThrows(IllegalArgumentException.class, () -> new FileCachingQueryList(null)); + assertThrows(IllegalArgumentException.class, () -> new FileReadingQueryList(null)); } @ParameterizedTest(name = "[{index}] queryListClass={0}, querySourceConfig={1}") diff --git a/src/test/resources/suite-configs/valid/config-full.yaml b/src/test/resources/suite-configs/valid/config-full.yaml index 5b4c5fb21..ad228cc29 100644 --- a/src/test/resources/suite-configs/valid/config-full.yaml +++ b/src/test/resources/suite-configs/valid/config-full.yaml @@ -53,6 +53,10 @@ tasks: path: "./example/suite/queries/" format: "folder" order: "random" + template: + endpoint: "http://localhost:3030/sp2b" + limit: 2000 + save: false timeout: 2S connection: fuseki completionTarget: From 033ef0b7ff5b03e0ff09a3d02266c27b762925f1 Mon Sep 17 00:00:00 2001 From: Alexander Bigerl Date: Mon, 16 Sep 2024 13:51:07 +0200 Subject: [PATCH 8/8] version bump (#277) --- graalvm/generate-profile.sh | 6 +++--- pom.xml | 2 +- schema/iguana.owx | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/graalvm/generate-profile.sh b/graalvm/generate-profile.sh index 5960767ed..8822f673b 100755 --- a/graalvm/generate-profile.sh +++ b/graalvm/generate-profile.sh @@ -40,21 +40,21 @@ if [ -z "$SUITE" ]; then fi # Instrument the application -"$GRAALVM_HOME"/bin/native-image --pgo-instrument "$ARGUMENTS" -jar ./target/iguana.jar -o "./target/iguana-4.0.0-instrumented" +"$GRAALVM_HOME"/bin/native-image --pgo-instrument "$ARGUMENTS" -jar ./target/iguana.jar -o "./target/iguana-4.1.0-instrumented" if [ $? -ne 0 ]; then echo "Error while instrumenting the application." exit 1 fi # Generate the profile -./target/iguana-4.0.0-instrumented -XX:ProfilesDumpFile=custom.iprof "$SUITE" +./target/iguana-4.1.0-instrumented -XX:ProfilesDumpFile=custom.iprof "$SUITE" if [ $? -ne 0 ]; then echo "Error while generating the profile." exit 1 fi # Compile the application with the profile -"$GRAALVM_HOME"/bin/native-image --pgo=custom.iprof "$ARGUMENTS" -jar ./target/iguana.jar -o "./target/iguana-4.0.0-pgo" +"$GRAALVM_HOME"/bin/native-image --pgo=custom.iprof "$ARGUMENTS" -jar ./target/iguana.jar -o "./target/iguana-4.1.0-pgo" if [ $? -ne 0 ]; then echo "Error while compiling the application." exit 1 diff --git a/pom.xml b/pom.xml index 8024e52cd..b4b9049ec 100644 --- a/pom.xml +++ b/pom.xml @@ -37,7 +37,7 @@ ${major.minor.version}.${build.version} ${major.version}.${minor.version} 4 - 0 + 1 0 17 diff --git a/schema/iguana.owx b/schema/iguana.owx index 9ae016f28..8a70dc8f4 100644 --- a/schema/iguana.owx +++ b/schema/iguana.owx @@ -6,7 +6,7 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" ontologyIRI="https://iguana-benchmark.eu/ontology/" - versionIRI="https://iguana-benchmark.eu/ontology/4.0.0/"> + versionIRI="https://iguana-benchmark.eu/ontology/4.1.0/"> @@ -48,7 +48,7 @@ - 4.0.0 + 4.1.0