diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..8c4a6e3 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,27 @@ +# .github/workflows/publish.yml + +name: Publish +on: + release: + types: [released, prereleased] +jobs: + publish: + name: Release build and publish + runs-on: macOS-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-version: 21 + - name: Publish to MavenCentral + run: ./gradlew publishToMavenCentral --no-configuration-cache + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY_CONTENTS }} + diff --git a/.gitignore b/.gitignore index e6d18f3..d1f804e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ bin .gradle build /modules -/plugins \ No newline at end of file +/plugins +logs \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/build.gradle.kts b/build.gradle.kts index 300b4f8..e7a8a26 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,13 +1,13 @@ plugins { java application - id("com.github.johnrengelman.shadow") version "8.1.1" - id("maven-publish") + id("com.gradleup.shadow") version "9.4.3" + id("com.vanniktech.maven.publish") version "0.37.0" } -group = "igs-landstuhl" +group = "io.github.learn-monitor" -version = "v1.1.0-SNAPSHOT-0" +version = "v2.0.0-SNAPSHOT-3" application { mainClass.set("de.igslandstuhl.database.Application") @@ -23,7 +23,13 @@ dependencies { implementation("commons-codec:commons-codec:1.19.0") implementation("com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer:20260101.1") implementation("org.jline:jline:3.30.6") // for better console input handling - implementation("org.yaml:snakeyaml:2.2") // plugin imports + + // Logging + implementation("org.slf4j:slf4j-api:2.0.13") + implementation("ch.qos.logback:logback-classic:1.5.6") + + // built-in plugins + implementation("io.github.learn-monitor:plugin-loader:v1.0.5") testImplementation("org.junit.jupiter:junit-jupiter:5.13.4") // using JUnit 5 (latest) testRuntimeOnly("org.junit.platform:junit-platform-launcher") @@ -53,26 +59,38 @@ java { } } -publishing { - publications { - create("mavenJava") { - from(components["java"]) +mavenPublishing { + publishToMavenCentral() - groupId = "igs-landstuhl" - artifactId = "student-database" - version = project.version.toString() - } - } + signAllPublications() + + coordinates(group.toString(), "student-database", version.toString()) - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/Learn-Monitor/student-database/") + pom { + name = "Student database" + description = "A Java-based application designed to manage and store student information efficiently. It allows admins to perform CRUD (Create, Read, Update, Delete) operations on student records, classes, subjects, and other school-related data, making it a valuable tool for educational institutions. Students can view their progress, and teachers can assign them topics, based on subjects." + url = "https://github.com/Learn-Monitor/student-database" - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") + licenses { + license { + name = "GNU General Public License v3.0" + url = "http://www.gnu.org/licenses/gpl-3.0.txt" } } + developers { + developer { + id = "schlaumeier5" + name = "Lukas Morgenstern" + url = "https://github.com/schlaumeier5" + } + } + scm { + url = "https://github.com/Learn-Monitor/student-database" + connection = "scm:git:https://github.com/Learn-Monitor/student-database.git" + developerConnection = "scm:git:ssh://git@github.com/Learn-Monitor/student-database.git" + } } +} +tasks.withType().configureEach { + dependsOn(tasks.withType()) } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a441313..7e7d24f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew.bat b/gradlew.bat index 25da30d..7101f8e 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,92 +1,92 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/de/igslandstuhl/database/Application.java b/src/main/java/de/igslandstuhl/database/Application.java index d84ca56..7884e4c 100644 --- a/src/main/java/de/igslandstuhl/database/Application.java +++ b/src/main/java/de/igslandstuhl/database/Application.java @@ -5,6 +5,8 @@ import java.util.List; import org.jline.reader.UserInterruptException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import de.igslandstuhl.database.api.SerializationException; import de.igslandstuhl.database.api.Subject; @@ -17,6 +19,7 @@ import de.igslandstuhl.database.server.webserver.WebPath; import de.igslandstuhl.database.server.webserver.handlers.GetRequestHandler; import de.igslandstuhl.database.server.webserver.handlers.PostRequestHandler; +import de.igslandstuhl.database.server.webserver.handlers.get.SQLRequestHandler; import de.igslandstuhl.database.utils.CommandLineUtils; /** @@ -29,6 +32,10 @@ public final class Application { public static final String TITLE_DELIMITER = "¶"; public static final String TASK_TITLE_DELIMITER = "\\|"; public static final String TASK_DELIMITER = "¤"; + + public static final Logger LOGGER = LoggerFactory.getLogger(Application.class); + public static final Logger LOGGER_API = LoggerFactory.getLogger("de.igslandstuhl.database.api"); + private static Application instance = new Application(new String[] {"--test-environment", "true"}); public static Application getInstance() { return instance; @@ -88,7 +95,6 @@ public Topic[] readFile(String file) throws SerializationException, SQLException } } } catch (Throwable t) { - t.printStackTrace(); throw new SerializationException("Failed to read file", t); } @@ -96,20 +102,32 @@ public Topic[] readFile(String file) throws SerializationException, SQLException return topics.toArray(topicsArr); } + private static void registerBuiltinPlugins() { + LOGGER.info("Registering built-in plugins..."); + Registry.builtinPluginRegistry().register("plugin-loader", de.igslandstuhl.database.plugins.PluginLoader.class); + } + public static void main(String[] args) throws Exception { + LOGGER.info("Starting up student-database..."); + instance = new Application(args); + registerBuiltinPlugins(); PluginLoader.getInstance().preloadPlugins(); if (!getInstance().suppressCmd()) { + LOGGER.info("Setting up command line..."); Command.registerCommands(); CommandLineUtils.setup(); } - + + LOGGER.info("Setting up server..."); + Server.getInstance().getConnection().createTables(); Holiday.setupCurrentSchoolYear(); PostRequestHandler.registerHandlers(); + SQLRequestHandler.register(); PluginLoader.getInstance().registerPlugins(); WebPath.registerPaths(); @@ -117,14 +135,17 @@ public static void main(String[] args) throws Exception { GetRequestHandler.getInstance().registerHandlers(); if (getInstance().runsWebServer()) { + LOGGER.info("Starting WebServer..."); Server.getInstance().getWebServer().start(); } PluginLoader.getInstance().enablePlugins(); + LOGGER.info("Adding shutdown hook for plugin cleanup..."); Runtime.getRuntime().addShutdownHook(new Thread(() -> PluginLoader.getInstance().unloadPlugins(),"Plugin cleanup thread")); try { + LOGGER.info("Starting main loop..."); while (true) { if (!getInstance().suppressCmd()) { CommandLineUtils.waitForCommandAndExec(); diff --git a/src/main/java/de/igslandstuhl/database/Registry.java b/src/main/java/de/igslandstuhl/database/Registry.java index 6e756e2..2c83a3f 100644 --- a/src/main/java/de/igslandstuhl/database/Registry.java +++ b/src/main/java/de/igslandstuhl/database/Registry.java @@ -8,13 +8,16 @@ import java.util.stream.Stream; import de.igslandstuhl.database.client.HTMLTemplate; +import de.igslandstuhl.database.client.dynamic.DynamicFieldType; import de.igslandstuhl.database.client.navigation.NavigationElement; import de.igslandstuhl.database.client.navigation.NavigationType; +import de.igslandstuhl.database.plugins.BuiltinPlugin; import de.igslandstuhl.database.plugins.Plugin; import de.igslandstuhl.database.server.commands.Command; import de.igslandstuhl.database.server.commands.CommandDescription; import de.igslandstuhl.database.server.webserver.WebPath; import de.igslandstuhl.database.server.webserver.handlers.HttpHandler; +import de.igslandstuhl.database.server.webserver.handlers.get.SQLRequestHandler; import de.igslandstuhl.database.server.webserver.requests.APIPostRequest; import de.igslandstuhl.database.server.webserver.requests.GetRequest; import de.igslandstuhl.database.utils.RegistryEnum; @@ -24,10 +27,13 @@ public class Registry implements Closeable { private static final Registry COMMAND_DESCRIPTION_REGISTRY = new Registry<>(); private static final Registry> POST_HANDLER_REGISTRY = new Registry<>(); private static final Registry> GET_HANDLER_REGISTRY = new Registry<>(); + private static final Registry SQL_REQUEST_HANDLER_REGISTRY = new Registry<>(); private static final Registry PLUGIN_REGISTRY = new Registry<>(); + private static final Registry> BUILTIN_PLUGIN_REGISTRY = new Registry<>(); private static final Registry WEB_PATH_REGISTRY = new Registry<>(); private static final EnumRegistry NAVIGATION_REGISTRY = new EnumRegistry<>(NavigationType.class); + private static final EnumRegistry DYNAMIC_TEMPLATES_REGISTRY = new EnumRegistry<>(DynamicFieldType.class); private static final Registry TEMPLATE_REGISTRY = new Registry<>(); public static Registry commandRegistry() { @@ -39,9 +45,15 @@ public static Registry> postRequestHandlerRe public static Registry> getRequestHandlerRegistry() { return GET_HANDLER_REGISTRY; } + public static Registry sqlRequestHandlerRegistry() { + return SQL_REQUEST_HANDLER_REGISTRY; + } public static Registry pluginRegistry() { return PLUGIN_REGISTRY; } + public static Registry> builtinPluginRegistry() { + return BUILTIN_PLUGIN_REGISTRY; + } public static Registry commandDescriptionRegistry() { return COMMAND_DESCRIPTION_REGISTRY; } @@ -51,6 +63,9 @@ public static Registry webPathRegistry() { public static EnumRegistry navigationRegistry() { return NAVIGATION_REGISTRY; } + public static EnumRegistry dynamicTemplatesRegistry() { + return DYNAMIC_TEMPLATES_REGISTRY; + } public static Registry templateRegistry() { return TEMPLATE_REGISTRY; } diff --git a/src/main/java/de/igslandstuhl/database/api/Admin.java b/src/main/java/de/igslandstuhl/database/api/Admin.java index cc1c69f..04b83a9 100644 --- a/src/main/java/de/igslandstuhl/database/api/Admin.java +++ b/src/main/java/de/igslandstuhl/database/api/Admin.java @@ -2,6 +2,7 @@ import java.sql.SQLException; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -61,7 +62,7 @@ public static Admin get(String username) { try { return Server.getInstance().processSingleRequest(Admin::fromSQL, "get_admin_by_username", SQL_FIELDS, username); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve Admin user '{}' from database", username, e); return null; } } diff --git a/src/main/java/de/igslandstuhl/database/api/Room.java b/src/main/java/de/igslandstuhl/database/api/Room.java deleted file mode 100644 index 9919a6c..0000000 --- a/src/main/java/de/igslandstuhl/database/api/Room.java +++ /dev/null @@ -1,240 +0,0 @@ -package de.igslandstuhl.database.api; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import de.igslandstuhl.database.server.Server; -import de.igslandstuhl.database.server.sql.SQLHelper; - -/** - * Represents a room in the system. - * Each room has a label and a minimum level required for students to access it. - */ -public class Room implements APIObject { - private static final String[] SQL_FIELDS = {"label", "minimum_level"}; - /** - * A map to store all rooms, keyed by their label. - * This allows for quick access to room information without repeated database queries. - */ - private static final Map rooms = new HashMap<>(); - /** - * The label of the room, which is a unique identifier. - */ - private final String label; - /** - * The minimum level required for students to access this room. - * This is used to determine if a student is eligible to enter the room. - */ - private final int minimumLevel; - - /** - * Constructs a new Room. - * @param label the label of the room - * @param minimumLevel the minimum level required to access the room - */ - private Room(String label, int minimumLevel) { - this.label = label; - this.minimumLevel = minimumLevel; - } - /** - * Creates a Room instance from SQL result fields. - * This method is used to convert the result of a database query into a Room object. - * @param sqlResult the result fields from the SQL query - * @return a Room object constructed from the SQL fields - * @see Room#SQL_FIELDS - */ - private static Room fromSQLFields(String[] sqlResult) { - String label = sqlResult[0]; - int minimumLevel = Integer.parseInt(sqlResult[1]); - return new Room(label, minimumLevel); - } - /** - * Fetches all rooms from the database and populates the static map. - * This method retrieves all room records and stores them in the `rooms` map for quick access. - * @throws SQLException if there is an error accessing the database - */ - public static void fetchAll() throws SQLException { - rooms.clear(); - Server.getInstance().processRequest((fields) -> { - Room room = fromSQLFields(fields); - rooms.put(room.getLabel(), room); - }, "get_all_rooms", SQL_FIELDS); - } - /** - * Checks if the rooms map is empty and fetches all rooms if it is. - * This method ensures that the rooms are loaded into memory only once, - * preventing unnecessary database queries in subsequent calls. - * @throws SQLException if there is an error accessing the database - */ - public static void fetchAllIfNotExists() throws SQLException { - if (rooms.size() == 0) { - fetchAll(); - } - } - - /** - * Returns a map of all rooms. - * This method ensures that all rooms are fetched from the database if they haven't been loaded yet. - * @return a map of room labels to Room objects - * @throws IllegalStateException if there is an error fetching rooms from the database - */ - public static Map getRooms() { - try { - fetchAllIfNotExists(); - } catch (SQLException e) { - throw new IllegalStateException("Could not fetch rooms", e); - } - return rooms; - } - /** - * Retrieves a room by its label. - * This method checks if the room is already in the static map; if not, it fetches it from the database. - * @param label the label of the room to retrieve - * @return the Room object corresponding to the label, or null if not found - */ - public static Room getRoom(String label) { - if (rooms.keySet().contains(label)) { - return rooms.get(label); - } else { - try { - Room room = Server.getInstance().processSingleRequest(Room::fromSQLFields, "get_room_by_label", SQL_FIELDS, label); - if (room == null) { - return null; - } - rooms.put(label, room); - return room; - } catch (SQLException e) { - e.printStackTrace(); - return null; - } - } - } - /** - * Adds a new room to the database and the static map. - * This method creates a new Room object, inserts it into the database, - * and adds it to the `rooms` map for future access. - * @param label the label of the new room - * @param minimumLevel the minimum level required to access the new room - * @return the newly created Room object - * @throws SQLException if there is an error inserting the room into the database - */ - public static Room addRoom(String label, int minimumLevel) throws SQLException { - Room room = new Room(label, minimumLevel); - Server.getInstance().getConnection().executeVoidProcessSecure(SQLHelper.getAddObjectProcess("room", label, String.valueOf(minimumLevel))); - rooms.put(label, room); - return room; - } - public void delete() throws SQLException { - Server.getInstance().getConnection().executeVoidProcessSecure(SQLHelper.getDeleteObjectProcess("room", getLabel())); - rooms.remove(getLabel()); - } - /** - * Returns the label of the room. - * This is used to identify the room in various operations. - * @return the label of the room - */ - public String getLabel() { - return label; - } - /** - * Returns the minimum level required to access the room. - * This is used to determine if a student meets the requirements to enter the room. - * @return the minimum level required for access - */ - public int getMinimumLevel() { - return minimumLevel; - } - - public Room setMinimumLevel(int level) throws SQLException { - if (level < 0 || level > 3) throw new IllegalArgumentException("Level " + level + " out of range"); - Server.getInstance().getConnection().executeVoidProcessSecure(SQLHelper.getUpdateObjectProcess("level_of_room", getLabel(), String.valueOf(level))); - rooms.remove(getLabel()); - return getRoom(getLabel()); - } - - @Override - public String toString() { - return "{\"label\": \""+label+ "\", \"minimumLevel\": \"" + minimumLevel + "\"}"; - } - /** - * Adds multiple rooms to the database and the static map. - * This method allows for batch creation of rooms, ensuring that all rooms are added in a single operation. - * @param labels a list of room labels - * @param minimumLevels a list of minimum levels corresponding to each room - * @return a list of Room objects created - * @throws SQLException if there is an error inserting any of the rooms into the database - */ - public static List addAllRooms(List labels, List minimumLevels) throws SQLException { - if (labels.size() != minimumLevels.size()) { - throw new IllegalArgumentException("Labels and minimum levels must have the same size"); - } - List rooms = new ArrayList<>(); - for (int i = 0; i < labels.size(); i++) { - rooms.add(addRoom(labels.get(i), minimumLevels.get(i))); - } - return rooms; - } - /** - * Generates a list of Room objects from a CSV string. - * This method parses the CSV data and creates Room objects for each entry. - * @param csv the CSV string containing room data - * @return an array of Room objects created from the CSV data - */ - public static Room[] generateRoomsFromCSV(String csv) throws SQLException, IllegalArgumentException { - String[] lines = csv.split("\n"); - List labels = new ArrayList<>(); - List minimumLevels = new ArrayList<>(); - for (int i = 0; i < lines.length; i++) { - String[] parts = lines[i].split(","); - if (parts.length != 2) { - throw new IllegalArgumentException("Invalid CSV format for room: " + lines[i]); - } - String label = parts[0].trim(); - int minimumLevel; - try { - minimumLevel = Integer.parseInt(parts[1].trim()); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid minimum level for room: " + lines[i], e); - } - labels.add(label); - minimumLevels.add(minimumLevel); - } - List rooms = Room.addAllRooms(labels, minimumLevels); - return rooms.toArray(new Room[rooms.size()]); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((label == null) ? 0 : label.hashCode()); - result = prime * result + minimumLevel; - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Room other = (Room) obj; - if (label == null) { - if (other.label != null) - return false; - } else if (!label.equals(other.label)) - return false; - if (minimumLevel != other.minimumLevel) - return false; - return true; - } - @Override - public String toJSON() { - return "{\"label\": \""+label+ "\", \"minimumLevel\": \"" + minimumLevel + "\"}"; - } - -} diff --git a/src/main/java/de/igslandstuhl/database/api/SchoolClass.java b/src/main/java/de/igslandstuhl/database/api/SchoolClass.java index 90485d9..73ffd24 100644 --- a/src/main/java/de/igslandstuhl/database/api/SchoolClass.java +++ b/src/main/java/de/igslandstuhl/database/api/SchoolClass.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -157,7 +158,7 @@ public List getStudents() { "get_students_by_class", new String[] {"id"}, String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve student list from database", e); } return studentIds.stream().map(Student::get).toList(); } @@ -168,7 +169,6 @@ public void delete() throws SQLException { try { s.delete(); } catch (SQLException e) { - e.printStackTrace(); throw new IllegalStateException(e); } }); @@ -214,7 +214,7 @@ public static SchoolClass get(int id) { try { return Server.getInstance().processSingleRequest(SchoolClass::fromSQL, "get_class_by_id", SQL_FIELDS, String.valueOf(id)); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolClass with id {} from database", id, e); return null; } } @@ -229,7 +229,7 @@ public static SchoolClass get(String label) { try { return Server.getInstance().processSingleRequest(SchoolClass::fromSQL, "get_class_by_label", SQL_FIELDS, label); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolClass with label '{}' from database", label, e); return null; } } @@ -254,7 +254,7 @@ public static SchoolClass getOrCreate(String label) { try { schoolClass = addClass(label, grade); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to create previously not existing class with label {} and grade {}", label, grade, e); } } return schoolClass; @@ -268,7 +268,7 @@ public static List getAll() { "get_all_classes", new String[] {"id"} ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve a list of all classes from the database", e); } return ids.stream() .map(SchoolClass::get) diff --git a/src/main/java/de/igslandstuhl/database/api/SchoolYear.java b/src/main/java/de/igslandstuhl/database/api/SchoolYear.java index 56d1002..6901840 100644 --- a/src/main/java/de/igslandstuhl/database/api/SchoolYear.java +++ b/src/main/java/de/igslandstuhl/database/api/SchoolYear.java @@ -2,6 +2,8 @@ import java.sql.SQLException; import java.util.*; + +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -124,7 +126,7 @@ public static SchoolYear get(int id) { if (year != null) years.put(id, year); return year; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolYear with id {} from database", id, e); return null; } } @@ -134,7 +136,7 @@ public static SchoolYear get(String label) { return get(Integer.parseInt(fields[0])); }, "get_school_year_by_label", new String[] {"id"}, label); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolYear with label '{}' from database", label, e); return null; } } @@ -156,7 +158,7 @@ public static List getAll() { "get_all_school_years", SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve a list of all school years from the database", e); } return all; } @@ -176,7 +178,7 @@ public static SchoolYear getCurrentYear() { if (year != null) years.put(year.getId(), year); return year; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to load current school year from database", e); return null; } } diff --git a/src/main/java/de/igslandstuhl/database/api/SpecialTask.java b/src/main/java/de/igslandstuhl/database/api/SpecialTask.java index c199912..709c0cf 100644 --- a/src/main/java/de/igslandstuhl/database/api/SpecialTask.java +++ b/src/main/java/de/igslandstuhl/database/api/SpecialTask.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -89,7 +90,7 @@ public static SpecialTask get(int id) { specialTasks.put(id, task); return task; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SpecialTask with id {} from database", id, e); return null; } } @@ -114,7 +115,7 @@ public static List getSpecialTasksByName(String name) { try { Server.getInstance().processRequest(SpecialTask::addToCache, "get_special_tasks_by_name", SQL_FIELDS, name); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SpecialTask with name {} from database", name, e); return new ArrayList<>(); } return specialTasks.values().stream() diff --git a/src/main/java/de/igslandstuhl/database/api/Student.java b/src/main/java/de/igslandstuhl/database/api/Student.java index 79eb120..f7c336f 100644 --- a/src/main/java/de/igslandstuhl/database/api/Student.java +++ b/src/main/java/de/igslandstuhl/database/api/Student.java @@ -13,6 +13,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.api.results.StudentGenerationResult; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -87,11 +88,6 @@ public class Student extends User { */ private final Map currentTopics = new ConcurrentHashMap<>(); - /** - * The current room of the student. - */ - private Room currentRoom = null; - /** * Constructs a new Student. * @@ -174,7 +170,7 @@ public static Student get(int id) { student.fetchTasks(); return student; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Student with id {} from database", id, e); return null; } } @@ -195,7 +191,7 @@ public static Student getByEmail(String email) { } catch (NullPointerException e) { return null; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Student with email {} from database", email, e); return null; } } @@ -215,7 +211,7 @@ public static List getAll() { "get_all_students", SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve student list from database", e); } return studentIDs.stream() .map(Student::get) @@ -223,10 +219,6 @@ public static List getAll() { .collect(Collectors.toList()); } - public static List getByRoom(Room room) { - return students.values().stream().filter((s) -> room.equals(s.getCurrentRoom())).toList(); - } - /** * Registers a new student with a password. * This method creates a new student in the database and returns the created Student object. @@ -256,7 +248,7 @@ public static String[] generatePasswords(int count, int length) { try { Thread.sleep(new Random().nextInt(1,10)); // Sleep to ensure different seeds } catch (InterruptedException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Thread sleep while generating passwords was interrupted", e); } } return passwords; @@ -352,18 +344,6 @@ public String getUsername() { */ public GraduationLevel getGraduationLevel() { return graduationLevel; } - /** - * Returns the student's current room. - * @return the current room - */ - public Room getCurrentRoom() { return currentRoom; } - - /** - * Sets the student's current room. - * @param currentRoom the new room - */ - public void setCurrentRoom(Room currentRoom) { this.currentRoom = currentRoom; } - /** * Returns the set of selected tasks. * @return selected tasks @@ -553,7 +533,6 @@ public String toJSON() { .append("\"selectedTasks\": ").append(selectedTasks).append(",\n") .append("\"completedTasks\": ").append(completedTasks).append(",\n") .append("\"lockedTasks\": ").append(lockedTasks).append(",\n") - .append("\"currentRoom\": ").append(String.valueOf(currentRoom)).append(",\n") .append("\"currentRequests\": {").append(currentRequests.entrySet().stream() .map(entry -> "\"" + entry.getKey() + "\": " + entry.getValue().stream().map((r) -> '"' + r.getGermanTranslation() + '"').toList()) .reduce((a, b) -> a + ", " + b).orElse("")).append("},\n") @@ -603,7 +582,7 @@ private void loadCurrentTopics() { } } } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to load current topics for '{}'", this.email, e); } } diff --git a/src/main/java/de/igslandstuhl/database/api/Subject.java b/src/main/java/de/igslandstuhl/database/api/Subject.java index cffbc48..ac92e36 100644 --- a/src/main/java/de/igslandstuhl/database/api/Subject.java +++ b/src/main/java/de/igslandstuhl/database/api/Subject.java @@ -9,6 +9,7 @@ import java.util.Objects; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -94,7 +95,7 @@ public static Subject get(int id) { subjects.put(id, subject); return subject; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Subject with id {} from database", id, e); return null; } } @@ -116,7 +117,7 @@ public static Subject get(String name) { subjects.put(subject.getId(), subject); return subject; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Subject with name {} from database", name, e); return null; } } @@ -137,7 +138,7 @@ public static List getAll() { SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve subject list from database", e); } return subjectIds.stream() .map(Subject::get) @@ -199,7 +200,7 @@ public List getTopics(int grade) { String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve topic list for subject '{}' in grade {} from database", this.name, grade, e); } return topicIds.stream() .map(Topic::get) @@ -218,7 +219,7 @@ public int[] getGrades() { new String[] {"grade"}, String.valueOf(id)); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve list of available grades for subject '{}' from database", this.name, e); } return grades.stream().mapToInt(Integer::intValue).toArray(); } @@ -242,8 +243,7 @@ public void delete() throws SQLException { try { t.delete(); } catch (SQLException e) { - e.printStackTrace(); - throw new IllegalStateException(e); + throw new IllegalStateException("Failed to delete topic " + t.getName() + " which is necessary to delete subject " + this.name, e); } })); } catch (IllegalStateException e) { diff --git a/src/main/java/de/igslandstuhl/database/api/Task.java b/src/main/java/de/igslandstuhl/database/api/Task.java index b4188c8..9460245 100644 --- a/src/main/java/de/igslandstuhl/database/api/Task.java +++ b/src/main/java/de/igslandstuhl/database/api/Task.java @@ -180,7 +180,7 @@ public static Task get(int id) { tasks.put(id, task); return task; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Task with id {} from database", id, e); return null; } } @@ -194,7 +194,7 @@ public static List getByName(String name) { String[][] table = Server.getInstance().processRequest("get_tasks_by_name", new String[] {"id"}, name); Arrays.stream(table).map(s -> s[0]).map(Integer::parseInt).map(Task::get).forEach((t) -> t.getId()); // Do something because streams are lazy } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Task with name {} from database", name, e); return new ArrayList<>(); } return tasks.values().stream() diff --git a/src/main/java/de/igslandstuhl/database/api/Teacher.java b/src/main/java/de/igslandstuhl/database/api/Teacher.java index db39ccc..1c617b2 100644 --- a/src/main/java/de/igslandstuhl/database/api/Teacher.java +++ b/src/main/java/de/igslandstuhl/database/api/Teacher.java @@ -4,6 +4,7 @@ import java.util.*; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.api.results.TeacherGenerationResult; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -200,7 +201,7 @@ public static Teacher get(int id) { teachersByEmail.put(teacher.getEmail(), teacher); return teacher; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Teacher with id {} from database", id, e); return null; } } @@ -223,7 +224,7 @@ public static Teacher fromEmail(String email) { teachersByEmail.put(email, teacher); return teacher; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Teacher with email {} from database", email, e); return null; } } @@ -243,7 +244,7 @@ public static List getAll() { "get_all_teachers", SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve teacher list from database", e); } return teacherIDs.stream() .map(Teacher::get) @@ -259,7 +260,7 @@ public List getSubjects() { "get_subjects_by_teacher", Subject.SQL_FIELDS, String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve subject list for teacher '{}' from database", this.email, e); } return subjectIds.stream() .map(Subject::get) @@ -312,7 +313,7 @@ public static TeacherGenerationResult[] generateTeachersFromCSV(String csv) thro try { Thread.sleep(new Random().nextInt(100)); // Sleep to ensure unique passwords } catch (InterruptedException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Thread sleep while generating passwords was interrupted", e); } } @@ -337,7 +338,7 @@ private void loadClasses() { "get_teacher_classes", CLASS_FIELDS, String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve class list of teacher '{}' from database", this.email, e); } } diff --git a/src/main/java/de/igslandstuhl/database/api/Topic.java b/src/main/java/de/igslandstuhl/database/api/Topic.java index e56d764..ceb5892 100644 --- a/src/main/java/de/igslandstuhl/database/api/Topic.java +++ b/src/main/java/de/igslandstuhl/database/api/Topic.java @@ -120,7 +120,7 @@ public static Topic get(int id) { topics.put(id, topic); return topic; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Topic with id {} from database", id, e); return null; } } @@ -271,7 +271,7 @@ private void loadTasks() { tasksLevel2 = getTasksByLevel(tasks, TaskLevel.LEVEL2); tasksLevel3 = getTasksByLevel(tasks, TaskLevel.LEVEL3); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get task list for topic '{}' from database", this.name, e); } } private static void addToCache(String[] fields) { @@ -287,7 +287,7 @@ public static List getByName(String name) { try { Server.getInstance().processRequest(Topic::addToCache, "get_topics_by_name", SQL_FIELDS, name); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Topic with name '{}' from database", name, e); return new ArrayList<>(); } return topics.values().stream() @@ -399,6 +399,7 @@ public boolean equals(Object obj) { return true; } public static Topic fromSerialized(String serialized, Subject subject, int grade, int number) throws SerializationException, SQLException { + Application.LOGGER_API.debug("Reading topic from serialized...");; // Gathering general info (topic name and ratio) String[] parts = serialized.split(Application.TITLE_DELIMITER); String[] generalInfo = parts[0].split(Application.TASK_DELIMITER); @@ -427,7 +428,7 @@ public static Topic fromSerialized(String serialized, Subject subject, int grade } topic.loadTasks(); - System.out.println(topic.getTasks()); + Application.LOGGER_API.debug("Loaded tasks for topic {}: {}", topic.getName(), topic.getTasks()); } return topic; } diff --git a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java index 79a3d20..32516bd 100644 --- a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java @@ -3,7 +3,12 @@ import java.io.FileNotFoundException; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.client.dynamic.DynamicFieldType; +import de.igslandstuhl.database.client.dynamic.DynamicHTMLTemplate; import de.igslandstuhl.database.client.navigation.HTMLNavigationTemplate; import de.igslandstuhl.database.client.navigation.NavigationAppearance; import de.igslandstuhl.database.client.navigation.NavigationElement; @@ -12,13 +17,16 @@ import de.igslandstuhl.database.server.resources.ResourceLocation; public interface HTMLTemplate { + public static final Logger LOGGER = LoggerFactory.getLogger(HTMLTemplate.class); public static final ResourceLocation meta = new ResourceLocation("meta", "templates", "templates.json"); public String fill(Map args); private static void register(HTMLTemplate template, String key) { Registry.templateRegistry().register(key, template); } public static void registerAll() { + LOGGER.info("Registering HTML templates..."); NavigationElement.registerAll(); + DynamicHTMLTemplate.registerDynamicElements(); Map json = Server.getInstance().getResourceManager().readJsonResourceMerged(meta); json.keySet().forEach((key) -> { @SuppressWarnings("unchecked") @@ -30,12 +38,14 @@ public static void registerAll() { try { register(new HTMLFileTemplate((String) template.get("path")), key); } catch (FileNotFoundException e) { - System.err.println("Failed to load html template " + key); - e.printStackTrace(); + LOGGER.error("Failed to load html template '{}'", key, e); } break; case "HTMLNavigationTemplate": register(new HTMLNavigationTemplate(NavigationAppearance.valueOf((String) template.get("appearance")), NavigationType.valueOf((String) template.get("navigation_type"))), key); + break; + case "DynamicHTMLTemplate": + register(new DynamicHTMLTemplate(DynamicFieldType.valueOf((String) template.get("dynamic_field_type"))), key); default: break; } diff --git a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java new file mode 100644 index 0000000..7220797 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java @@ -0,0 +1,44 @@ +package de.igslandstuhl.database.client.dynamic; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.server.resources.ResourceLocation; +import de.igslandstuhl.database.utils.RegistryEnum; + +public class DynamicFieldType extends RegistryEnum { + protected DynamicFieldType(Registry registry, String key) { + super(registry, key); + } + + private static final ResourceLocation meta = new ResourceLocation("meta", "dynamic", "dynamic_field_types.json"); + @Override + protected DynamicFieldType[] values(Registry registry) { + List DynamicFieldTypes = registry.stream().toList(); + DynamicFieldType[] arr = new DynamicFieldType[DynamicFieldTypes.size()]; + return DynamicFieldTypes.toArray(arr); + } + + @Override + protected void initValues() { + initUsingJSONMeta(meta); + } + + @Override + protected DynamicFieldType initValue(Registry registry,String key) { + return new DynamicFieldType(registry, key); + } + + public static DynamicFieldType valueOf(String string) { + return RegistryEnum.valueOf(string, DynamicFieldType.class); + } + public static void init() { + try { + RegistryEnum.init(DynamicFieldType.class); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException | SecurityException e) { + throw new ExceptionInInitializerError(e); + } + } +} diff --git a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java new file mode 100644 index 0000000..133f14c --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java @@ -0,0 +1,40 @@ +package de.igslandstuhl.database.client.dynamic; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import com.google.gson.reflect.TypeToken; + +import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.client.HTMLTemplate; +import de.igslandstuhl.database.client.TemplatingPreprocessor; +import de.igslandstuhl.database.server.Server; +import de.igslandstuhl.database.server.resources.ResourceLocation; + +public record DynamicHTMLTemplate(DynamicFieldType type) implements HTMLTemplate { + @Override + public String fill(Map args) { + return Registry.dynamicTemplatesRegistry().stream(type) + .map(Registry.templateRegistry()::get) + .map((t) -> t.fill(args)) + .map(arg0 -> { + try { + return TemplatingPreprocessor.getInstance().executeTemplating(arg0); + } catch (IOException e) { + HTMLTemplate.LOGGER.error("Failed filling template '{}'", arg0, e); + return ""; + } + }) + .reduce("", (s1, s2) -> s1 + "\n" + s2); + } + public static final ResourceLocation meta = new ResourceLocation("meta", "dynamic", "dynamic_elements.json"); + public static void registerDynamicElements() { + List> elements = Server.getInstance().getResourceManager().readJsonListMerged(meta, new TypeToken>>() {}); + elements.forEach((m) -> { + DynamicFieldType type = DynamicFieldType.valueOf(m.get("type")); + String template = m.get("template"); + Registry.dynamicTemplatesRegistry().register(type, template); + }); + } +} \ No newline at end of file diff --git a/src/main/java/de/igslandstuhl/database/holidays/Holiday.java b/src/main/java/de/igslandstuhl/database/holidays/Holiday.java index 66ff791..91ff9d5 100644 --- a/src/main/java/de/igslandstuhl/database/holidays/Holiday.java +++ b/src/main/java/de/igslandstuhl/database/holidays/Holiday.java @@ -16,6 +16,9 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -25,6 +28,7 @@ public final class Holiday { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); private static final String API_URL = "https://www.mehr-schulferien.de/api/v2.1/schools/66849-integrierte-gesamtschule-am-na/periods"; private static final String SUMMER_HOLIDAY_ID = "Sommer"; + private static final Logger LOGGER = LoggerFactory.getLogger(Holiday.class); private final int id; private final String name; @@ -138,7 +142,6 @@ public static Holiday[] holidaysInterval(Instant start, Instant end) { } catch (URISyntaxException | IOException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { - e.printStackTrace(); throw new IllegalStateException(e); } } @@ -167,6 +170,7 @@ public static int getActualWeek() { return (int) SchoolWeek.getAll(getLastSummerHoliday().getEnd(), Instant.now(), ZoneId.of("UTC")).stream().filter(SchoolWeek::noSchoolUTC).count(); } public static void setupCurrentSchoolYear() throws SQLException { + LOGGER.info("Trying to set up current school year..."); String name = getLastSummerHoliday().getEnd().toString().substring(0, 4) + "/" + getNextSummerHoliday().getStart().toString().substring(0, 4); int totalWeeks = getTotalWeeks(); int actualWeek = getActualWeek(); diff --git a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java b/src/main/java/de/igslandstuhl/database/plugins/Plugin.java deleted file mode 100644 index 08c8317..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java +++ /dev/null @@ -1,119 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.util.List; - -import de.igslandstuhl.database.plugins.config.PluginConfig; -import de.igslandstuhl.database.plugins.config.PluginSetting; - -public abstract class Plugin { - private String id; - private String name; - private String description; - - private boolean enabled; - private boolean initialized = false; - - public Plugin() { - this.enabled = false; - } - - void init(String id, String name, String description) { - if (initialized) throw new IllegalStateException("Plugin already initialized"); - this.id = id; - this.name = name; - this.description = description; - this.initialized = true; - } - void init(PluginDescription description) { - init(description.id(), description.name(), description.description()); - } - - public String getId() { - return id; - } - public String getName() { - return name; - } - public String getDescription() { - return description; - } - public boolean isEnabled() { - return enabled; - } - - public String toJSON() { - StringBuilder sb = new StringBuilder(); - sb.append("{"); - sb.append("\"id\":\"").append(id).append("\","); - sb.append("\"name\":\"").append(name).append("\","); - sb.append("\"description\":\"").append(description).append("\","); - sb.append("\"enabled\":").append(enabled).append(","); - sb.append("\"config\":").append(getConfig().toJSON()); - sb.append("}"); - return sb.toString(); - } - - /** - * Returns the config of this plugin. - * This should never be null, as it will break the plugin lifecycle otherwise. - * @return the config - */ - public abstract PluginConfig getConfig(); - - protected abstract void onEnable(); - protected abstract void onDisable(); - protected abstract void onLoad(); - - public void enable() { - if (enabled) return; - onEnable(); - enabled = true; - } - public void disable() { - if (!enabled) return; - onDisable(); - enabled = false; - } - public void toggle() { - if (enabled) { - disable(); - } else { - enable(); - } - getConfig().save(); - } - void load() { - onLoad(); - } - - static class DummyModule extends Plugin { - private final PluginConfig config; - public DummyModule(String id, String name, String description, List> settings) { - init(id, name, description); - config = new PluginConfig(this, settings) { - - }; - } - - @Override - public PluginConfig getConfig() { - return config; - } - - @Override - protected void onEnable() { - // Dummy enable logic - } - - @Override - protected void onDisable() { - // Dummy disable logic - } - - @Override - protected void onLoad() { - // Dummy load logic - } - } - -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java b/src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java deleted file mode 100644 index 1a2d7eb..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java +++ /dev/null @@ -1,7 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.util.List; - -public record PluginDescription(String id, String name, String description, String main, List depends) { - -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java deleted file mode 100644 index 85bf0a3..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java +++ /dev/null @@ -1,190 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.yaml.snakeyaml.Yaml; - -import de.igslandstuhl.database.Registry; - -public class PluginLoader { - private final List pluginInfos = new ArrayList<>(); - public List getPluginInfos() { - return pluginInfos; - } - private static final PluginLoader INSTANCE = new PluginLoader(); - public static PluginLoader getInstance() { - return INSTANCE; - } - private PluginLoader() {} - - private Map loadYaml(URLClassLoader classLoader) { - try (InputStream is = classLoader.getResourceAsStream("plugin.yml")) { - if (is == null) return null; - - Yaml yaml = new Yaml(); - return yaml.load(is); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - public PreLoadedPlugin loadPluginFromJar(File jarFile) { - URLClassLoader classLoader; - URLClassLoader resourceLoader; - try { - classLoader = new URLClassLoader( - new URL[]{jarFile.toURI().toURL()}, - getClass().getClassLoader() - ); - resourceLoader = new URLClassLoader( - new URL[]{jarFile.toURI().toURL()}, - null - ); - } catch (MalformedURLException e) { - e.printStackTrace(); - return null; - } - try { - - Map yaml = loadYaml(classLoader); - if (yaml == null) { - System.err.println("No plugin.yml found in " + jarFile.getName()); - classLoader.close(); - return null; - } - - String mainClassName = (String) yaml.get("main"); - String id = (String) yaml.get("id"); - if (id == null || mainClassName == null) { - throw new IllegalStateException("Invalid plugin.yml in " + jarFile.getName() + ": you must define id and main"); - } - String name = (String) yaml.getOrDefault("name", id); - String description = (String) yaml.getOrDefault("description", ""); - - Object dependsObj = yaml.get("depends"); - List depends = new ArrayList<>(); - - if (dependsObj instanceof List) { - for (Object o : (List) dependsObj) { - if (o instanceof String s) { - depends.add(s); - } - } - } - - Class clazz = classLoader.loadClass(mainClassName); - - if (!Plugin.class.isAssignableFrom(clazz)) { - throw new IllegalStateException("Main class does not extend Plugin"); - } - - return new PreLoadedPlugin(new PluginDescription(id, name, description, mainClassName, depends), clazz, classLoader, resourceLoader); - - } catch (Exception e) { - e.printStackTrace(); - try { - classLoader.close(); - } catch (IOException e1) { - System.out.println("FAILED to close class loader"); - e1.printStackTrace(); - } - return null; - } - } - public void load(PreLoadedPlugin preload) { - Plugin plugin; - try { - plugin = (Plugin) preload.clazz().getDeclaredConstructor().newInstance(); - plugin.init(preload.description()); - registerPlugin(plugin); - plugin.load(); - if (plugin.getConfig() == null) { - throw new NullPointerException("Plugin must have a config"); - } - } catch (Exception e) { - System.err.println("Failed to load plugin: " + preload.description().id()); - pluginInfos.remove(preload); - if (Registry.pluginRegistry().get(preload.description().id()) != null) Registry.pluginRegistry().unregister(preload.description().id()); - e.printStackTrace(); - } - } - public void preloadAllPlugins(File folder) { - File[] jars = folder.listFiles((dir, name) -> name.endsWith(".jar")); - if (jars == null) return; - - List plugins = new ArrayList<>(); - - for (File jar : jars) { - PreLoadedPlugin m = loadPluginFromJar(jar); - if (m != null) { - plugins.add(m); - } - } - - // Check for duplicate ids - Set ids = new HashSet<>(); - for (PreLoadedPlugin p : plugins) { - if (!ids.add(p.description().id())) { - throw new IllegalStateException("Duplicate module id: " + p.description().id()); - } - } - - PluginSort.sortPlugins(plugins).forEach((p) -> pluginInfos.add(p)); - } - public void loadAllPlugins(File folder) { - pluginInfos.forEach(this::load); - } - public void enablePlugins() { - pluginInfos.forEach((p) -> { - Plugin plugin = Registry.pluginRegistry().get(p.description().id()); - if (plugin.getConfig().isEnabledOnStart()) { - plugin.enable(); - } - }); - } - public void unloadPlugins() { - Collections.reverse(pluginInfos); - pluginInfos.forEach((p) -> { - Plugin plugin = Registry.pluginRegistry().get(p.description().id()); - plugin.getConfig().save(); - if (plugin != null && plugin.isEnabled()) { - plugin.disable(); - } - Registry.pluginRegistry().unregister(plugin.getId()); - - try { - p.classLoader().close(); - p.resourceLoader().close(); - } catch (IOException e) { - throw new RuntimeException("Problem while unloading", e); - } - }); - pluginInfos.clear(); - } - - - - private void registerPlugin(Plugin plugin) { - if (Registry.pluginRegistry().keyStream().anyMatch(plugin.getId()::equals)) { - throw new IllegalStateException("Duplicate module id: " + plugin.getId()); - } - Registry.pluginRegistry().register(plugin.getId(), plugin); - } - public void preloadPlugins() { - preloadAllPlugins(new File("plugins")); - } - public void registerPlugins() { - loadAllPlugins(new File("plugins")); - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java index 77f46fc..2cb6e16 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java @@ -14,6 +14,7 @@ import de.igslandstuhl.database.server.resources.CoreResourceProvider; import de.igslandstuhl.database.server.resources.ResourceLocation; +import de.igslandstuhl.database.server.resources.ResourceManager; import de.igslandstuhl.database.server.resources.ResourceProvider; public class PluginResourceProvider implements ResourceProvider { @@ -24,6 +25,7 @@ public InputStream open(ResourceLocation location) { for (PreLoadedPlugin module : PluginLoader.getInstance().getPluginInfos()) { ClassLoader cl = module.resourceLoader(); + if (cl == null) continue; // built-in plugin InputStream stream = cl.getResourceAsStream(path); if (stream != null) { @@ -41,6 +43,7 @@ public List openAll(ResourceLocation location) { for (PreLoadedPlugin module : PluginLoader.getInstance().getPluginInfos()) { ClassLoader cl = module.resourceLoader(); + if (cl == null) continue; // built-in plugin InputStream stream = cl.getResourceAsStream(path); if (stream != null) { @@ -57,8 +60,8 @@ public Collection list(Pattern pattern) { // Virtual root – no real filesystem access needed final Path virtualRoot = Paths.get("").toAbsolutePath().normalize(); - for (PreLoadedPlugin module : PluginLoader.getInstance().getPluginInfos()) { - try (ZipFile zip = new ZipFile(new File(module.resourceLoader().getURLs()[0].toURI()))) { + for (PreLoadedPlugin plugin : PluginLoader.getInstance().getPluginInfos()) { + try (ZipFile zip = new ZipFile(new File(plugin.resourceLoader().getURLs()[0].toURI()))) { Enumeration entries = zip.entries(); @@ -80,7 +83,7 @@ public Collection list(Pattern pattern) { } } catch (Exception e) { - e.printStackTrace(); + ResourceManager.LOGGER.error("Failed to get resource locations of pattern {} from plugin '{}'", pattern.pattern(), plugin.description().id()); } } diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginSort.java b/src/main/java/de/igslandstuhl/database/plugins/PluginSort.java deleted file mode 100644 index 05f59d4..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginSort.java +++ /dev/null @@ -1,57 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class PluginSort { - private PluginSort() {} - private static void visit( - PreLoadedPlugin plugin, - Map map, - List sorted, - Set visited, - Set visiting - ) { - String id = plugin.description().id(); - - if (visited.contains(id)) return; - - if (visiting.contains(id)) { - throw new IllegalStateException("Circular dependency detected: " + id); - } - - visiting.add(id); - - for (String dep : plugin.description().depends()) { - PreLoadedPlugin dependency = map.get(dep); - if (dependency == null) { - throw new IllegalStateException("Missing dependency: " + dep + " for " + id); - } - visit(dependency, map, sorted, visited, visiting); - } - - visiting.remove(id); - visited.add(id); - sorted.add(plugin); - } - public static List sortPlugins(List plugins) { - Map map = new HashMap<>(); - for (PreLoadedPlugin m : plugins) { - map.put(m.description().id(), m); - } - - List sorted = new ArrayList<>(); - Set visited = new HashSet<>(); - Set visiting = new HashSet<>(); - - for (PreLoadedPlugin m : plugins) { - visit(m, map, sorted, visited, visiting); - } - - return sorted; - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java b/src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java deleted file mode 100644 index dcb82df..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java +++ /dev/null @@ -1,12 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.net.URLClassLoader; - -record PreLoadedPlugin ( - PluginDescription description, - Class clazz, - URLClassLoader classLoader, - URLClassLoader resourceLoader -) { - -} \ No newline at end of file diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java deleted file mode 100644 index 1e368ff..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java +++ /dev/null @@ -1,31 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -public class BoolSetting extends PluginSetting { - public BoolSetting(String key, String name, String description, boolean defaultValue) { - super(key, name, description, defaultValue); - } - - public void toggle() { - setValue(!getValue()); - } - public void enable() { - setValue(true); - } - public void disable() { - setValue(false); - } - public boolean isEnabled() { - return getValue(); - } - - @Override - public String toJSON() { - return "{" + - "\"key\":\"" + getKey() + "\"," + - "\"name\":\"" + getName() + "\"," + - "\"description\":\"" + getDescription() + "\"," + - "\"defaultValue\":" + getDefaultValue() + "," + - "\"value\":" + getValue() + - "}"; - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java deleted file mode 100644 index 61c88c3..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java +++ /dev/null @@ -1,134 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; - -import de.igslandstuhl.database.plugins.Plugin; - -public abstract class PluginConfig { - private final T plugin; - private final BoolSetting[] boolSettings; - - private final File configFile; - private boolean enabledOnStart; - - public PluginConfig(T plugin, PluginSetting... moduleSettings) { - this.plugin = plugin; - List boolSettings = Arrays.stream(moduleSettings).filter((s) -> s instanceof BoolSetting).map((s) -> (BoolSetting) s).toList(); - this.boolSettings = boolSettings.toArray(new BoolSetting[boolSettings.size()]); - this.configFile = new File("plugins/config", plugin.getId() + ".json"); - load(); - } - - public PluginConfig(T plugin, List> moduleSettings) { - this.plugin = plugin; - List boolSettings = moduleSettings.stream().filter((s) -> s instanceof BoolSetting).map((s) -> (BoolSetting) s).toList(); - this.boolSettings = boolSettings.toArray(new BoolSetting[boolSettings.size()]); - this.configFile = new File("plugins/config", plugin.getId() + ".json"); - load(); - } - - public T getPlugin() { - return plugin; - } - public boolean isEnabledOnStart() { - return enabledOnStart; - } - - private BoolSetting findBoolSetting(String key) { - return Arrays.stream(boolSettings) - .filter((s) -> s.getKey().equals(key)) - .findAny().orElseThrow(); - } - - public boolean getBool(String key) { - return findBoolSetting(key).getValue(); - } - - public void setBool(String key, boolean value) { - findBoolSetting(key).setValue(value); - save(); - } - public void enableSetting(String key) { - findBoolSetting(key).enable(); - save(); - } - public void disableSetting(String key) { - findBoolSetting(key).disable(); - save(); - } - public void toggleSetting(String key) { - findBoolSetting(key).toggle(); - save(); - } - - private JsonObject valuesJSON() { - JsonObject values = new JsonObject(); - for (BoolSetting s : boolSettings) { - values.addProperty(s.getKey(), s.getValue()); - } - return values; - } - public String toJSON() { - StringBuilder builder = new StringBuilder("{"); - builder.append("\"settings\": {") - .append("\"bools\": ["); - for (int i = 0; i < boolSettings.length; i++) { - builder.append(boolSettings[i].toJSON()); - if (i < boolSettings.length - 1) { - builder.append(", "); - } - } - builder - .append("]}, ") - .append("\"values\": ") - .append((new Gson()).toJson(valuesJSON())) - .append("}"); - return builder.toString(); - } - - // Persistence - public void save() { - if (configFile.getParentFile() != null && !configFile.getParentFile().exists()) { - configFile.getParentFile().mkdirs(); - } - try (FileWriter writer = new FileWriter(configFile)) { - JsonObject root = new JsonObject(); - root.add("values", valuesJSON()); - root.addProperty("enabled", plugin.isEnabled()); - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - gson.toJson(root, writer); - } catch (IOException e) { - e.printStackTrace(); - } - } - public void load() { - if (!configFile.exists()) return; - try (FileReader reader = new FileReader(configFile)) { - Gson gson = new Gson(); - JsonObject root = gson.fromJson(reader, JsonObject.class); - - JsonObject values = root.getAsJsonObject("values"); - if (values != null) { - for (BoolSetting s : boolSettings) { - if (values.has(s.getKey())) { - s.setValue(values.get(s.getKey()).getAsBoolean()); - } - } - } - enabledOnStart = root.get("enabled").getAsBoolean(); - - } catch (IOException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java deleted file mode 100644 index 0d632fa..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java +++ /dev/null @@ -1,49 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -public class PluginSetting { - private final String key; - private final String name; - private final String description; - private final T defaultValue; - private T value; - - PluginSetting(String key, String name, String description, T defaultValue) { - this.key = key; - this.name = name; - this.description = description; - this.defaultValue = defaultValue; - this.value = defaultValue; - } - - public String getKey() { - return key; - } - public String getName() { - return name; - } - public String getDescription() { - return description; - } - public T getDefaultValue() { - return defaultValue; - } - - public T getValue() { - return value; - } - - public void setValue(T value) { - this.value = value; - } - - public String toJSON() { - return "{" + - "\"key\":\"" + key + "\"," + - "\"name\":\"" + name + "\"," + - "\"description\":\"" + description + "\"," + - "\"defaultValue\":\"" + defaultValue + "\"," + - "\"value\":\"" + value + "\"" + - "}"; - } - -} diff --git a/src/main/java/de/igslandstuhl/database/server/Server.java b/src/main/java/de/igslandstuhl/database/server/Server.java index a4b2f98..4901f49 100644 --- a/src/main/java/de/igslandstuhl/database/server/Server.java +++ b/src/main/java/de/igslandstuhl/database/server/Server.java @@ -3,25 +3,21 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.HashSet; import java.util.LinkedList; import java.util.List; -import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import org.apache.commons.codec.digest.DigestUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import de.igslandstuhl.database.Application; -import de.igslandstuhl.database.api.Room; -import de.igslandstuhl.database.api.SchoolClass; -import de.igslandstuhl.database.api.Student; -import de.igslandstuhl.database.api.Subject; -import de.igslandstuhl.database.api.Teacher; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.resources.ResourceManager; import de.igslandstuhl.database.server.sql.SQLHelper; import de.igslandstuhl.database.server.sql.SQLiteConnection; +import de.igslandstuhl.database.server.webserver.handlers.get.SQLRequestHandler; /** * Represents the main server class that handles all incoming requests and manages the database connection. @@ -85,6 +81,8 @@ public ResourceManager getResourceManager() { return resourceManager; } + public static final Logger LOGGER = LoggerFactory.getLogger(Server.class); + /** * Private constructor to initialize the server instance. * This constructor sets up the database connection and initializes the web server. @@ -157,15 +155,15 @@ public void processRequest(Consumer callback, String request, String[] callback.accept(results.toArray(resultArr)); } } catch (SQLException e) { - e.printStackTrace(); + LOGGER.error("Failed to process sql request {} with args {}", request, args, e); throw new IllegalStateException(e); } - }); + }, "SQL Request Subroutine"); subroutine.start(); try { subroutine.join(); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Request subroutine was interrupted", e); throw new IllegalStateException(e); } } finally { @@ -206,45 +204,7 @@ public boolean isValidUser(String username, String password) { */ public String getSQLResource(String username, String resource) { resource = resource.intern(); - if (resource.equals("mydata")) { - User user = User.getUser(username); - return user.toJSON(); - } else if (resource.equals("rooms")) { - return new HashSet<>(Room.getRooms().values()).toString(); - } else if (resource.equals("mysubjects")) { - User user = User.getUser(username); - if (user instanceof Student student) { - return student.getSchoolClass().getSubjects().toString(); - } else if (user instanceof Teacher teacher) { - return teacher.getSubjects().toString(); - } else { - return null; - } - } else if (resource.equals("myclasses")) { - User user = User.getUser(username); - if (user instanceof Teacher teacher) { - Set classIDs = teacher.getClassIds(); - Set classes = new HashSet<>(); - for (Integer classID : classIDs) { - classes.add("{\"classId\": " + classID + ", \"name\": \"" + SchoolClass.get(classID).getLabel() + "\"}"); - } - return classes.toString(); - } else { - return null; - } - } else if (resource.equals("teachers")) { - return new HashSet<>(Teacher.getAll()).toString(); - } else if (resource.equals("students")) { - return new HashSet<>(Student.getAll()).toString(); - } else if (resource.equals("subjects")) { - return new HashSet<>(Subject.getAll()).toString(); - } else if (resource.equals("classes")) { - return new HashSet<>(SchoolClass.getAll()).toString(); - } else if (resource.equals("all-student-results")) { - return Student.getAllResultsCSV(); - } else { - return null; - } + return SQLRequestHandler.getResource(resource, User.getUser(username)); } @Override diff --git a/src/main/java/de/igslandstuhl/database/server/WebServer.java b/src/main/java/de/igslandstuhl/database/server/WebServer.java index 7091055..570f317 100644 --- a/src/main/java/de/igslandstuhl/database/server/WebServer.java +++ b/src/main/java/de/igslandstuhl/database/server/WebServer.java @@ -9,6 +9,10 @@ import java.nio.charset.StandardCharsets; import javax.net.ssl.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; @@ -40,6 +44,7 @@ public class WebServer implements Runnable { public static final int SESSION_DURATION = 21600; // six hours public static final int MAXIMUM_INACTIVITY_DURATION = 3600; // An hour public static final int RATELIMIT = 60; + public static final Logger LOGGER = LoggerFactory.getLogger(Server.class); private volatile boolean running; private final SSLServerSocket serverSocket; @@ -112,7 +117,7 @@ public void run() { } } } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("Failed to handle client {}", clientIp, e); } finally { try { clientSocket.close(); } catch (IOException ignored) {} } @@ -233,7 +238,7 @@ public void start() { public void stop() { running = false; - try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } + try { serverSocket.close(); } catch (IOException e) { LOGGER.error("Failed to close server socket", e); } clientPool.shutdownNow(); } @@ -245,8 +250,7 @@ public void run() { clientPool.submit(new ClientHandler(clientSocket)); } catch (IOException e) { if (running) { - System.err.println("Error while accepting client"); - e.printStackTrace(); + LOGGER.error("Unexpected Exception while accepting client", e); } } } diff --git a/src/main/java/de/igslandstuhl/database/server/commands/Command.java b/src/main/java/de/igslandstuhl/database/server/commands/Command.java index 795833d..6b07495 100644 --- a/src/main/java/de/igslandstuhl/database/server/commands/Command.java +++ b/src/main/java/de/igslandstuhl/database/server/commands/Command.java @@ -5,6 +5,9 @@ import java.util.List; import java.util.Random; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.*; import de.igslandstuhl.database.server.Server; @@ -12,6 +15,7 @@ @FunctionalInterface public interface Command { + public static final Logger LOGGER = LoggerFactory.getLogger(Command.class); public String execute(String[] args); public default CommandDescription getDescription() { return Registry.commandDescriptionRegistry().get(Registry.commandDescriptionRegistry() @@ -25,7 +29,7 @@ public static String executeCommand(String command, String[] args) { } catch (NullPointerException e) { return "Command not found: " + command; } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("Failed to execute command '{}'", command, e); return ""; } } @@ -34,8 +38,9 @@ public static void registerCommand(String name, Command command, CommandDescript Registry.commandDescriptionRegistry().register(name, description); } public static void registerCommands() { + LOGGER.info("Registering commands..."); registerCommand("exit", (args) -> { - System.out.println("Exiting..."); + LOGGER.info("Program exit through command;exiting..."); System.exit(0); return ""; }, new CommandDescription("exit", "Exits the application", "exit")); @@ -78,71 +83,6 @@ public static void registerCommands() { return String.valueOf(level.getRatio() * 100) + "%"; }, new CommandDescription("get-level-ratio", "Gets the ratio of a task level", "get-level-ratio [level]")); - // Room commands - registerCommand("list-rooms", (args) -> { - try { - Room.fetchAll(); - } catch (SQLException e) { - return "Error while trying to access database:\n" + CommonUtils.getStacktrace(e); - } - return Room.getRooms().keySet().stream().reduce("Rooms:", (s1, s2) -> s1 + "\n" + s2); - }, new CommandDescription("list-rooms", "Lists all available rooms", "list-rooms")); - registerCommand("get-room-level", (args) -> { - if (args.length < 1) return "Usage: get-room-level [room]"; - Room room = Room.getRoom(argsPart(args, 0, args.length)); - if (room == null) return "Room not found. Try list-rooms for a list of available rooms"; - return "Room " + room.getLabel() + " has access level " + room.getMinimumLevel(); - }, new CommandDescription("get-room-level", "Gets the minimum level required to access a room", "get-room-level [room]")); - registerCommand("set-room-level", (args) -> { - if (args.length < 2) return "Usage: set-room-level [room] [level]"; - Room room = Room.getRoom(argsPart(args, 0, args.length-1)); - if (room == null) return "Room not found. Try list-rooms for a list of available rooms"; - int level; - try { - level = Integer.parseInt(args[args.length - 1]); - } catch (NumberFormatException e) { - return args[1] + " is not a valid number."; - } - try { - room.setMinimumLevel(level); - } catch (SQLException e) { - return "Error while trying to access database: \n" + CommonUtils.getStacktrace(e); - } catch (IllegalArgumentException e) { - return e.getMessage(); - } - return "Successfully changed room level"; - }, new CommandDescription("set-room-level", "Sets the minimum level required to access a room", "set-room-level [room] [level]")); - registerCommand("add-room", (args) -> { - if (args.length < 2) return "Usage: add-room [room] [level]"; - if (Room.getRoom(args[0]) != null) return "Room already present"; - - try { - String label = argsPart(args, 0, args.length-1); - int level = Integer.parseInt(args[args.length-1]); - - Room.addRoom(label, level); - } catch (NumberFormatException e) { - return args[args.length - 1] + " is not a valid number."; - } catch (IllegalArgumentException e) { - return e.getMessage(); - } catch (SQLException e) { - throw new IllegalStateException(e); - } - return "Room successfully added"; - }, new CommandDescription("add-room", "Adds a new room", "add-room [room] [level]")); - registerCommand("remove-room", (args) -> { - if (args.length < 1) return "Usage: remove-room [room]"; - - Room room = Room.getRoom(argsPart(args, 0, args.length)); - try { - room.delete(); - } catch (SQLException e) { - return "Error while trying to access database: \n" + CommonUtils.getStacktrace(e); - } - return "Room successfully deleted"; - }, new CommandDescription("remove-room", "Removes a room", "remove-room [room]")); - - // class commands registerCommand("list-classes", (args) -> { return SchoolClass.getAll().stream().map(SchoolClass::getLabel).reduce("Classes:", (s1,s2) -> s1 + "\n" + s2); diff --git a/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java b/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java index 1c67d53..005b25c 100644 --- a/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java @@ -119,7 +119,7 @@ private Collection getResourcesFromDirectory(final Path direct } }); } catch (IOException e) { - e.printStackTrace(); + ResourceManager.LOGGER.error("Failed to get resources from directory '{}'", directory.toString(), e); return retval; } return retval; diff --git a/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java b/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java index 7c2f9c5..53de6d3 100644 --- a/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java @@ -58,7 +58,7 @@ public Collection list(Pattern pattern) { } }); } catch (IOException e) { - e.printStackTrace(); + ResourceManager.LOGGER.error("Failed to get resource locations of pattern {} from file root '{}'", pattern.pattern(), root, e); } return result; diff --git a/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java b/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java index 567495c..9f26871 100644 --- a/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java +++ b/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java @@ -19,6 +19,9 @@ import java.util.regex.Pattern; import java.util.stream.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -29,6 +32,7 @@ * Manages Resources in the application */ public class ResourceManager { + public static final Logger LOGGER = LoggerFactory.getLogger(ResourceManager.class); private final List providers; public ResourceManager(ResourceProvider... providers) { this.providers = Arrays.asList(providers); diff --git a/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java b/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java index c4bdf58..97f54bb 100644 --- a/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java +++ b/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java @@ -2,7 +2,7 @@ public class SQLMultipleAccessesException extends RuntimeException { public SQLMultipleAccessesException() {} - public SQLMultipleAccessesException(String msg) { super(msg); System.out.println("Test");} + public SQLMultipleAccessesException(String msg) { super(msg); } public SQLMultipleAccessesException(Throwable cause) { super(cause); } public SQLMultipleAccessesException(String msg, Throwable cause) { super(msg, cause); } } diff --git a/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java b/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java index a39a389..03f2364 100644 --- a/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java +++ b/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java @@ -10,6 +10,9 @@ import java.sql.Statement; import java.util.regex.Pattern; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.utils.TrackingReadWriteLock; @@ -38,6 +41,8 @@ public Connection getSQLConnection() { private final TrackingReadWriteLock lock = new TrackingReadWriteLock(); + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); + /** * Creates the necessary tables in the database by executing SQL scripts. * This method reads SQL files matching the pattern "./tables/*.sql" (regex: .*tables.+\\.sql) and executes their content. @@ -75,7 +80,7 @@ public PreparedStatement prepareStatement(String sql) throws SQLException { public ResultSet executeStatementQuerySecure(PreparedStatement statement) throws SQLException { lock.readLock().lock(); try (statement) { - return statement.executeQuery(); + return statement.executeQuery(); } finally { lock.readLock().unlock(); } @@ -157,6 +162,7 @@ public void closePendingStatement() throws SQLException { * @throws SQLException if an SQL error occurs during table creation */ public void createTables() throws SQLException { + LOGGER.debug("Creating Database Tables..."); executeVoidProcessSecure(this::createTables); } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java b/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java index f287017..53ca04a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java @@ -5,6 +5,9 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.Server; @@ -15,6 +18,7 @@ * It determines whether a user has access to a specific resource based on predefined rules. */ public class AccessManager { + private static final Logger LOGGER = LoggerFactory.getLogger(AccessManager.class); private static final AccessManager INSTANCE = new AccessManager(); public static AccessManager getInstance() { return INSTANCE; @@ -60,6 +64,7 @@ public static AccessManager getInstance() { @SuppressWarnings("unchecked") private AccessManager() { + LOGGER.info("Setting up AccessManager..."); ResourceLocation metaLocation = new ResourceLocation("meta", "paths", "spaces.json"); String userSpace = "user"; String teacherSpace = "teacher"; @@ -71,6 +76,7 @@ private AccessManager() { String[] teacherLocations = {}; String[] adminLocations = {"students", "teachers", "classes"}; try { + LOGGER.debug("Trying to read spaces metadata..."); Map pathData = Server.getInstance().getResourceManager().readJsonResourceAsMap(metaLocation); List publicSpacesList = (List) pathData.get("public_spaces"); List publicLocationsList = (List) pathData.get("public_locations"); @@ -86,8 +92,7 @@ private AccessManager() { teacherLocations = teacherLocationsList.toArray(new String[teacherLocationsList.size()]); adminLocations = adminLocationsList.toArray(new String[adminLocationsList.size()]); } catch (IOException e) { - System.err.println("Could not read spaces metadata!"); - e.printStackTrace(); + LOGGER.error("Could not read spaces metadata!", e); } finally { USER_SPACE = userSpace; TEACHER_SPACE = teacherSpace; diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java b/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java index 3c11767..075401d 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java @@ -4,16 +4,22 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.resources.ResourceLocation; import de.igslandstuhl.database.server.webserver.requests.RequestType; public record WebPath(RequestType type, String handlerType, List namespaces, String context, AccessLevel accessLevel) { + private static final Logger LOGGER = LoggerFactory.getLogger(WebPath.class); + public static void registerPath(String path, RequestType type, String handlerType, List namespaces, String context, AccessLevel accessLevel) { Registry.webPathRegistry().register(path, new WebPath(type, handlerType, namespaces, context, accessLevel)); } public static void registerPaths() throws IOException { + LOGGER.info("Registering get request paths..."); if (Registry.webPathRegistry().stream().count() > 0) return; // already registered ResourceLocation metaLocation = new ResourceLocation("meta", "paths", "get_paths.json"); Map pathData = Server.getInstance().getResourceManager().readJsonResourceMerged(metaLocation); diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java index ff9e130..befe33a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java @@ -2,6 +2,9 @@ import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.Server; @@ -15,6 +18,7 @@ import de.igslandstuhl.database.utils.ThrowingFunction; public class GetRequestHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(GetRequestHandler.class); private static final GetRequestHandler instance = new GetRequestHandler(); public static GetRequestHandler getInstance() { return instance; @@ -65,6 +69,7 @@ public static GetResponse handlePluginRequest(GetRequest request) { } public final void registerHandlers() { + LOGGER.info("Registering Get Request Handlers..."); if (Registry.getRequestHandlerRegistry().stream().count() > 0) return; // already registered List getPaths = Registry.webPathRegistry().keyStream().filter((p) -> Registry.webPathRegistry().get(p).type() == RequestType.GET).toList(); for (String path : getPaths) { diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java index 2477732..d64604b 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java @@ -1,5 +1,8 @@ package de.igslandstuhl.database.server.webserver.handlers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.webserver.AccessLevel; @@ -12,6 +15,7 @@ import de.igslandstuhl.database.utils.ThrowingFunction; public class HttpHandler { + public static final Logger LOGGER = LoggerFactory.getLogger(HttpHandler.class); private final String path; private final AccessLevel accessLevel; private final ThrowingFunction handler; @@ -31,13 +35,13 @@ public HttpResponse handleHttpRequest(Rq request) { if (!accessLevel.hasAccess(sessionManager.getSessionUser(request))) { return HttpResponse.error(request, Status.UNAUTHORIZED); } else if (!path.equals(request.getPath().split("\\?")[0])) { - System.err.println("Wrong path for HTTP handler: " + handler + ", path: " + request.getPath()); + LOGGER.error("Wrong path for HTTP handler: path {} does not match handler path {}", request.getPath(), path); return HttpResponse.error(request, Status.INTERNAL_SERVER_ERROR); } else { try { return handler.apply(request); } catch (Throwable t) { - t.printStackTrace(); + LOGGER.error("Failed to apply HTTP handler", t); return HttpResponse.error(request, Status.INTERNAL_SERVER_ERROR); } } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java index 6b8d4e3..a60266a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java @@ -14,13 +14,14 @@ import org.owasp.html.PolicyFactory; import org.owasp.html.Sanitizers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.gson.reflect.TypeToken; import de.igslandstuhl.database.Application; import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.APIObject; -import de.igslandstuhl.database.api.Room; import de.igslandstuhl.database.api.SchoolClass; import de.igslandstuhl.database.api.Student; import de.igslandstuhl.database.api.Subject; @@ -30,6 +31,11 @@ import de.igslandstuhl.database.api.Topic; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.api.results.GenerationResult; +import de.igslandstuhl.database.plugins.config.BoolSetting; +import de.igslandstuhl.database.plugins.config.IntSetting; +import de.igslandstuhl.database.plugins.config.PluginConfig; +import de.igslandstuhl.database.plugins.config.PluginSetting; +import de.igslandstuhl.database.plugins.config.ShortAnswerSetting; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.webserver.AccessLevel; import de.igslandstuhl.database.server.webserver.ContentType; @@ -67,6 +73,8 @@ private PostRequestHandler() { // Private constructor to prevent instantiation } + private static final Logger LOGGER = LoggerFactory.getLogger(PostRequestHandler.class); + /** * Handles the POST request based on the path specified in the request. * It routes the request to the appropriate handler method based on the path. @@ -92,7 +100,7 @@ private static String prepare(String webInput, boolean sanitize) { try { webInput = URLDecoder.decode(webInput, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + LOGGER.error("Encoding is not supported by URLDecoder", e); } ; if (sanitize) { @@ -167,6 +175,7 @@ public static PostResponse handleObjectAction(APIPostReque return successMessage; } public static void registerHandlers() { + LOGGER.info("Registering Post Request Handlers..."); HttpHandler.registerPostRequestHandler("/login", AccessLevel.PUBLIC, (rq) -> { String username = prepare(rq.getString("username"), false); // Do not sanitize / url-decode password to allow special characters like % @@ -205,15 +214,6 @@ public static void registerHandlers() { } }, PostRequestHandler::csvResult) ); - HttpHandler.registerPostRequestHandler("/add-rooms", AccessLevel.ADMIN, (rq) -> - handleBatchInsertCSV(rq, "rooms", ContentType.JSON, t -> { - try { - return Room.generateRoomsFromCSV(t); - } catch (SQLException e) { - throw new IllegalStateException(e); - } - }, Arrays::toString) - ); HttpHandler.registerPostRequestHandler("/add-teacher", AccessLevel.ADMIN, (rq) -> { String firstName = prepare(rq.getString("firstName")); String lastName = prepare(rq.getString("lastName")); @@ -271,14 +271,6 @@ public static void registerHandlers() { HttpHandler.registerPostRequestHandler("/tasks", AccessLevel.USER, (rq) -> { return PostResponse.ok(JSONUtils.toJSON(rq.getTaskList()), ContentType.JSON, rq); }); - HttpHandler.registerPostRequestHandler("/update-room", AccessLevel.USER, (rq) -> { - Student student = rq.getCurrentStudent(); - if (student == null) return PostResponse.unauthorized(rq); - Room room = rq.getRoom(); - if (room == null) return PostResponse.badRequest("Room not found", rq); - student.setCurrentRoom(room); - return PostResponse.ok("Changed current room", ContentType.TEXT_PLAIN, rq); - }); HttpHandler.registerPostRequestHandler("/begin-task", AccessLevel.USER, (rq) -> handleTaskChange(rq, Task.STATUS_IN_PROGRESS)); HttpHandler.registerPostRequestHandler("/complete-task", AccessLevel.USER, (rq) -> handleTaskChange(rq, Task.STATUS_COMPLETED)); HttpHandler.registerPostRequestHandler("/cancel-task", AccessLevel.USER, (rq) -> handleTaskChange(rq, Task.STATUS_NOT_STARTED)); @@ -301,30 +293,7 @@ public static void registerHandlers() { .addProperty("id", student.getId()) .addProperty("name", student.getFirstName() + " " + student.getLastName()) .addProperty("actionRequired", student.isActionRequired()) - .addProperty("graduationLevel", student.getGraduationLevel()) - .addProperty("room", student.getCurrentRoom() != null ? student.getCurrentRoom().getLabel() : "None"); - if (rq.getJson().containsKey("subjectId") && rq.getSubject() != null) { - Set subjectRequests = student.getCurrentRequests(rq.getSubject()); - builder.addProperty("experiment",subjectRequests.stream().anyMatch(r -> r == SubjectRequest.EXPERIMENT)) - .addProperty("help", subjectRequests.stream().anyMatch(r -> r == SubjectRequest.HELP)) - .addProperty("test", subjectRequests.stream().anyMatch(r -> r == SubjectRequest.EXAM)) - .addProperty("partner", subjectRequests.stream().anyMatch(r -> r == SubjectRequest.PARTNER)); - } - }), - ContentType.JSON, rq - ); - }); - HttpHandler.registerPostRequestHandler("/get-students-by-room", AccessLevel.TEACHER, (rq) -> { - Room room = rq.getRoom(); - List students = Student.getByRoom(room); - return PostResponse.ok( - JSONUtils.toJSON(students, (student, builder) -> { - builder - .addProperty("id", student.getId()) - .addProperty("name", student.getFirstName() + " " + student.getLastName()) - .addProperty("actionRequired", student.isActionRequired()) - .addProperty("graduationLevel", student.getGraduationLevel()) - .addProperty("room", student.getCurrentRoom() != null ? student.getCurrentRoom().getLabel() : "None"); + .addProperty("graduationLevel", student.getGraduationLevel()); if (rq.getJson().containsKey("subjectId") && rq.getSubject() != null) { Set subjectRequests = student.getCurrentRequests(rq.getSubject()); builder.addProperty("experiment",subjectRequests.stream().anyMatch(r -> r == SubjectRequest.EXPERIMENT)) @@ -364,8 +333,7 @@ public static void registerHandlers() { .toList(); return PostResponse.ok(JSONUtils.toJSON(students, (partner, builder) -> { builder.addProperty("id", partner.getId()) - .addProperty("name", partner.getFirstName() + " " + partner.getLastName()) - .addProperty("room", partner.getCurrentRoom() != null ? partner.getCurrentRoom().getLabel() : "None"); + .addProperty("name", partner.getFirstName() + " " + partner.getLastName()); }), ContentType.JSON, rq); }); HttpHandler.registerPostRequestHandler("/delete-subject", AccessLevel.ADMIN, (rq) -> @@ -420,6 +388,20 @@ public static void registerHandlers() { Registry.pluginRegistry().get(key[0]).getConfig().toggleSetting(key[1]); return PostResponse.ok("Plugin setting toggled", ContentType.TEXT_PLAIN, rq); }); + HttpHandler.registerPostRequestHandler("/set-plugin-setting", AccessLevel.ADMIN, (rq) -> { + String[] key = rq.getString("key").split(":"); + PluginConfig config = Registry.pluginRegistry().get(key[0]).getConfig(); + PluginSetting setting = config.getSetting(key[1]); + if (setting instanceof BoolSetting boolSetting) { + boolSetting.setValue(rq.getBoolean("value")); + } else if (setting instanceof IntSetting intSetting) { + intSetting.setValue(rq.getInt("value")); + } else if (setting instanceof ShortAnswerSetting shortAnswerSetting) { + shortAnswerSetting.setValue(rq.getString("value")); + } else { + return PostResponse.badRequest("Setting not found", rq);} + return PostResponse.ok("Plugin setting set", ContentType.TEXT_PLAIN, rq); + }); HttpHandler.registerPostRequestHandler("/student-results-csv", AccessLevel.TEACHER, (rq) -> { Student student = rq.getCurrentStudent(); diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java new file mode 100644 index 0000000..37bd4e1 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java @@ -0,0 +1,57 @@ +package de.igslandstuhl.database.server.webserver.handlers.get; + +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.api.SchoolClass; +import de.igslandstuhl.database.api.Student; +import de.igslandstuhl.database.api.Subject; +import de.igslandstuhl.database.api.Teacher; +import de.igslandstuhl.database.api.User; + +@FunctionalInterface +public interface SQLRequestHandler { + public static final Logger LOGGER = LoggerFactory.getLogger(SQLRequestHandler.class); + public String get(User user); + + public static String getResource(String resource, User user) { + return Registry.sqlRequestHandlerRegistry().get(resource).get(user); + } + public static void register() { + LOGGER.info("Registering SQL request handlers..."); + + Registry.sqlRequestHandlerRegistry().register("mydata", (user) -> user.toJSON()); + + Registry.sqlRequestHandlerRegistry().register("mysubjects", (user) -> { + if (user instanceof Student student) { + return student.getSchoolClass().getSubjects().toString(); + } else if (user instanceof Teacher teacher) { + return teacher.getSubjects().toString(); + } else { + return null; + } + }); + Registry.sqlRequestHandlerRegistry().register("myclasses", (user) -> { + if (user instanceof Teacher teacher) { + Set classIDs = teacher.getClassIds(); + Set classes = new HashSet<>(); + for (Integer classID : classIDs) { + classes.add("{\"classId\": " + classID + ", \"name\": \"" + SchoolClass.get(classID).getLabel() + "\"}"); + } + return classes.toString(); + } else { + return null; + } + }); + + Registry.sqlRequestHandlerRegistry().register("teachers", (user) -> new HashSet<>(Teacher.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("students", (user) -> new HashSet<>(Student.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("subjects", (user) -> new HashSet<>(Subject.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("classes", (user) -> new HashSet<>(SchoolClass.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("all-student-resukts", (user) -> Student.getAllResultsCSV()); + } +} diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java b/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java index 72edc41..2c070a4 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java @@ -7,7 +7,6 @@ import com.google.gson.reflect.TypeToken; import de.igslandstuhl.database.api.APIObject; -import de.igslandstuhl.database.api.Room; import de.igslandstuhl.database.api.SchoolClass; import de.igslandstuhl.database.api.Student; import de.igslandstuhl.database.api.Subject; @@ -58,9 +57,6 @@ public Topic getTopic() { public SubjectRequest getSubjectRequest() { return SubjectRequest.fromGermanTranslation(getString("subjectRequest")); } - public Room getRoom() { - return Room.getRoom(getString("room")); - } public Task getTask() { return Task.get(getInt("taskId")); } @@ -86,8 +82,6 @@ public T getAPIObject(TypeToken type) { return (T) getSubjectRequest(); } else if (rawType.getTypeName().contains("Task")) { return (T) getTask(); - } else if (rawType.getTypeName().contains("Room")) { - return (T) getRoom(); } else if (rawType.getTypeName().contains("SchoolClass")) { return (T) getSchoolClass(); } else { diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java b/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java index 71d10da..7189ed0 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java @@ -11,6 +11,7 @@ import de.igslandstuhl.database.server.webserver.ContentType; import de.igslandstuhl.database.server.webserver.NoWebResourceException; import de.igslandstuhl.database.server.webserver.Status; +import de.igslandstuhl.database.server.webserver.handlers.HttpHandler; import de.igslandstuhl.database.server.webserver.handlers.get.PluginRequestHandler; import de.igslandstuhl.database.server.webserver.requests.HttpRequest; @@ -211,7 +212,7 @@ public void respond(PrintStream out) { } catch (FileNotFoundException e) { notFound(request).respond(out); } catch (Exception e) { - e.printStackTrace(); + HttpHandler.LOGGER.warn("Exception while trying to write output stream for get request {}", request, e); if (status != Status.INTERNAL_SERVER_ERROR) { internalServerError(request).respond(out); } else { diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java b/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java index 344de23..f2d373a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java @@ -6,12 +6,14 @@ import com.google.gson.Gson; import de.igslandstuhl.database.server.Server; +import de.igslandstuhl.database.server.WebServer; import de.igslandstuhl.database.server.resources.ResourceLocation; import de.igslandstuhl.database.server.webserver.AccessManager; import de.igslandstuhl.database.server.webserver.ContentType; import de.igslandstuhl.database.server.webserver.Cookie; import de.igslandstuhl.database.server.webserver.NoWebResourceException; import de.igslandstuhl.database.server.webserver.Status; +import de.igslandstuhl.database.server.webserver.handlers.HttpHandler; import de.igslandstuhl.database.server.webserver.requests.HttpRequest; import de.igslandstuhl.database.server.webserver.requests.PostRequest; @@ -106,7 +108,7 @@ public void respond(PrintStream out) { out.print("HTTP/1.1 "); statusCode.write(out); out.print("\r\n"); - out.print("Content-Type: " + contentType + "; charset=UTF-8\r\n"); + out.print("Content-Type: " + contentType.getName() + "; charset=UTF-8\r\n"); if (cookie != null) { out.print("Set-Cookie: " + cookie + "; HttpOnly; Secure\r\n"); } @@ -115,6 +117,7 @@ public void respond(PrintStream out) { } out.print("\r\n"); if (body != null) { + WebServer.LOGGER.debug("Response body: {}", body); out.print(body); } out.flush(); @@ -165,7 +168,7 @@ public static PostResponse getResource(ResourceLocation resourceLocation, String } catch (FileNotFoundException e) { return notFound("The requested resource was not found: " + resourceLocation, request); } catch (Exception e) { - e.printStackTrace(); + HttpHandler.LOGGER.warn("Failed to get resource for request {} on resource location {}", request, resourceLocation); return internalServerError("An error occurred while processing your request.", request); } } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java b/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java index 4c226ee..dd5114c 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java @@ -5,12 +5,16 @@ import java.util.Map; import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.webserver.Cookie; import de.igslandstuhl.database.server.webserver.handlers.SessionValidationResult; import de.igslandstuhl.database.server.webserver.requests.HttpRequest; public class SessionManager { + private static final Logger LOGGER = LoggerFactory.getLogger(SessionManager.class); private Map sessionStore = new HashMap<>(); /** * A map to store session IDs and their associated usernames. @@ -33,6 +37,7 @@ public SessionManager(int sessionExpireDuration, int maximumInactivityDuration, this.sessionExpireDuration = sessionExpireDuration; this.maximumInactivityDuration = maximumInactivityDuration; this.maxRequests = maxRequests; + LOGGER.debug("Starting session cleanup job..."); new Thread(this::cleanSecondsJob, "Session Expiring").start(); } @@ -63,7 +68,7 @@ private void cleanSecondsJob() { try { Thread.sleep(60000); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.warn("Session manager cleanup job interrupted while sleeping", e); } } } @@ -76,18 +81,18 @@ public SessionValidationResult validateSession(HttpRequest request) { count++; requestCount.set(request, count); if (count > maxRequests && !getSessionUser(request).isAdmin()) { - System.out.println("Ratelimit!"); + LOGGER.warn("Needed to put {} under rate limit: {} requests of maximum {} allowed", getSessionUser(request).getUsername(), count, maxRequests); return SessionValidationResult.RATE_LIMITED; } String userAgent = request.getUserAgent(); if (!getSession(request).getUserAgent().equals(userAgent)) { - System.err.println("SEVERE WARNING: POTENTIAL ATTACK: faked session id (device changed), for user " + getSessionUser(request)); + LOGGER.warn("faked session id (device changed), for user {}" + getSessionUser(request)); return SessionValidationResult.INVALID_SESSION; } String ip = request.getIP(); if (!getSession(request).getIpAddress().equals(ip)) { - System.err.println("SEVERE WARNING: POTENTIAL ATTACK: faked session id (ip address changed) for user " + getSessionUser(request)); + LOGGER.warn("faked session id (ip address changed) for user {}" + getSessionUser(request)); return SessionValidationResult.INVALID_SESSION; } diff --git a/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java b/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java index 8f43174..7cb11b0 100644 --- a/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java +++ b/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java @@ -34,6 +34,6 @@ public static void waitForCommandAndExec() { String line = input(); String[] args = line.trim().split(" "); String command = args[0]; - System.out.println(Command.executeCommand(command, Arrays.copyOfRange(args, 1, args.length))); + Command.LOGGER.info("[Commands] {}", Command.executeCommand(command, Arrays.copyOfRange(args, 1, args.length))); } } diff --git a/src/main/resources/html/admin/class.html b/src/main/resources/html/admin/class.html index cec7d6a..513c556 100644 --- a/src/main/resources/html/admin/class.html +++ b/src/main/resources/html/admin/class.html @@ -40,7 +40,6 @@

Schüler in der Klasse

Name - Raum Graduierung diff --git a/src/main/resources/html/admin/manage_rooms.html b/src/main/resources/html/admin/manage_rooms.html deleted file mode 100644 index bda0d6d..0000000 --- a/src/main/resources/html/admin/manage_rooms.html +++ /dev/null @@ -1,46 +0,0 @@ -%[site;title=Raumverwaltung;content=!FOLLOWS] -
-
-

Raumverwaltung

-
-
-
-

Räume hinzufügen

-
- - - -
-
-
-

Raumliste

- - - - - - - - - - -
RaumnameMindestlevel
-
-
- -
- \ No newline at end of file diff --git a/src/main/resources/html/admin/teacher.html b/src/main/resources/html/admin/teacher.html index e6c43f5..96eb3ee 100644 --- a/src/main/resources/html/admin/teacher.html +++ b/src/main/resources/html/admin/teacher.html @@ -19,9 +19,7 @@

Lehrer bearbeiten

- %[class_info] - %[subject_info] - %[room_info] + %[teacher_infos]