From e8d8b536f47857313a502585840a9aa7efd568f2 Mon Sep 17 00:00:00 2001 From: Janis Saldabols Date: Wed, 15 Nov 2023 09:25:13 +0200 Subject: [PATCH] Init commit --- .editorconfig | 12 + .github/workflows/api-doc.yml | 91 ++++ .github/workflows/api-lint.yml | 65 +++ .github/workflows/api-schema-lint.yml | 46 ++ .gitignore | 5 + CONTRIBUTING.md | 4 + Dockerfile | 12 + Jenkinsfile | 14 + LICENSE | 201 ++++++++ MODULE_EVALUATION.md | 53 +++ NEWS.md | 1 + PERSONAL_DATA_DISCLOSURE.md | 57 +++ README.md | 121 +++++ checkstyle/folio_checks.xml | 330 ++++++++++++++ .../DeploymentDescriptor-template.json | 7 + descriptors/ModuleDescriptor-template.json | 216 +++++++++ mod-batch-print.iml | 6 + mod-settings.iml | 6 + pom.xml | 429 ++++++++++++++++++ .../org/folio/print/server/data/Message.java | 17 + .../folio/print/server/data/PrintEntry.java | 49 ++ .../print/server/data/PrintEntryType.java | 6 + .../folio/print/server/main/MainVerticle.java | 74 +++ .../resources/BatchCreationResource.java | 89 ++++ .../print/server/service/PdfService.java | 71 +++ .../print/server/service/PrintService.java | 237 ++++++++++ .../server/storage/ForbiddenException.java | 8 + .../server/storage/NotFoundException.java | 7 + .../print/server/storage/PrintStorage.java | 357 +++++++++++++++ .../print/server/storage/UserException.java | 7 + src/main/resources/log4j2.properties | 18 + src/main/resources/openapi/batchPrint.yaml | 233 ++++++++++ .../resources/openapi/examples/errors.sample | 15 + .../openapi/examples/tenantAttributes.sample | 7 + .../openapi/headers/okapi-permissions.yaml | 6 + .../openapi/headers/okapi-tenant.yaml | 7 + .../openapi/headers/okapi-token.yaml | 6 + .../resources/openapi/headers/okapi-url.yaml | 6 + .../resources/openapi/headers/okapi-user.yaml | 6 + .../resources/openapi/parameters/count.yaml | 10 + .../resources/openapi/parameters/limit.yaml | 8 + .../resources/openapi/parameters/offset.yaml | 8 + .../resources/openapi/parameters/query.yaml | 6 + .../resources/openapi/schemas/entries.json | 23 + src/main/resources/openapi/schemas/entry.json | 27 ++ src/main/resources/openapi/schemas/error.json | 27 ++ .../resources/openapi/schemas/errors.json | 19 + .../openapi/schemas/messageRequest.json | 27 ++ .../openapi/schemas/messageResponse.json | 15 + .../resources/openapi/schemas/parameter.json | 18 + .../resources/openapi/schemas/parameters.json | 9 + .../resources/openapi/schemas/resultInfo.json | 55 +++ .../java/org/folio/print/server/TestBase.java | 147 ++++++ .../print/server/main/MainVerticleTest.java | 403 ++++++++++++++++ .../resources/BatchCreationResourceTest.java | 53 +++ src/test/resources/mail/mail.json | 8 + 56 files changed, 3765 insertions(+) create mode 100644 .editorconfig create mode 100644 .github/workflows/api-doc.yml create mode 100644 .github/workflows/api-lint.yml create mode 100644 .github/workflows/api-schema-lint.yml create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 Dockerfile create mode 100644 Jenkinsfile create mode 100644 LICENSE create mode 100644 MODULE_EVALUATION.md create mode 100644 NEWS.md create mode 100644 PERSONAL_DATA_DISCLOSURE.md create mode 100644 README.md create mode 100644 checkstyle/folio_checks.xml create mode 100644 descriptors/DeploymentDescriptor-template.json create mode 100644 descriptors/ModuleDescriptor-template.json create mode 100644 mod-batch-print.iml create mode 100644 mod-settings.iml create mode 100644 pom.xml create mode 100644 src/main/java/org/folio/print/server/data/Message.java create mode 100644 src/main/java/org/folio/print/server/data/PrintEntry.java create mode 100644 src/main/java/org/folio/print/server/data/PrintEntryType.java create mode 100644 src/main/java/org/folio/print/server/main/MainVerticle.java create mode 100644 src/main/java/org/folio/print/server/resources/BatchCreationResource.java create mode 100644 src/main/java/org/folio/print/server/service/PdfService.java create mode 100644 src/main/java/org/folio/print/server/service/PrintService.java create mode 100644 src/main/java/org/folio/print/server/storage/ForbiddenException.java create mode 100644 src/main/java/org/folio/print/server/storage/NotFoundException.java create mode 100644 src/main/java/org/folio/print/server/storage/PrintStorage.java create mode 100644 src/main/java/org/folio/print/server/storage/UserException.java create mode 100644 src/main/resources/log4j2.properties create mode 100644 src/main/resources/openapi/batchPrint.yaml create mode 100644 src/main/resources/openapi/examples/errors.sample create mode 100644 src/main/resources/openapi/examples/tenantAttributes.sample create mode 100644 src/main/resources/openapi/headers/okapi-permissions.yaml create mode 100644 src/main/resources/openapi/headers/okapi-tenant.yaml create mode 100644 src/main/resources/openapi/headers/okapi-token.yaml create mode 100644 src/main/resources/openapi/headers/okapi-url.yaml create mode 100644 src/main/resources/openapi/headers/okapi-user.yaml create mode 100644 src/main/resources/openapi/parameters/count.yaml create mode 100644 src/main/resources/openapi/parameters/limit.yaml create mode 100644 src/main/resources/openapi/parameters/offset.yaml create mode 100644 src/main/resources/openapi/parameters/query.yaml create mode 100644 src/main/resources/openapi/schemas/entries.json create mode 100644 src/main/resources/openapi/schemas/entry.json create mode 100644 src/main/resources/openapi/schemas/error.json create mode 100644 src/main/resources/openapi/schemas/errors.json create mode 100644 src/main/resources/openapi/schemas/messageRequest.json create mode 100644 src/main/resources/openapi/schemas/messageResponse.json create mode 100644 src/main/resources/openapi/schemas/parameter.json create mode 100644 src/main/resources/openapi/schemas/parameters.json create mode 100644 src/main/resources/openapi/schemas/resultInfo.json create mode 100644 src/test/java/org/folio/print/server/TestBase.java create mode 100644 src/test/java/org/folio/print/server/main/MainVerticleTest.java create mode 100644 src/test/java/org/folio/print/server/resources/BatchCreationResourceTest.java create mode 100644 src/test/resources/mail/mail.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ad6c3f7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +# http://editorconfig.org/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +continuation_indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.github/workflows/api-doc.yml b/.github/workflows/api-doc.yml new file mode 100644 index 0000000..ff59ae2 --- /dev/null +++ b/.github/workflows/api-doc.yml @@ -0,0 +1,91 @@ +name: api-doc + +# https://dev.folio.org/guides/api-doc/ + +# API_TYPES: string: The space-separated list of types to consider. +# One or more of 'RAML OAS'. +# e.g. 'OAS' +# +# API_DIRECTORIES: string: The space-separated list of directories to search +# for API description files. +# e.g. 'src/main/resources/openapi' +# NOTE: -- Also add each separate path to each of the "on: paths:" sections. +# e.g. 'src/main/resources/openapi/**' +# +# API_EXCLUDES: string: The space-separated list of directories and files +# to exclude from traversal, in addition to the default exclusions. +# e.g. '' + +env: + API_TYPES: 'OAS' + API_DIRECTORIES: 'src/main/resources/openapi' + API_EXCLUDES: '' + OUTPUT_DIR: 'folio-api-docs' + AWS_S3_BUCKET: 'foliodocs' + AWS_S3_FOLDER: 'api' + AWS_S3_REGION: 'us-east-1' + AWS_S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }} + AWS_S3_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }} + +on: + push: + branches: [ main, master ] + paths: + - 'src/main/resources/openapi/**' + tags: '[vV][0-9]+.[0-9]+.[0-9]+*' + +jobs: + api-doc: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + ref: ${{ github.REF }} + submodules: recursive + - name: Prepare folio-tools + run: | + git clone https://github.com/folio-org/folio-tools + cd folio-tools/api-doc \ + && yarn install \ + && pip3 install -r requirements.txt + - name: Obtain version if release tag + if: ${{ startsWith(github.ref, 'refs/tags/v') }} + run: | + version=$(echo ${GITHUB_REF#refs/tags/[vV]} | awk -F'.' '{ printf("%d.%d", $1, $2) }') + echo "VERSION_MAJ_MIN=${version}" >> $GITHUB_ENV + - name: Set some vars + run: | + echo "REPO_NAME=${GITHUB_REPOSITORY##*/}" >> $GITHUB_ENV + - name: Report some info + run: | + echo "REPO_NAME=${{ env.REPO_NAME }}" + - name: Do api-doc + run: | + if test -n "${{ env.VERSION_MAJ_MIN }}"; then + echo "Docs for release version ${{ env.VERSION_MAJ_MIN }}" + option_release=$(echo "--version ${{ env.VERSION_MAJ_MIN }}") + else + option_release="" + fi + python3 folio-tools/api-doc/api_doc.py \ + --loglevel info \ + --types ${{ env.API_TYPES }} \ + --directories ${{ env.API_DIRECTORIES }} \ + --excludes ${{ env.API_EXCLUDES }} \ + --output ${{ env.OUTPUT_DIR }} $option_release + - name: Show generated files + working-directory: ${{ env.OUTPUT_DIR }} + run: ls -R + - name: Publish to AWS S3 + uses: sai-sharan/aws-s3-sync-action@v0.1.0 + with: + access_key: ${{ env.AWS_S3_ACCESS_KEY_ID }} + secret_access_key: ${{ env.AWS_S3_ACCESS_KEY }} + region: ${{ env.AWS_S3_REGION }} + source: ${{ env.OUTPUT_DIR }} + destination_bucket: ${{ env.AWS_S3_BUCKET }} + destination_prefix: ${{ env.AWS_S3_FOLDER }} + delete: false + quiet: false + diff --git a/.github/workflows/api-lint.yml b/.github/workflows/api-lint.yml new file mode 100644 index 0000000..f86aa22 --- /dev/null +++ b/.github/workflows/api-lint.yml @@ -0,0 +1,65 @@ +name: api-lint + +# https://dev.folio.org/guides/api-lint/ + +# API_TYPES: string: The space-separated list of types to consider. +# One or more of 'RAML OAS'. +# e.g. 'OAS' +# +# API_DIRECTORIES: string: The space-separated list of directories to search +# for API description files. +# e.g. 'src/main/resources/openapi' +# NOTE: -- Also add each separate path to each of the "on: paths:" sections. +# e.g. 'src/main/resources/openapi/**' +# +# API_EXCLUDES: string: The space-separated list of directories and files +# to exclude from traversal, in addition to the default exclusions. +# e.g. '' +# +# API_WARNINGS: boolean: Whether to cause Warnings to be displayed, +# and to fail the workflow. +# e.g. false + +env: + API_TYPES: 'OAS' + API_DIRECTORIES: 'src/main/resources/openapi' + API_EXCLUDES: '' + API_WARNINGS: false + +on: + push: + paths: + - 'src/main/resources/openapi/**' + pull_request: + paths: + - 'src/main/resources/openapi/**' + +jobs: + api-lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + - name: Prepare folio-tools + run: | + git clone https://github.com/folio-org/folio-tools + cd folio-tools/api-lint \ + && yarn install \ + && pip3 install -r requirements.txt + - name: Configure default options + run: | + echo "OPTION_WARNINGS=''" >> $GITHUB_ENV + - name: Configure option warnings + if: ${{ env.API_WARNINGS == 'true' }} + run: | + echo "OPTION_WARNINGS=--warnings" >> $GITHUB_ENV + - name: Do api-lint + run: | + python3 folio-tools/api-lint/api_lint.py \ + --loglevel info \ + --types ${{ env.API_TYPES }} \ + --directories ${{ env.API_DIRECTORIES }} \ + --excludes ${{ env.API_EXCLUDES }} \ + ${{ env.OPTION_WARNINGS }} diff --git a/.github/workflows/api-schema-lint.yml b/.github/workflows/api-schema-lint.yml new file mode 100644 index 0000000..776c32d --- /dev/null +++ b/.github/workflows/api-schema-lint.yml @@ -0,0 +1,46 @@ +name: api-schema-lint + +# https://dev.folio.org/guides/describe-schema/ + +# API_DIRECTORIES: string: The space-separated list of directories to search +# for JSON Schema files. +# e.g. 'src/main/resources/openapi' +# NOTE: -- Also add each separate path to each of the "on: paths:" sections. +# e.g. 'src/main/resources/openapi/**' +# +# API_EXCLUDES: string: The space-separated list of directories and files +# to exclude from traversal, in addition to the default exclusions. +# e.g. '' + +env: + API_DIRECTORIES: 'src/main/resources/openapi' + API_EXCLUDES: '' + +on: + push: + paths: + - 'src/main/resources/openapi/**' + pull_request: + paths: + - 'src/main/resources/openapi/**' + +jobs: + api-schema-lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + - name: Prepare folio-tools + run: | + git clone https://github.com/folio-org/folio-tools + cd folio-tools/api-schema-lint \ + && yarn install \ + && pip3 install -r requirements.txt + - name: Do api-schema-lint + run: | + python3 folio-tools/api-schema-lint/api_schema_lint.py \ + --loglevel info \ + --directories ${{ env.API_DIRECTORIES }} \ + --excludes ${{ env.API_EXCLUDES }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f258430 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.idea/ +target/ +.vscode/ +*.code-workspace +.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c6e1e05 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,4 @@ +# Contribution guidelines + +Guidelines for Contributing Code: +[dev.folio.org/guidelines/contributing](https://dev.folio.org/guidelines/contributing) diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..67ce664 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM folioci/alpine-jre-openjdk17:latest + +ENV VERTICLE_FILE mod-batch-print-fat.jar + +# Set the location of the verticles +ENV VERTICLE_HOME /usr/verticles + +# Copy your fat jar to the container +COPY target/${VERTICLE_FILE} ${VERTICLE_HOME}/${VERTICLE_FILE} + +# Expose this port locally in the container. +EXPOSE 8081 diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..16c9afd --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,14 @@ +buildMvn { + publishModDescriptor = true + mvnDeploy = true + buildNode = 'jenkins-agent-java17' + + doDocker = { + buildJavaDocker { + publishMaster = true + healthChk = true + healthChkCmd = 'wget --no-verbose --tries=1 --spider http://localhost:8081/admin/health || exit 1' + } + } +} + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MODULE_EVALUATION.md b/MODULE_EVALUATION.md new file mode 100644 index 0000000..33288f4 --- /dev/null +++ b/MODULE_EVALUATION.md @@ -0,0 +1,53 @@ +# Module acceptance criteria for `mod-batch-print` + +## How to use this form +When performing a technical evaluation of a module, create a copy of this document and use the conventions below to indicate the status of each criterion. The evaluation results should be placed in the [module_evaluations](https://github.com/folio-org/tech-council/tree/master/module_evaluations) directory and should conform to the following naming convention: `{JIRA Key}_YYYY-MM-DD.MD`, e.g. `TCR-1_2021-11-17.MD`. The date here is used to differentiate between initial and potential re-evaluation(s). It should be the date when the evaluation results file was created. + +* [ ] ACCEPTABLE +* [ ] ~INAPPLICABLE~ +* [ ] UNACCEPTABLE + * comments on what was evaluated/not evaluated, why a criterion failed + +## [Criteria](https://github.com/folio-org/tech-council/blob/7b10294a5c1c10c7e1a7c5b9f99f04bf07630f06/MODULE_ACCEPTANCE_CRITERIA.MD) + +## Shared/Common +* [ ] Uses Apache 2.0 license +* [ ] Module build MUST produce a valid module descriptor +* [ ] Module descriptor MUST include interface requirements for all consumed APIs +* [ ] Third party dependencies use an Apache 2.0 compatible license +* [ ] Installation documentation is included + * -_note: read more at https://github.com/folio-org/mod-search/blob/master/README.md_ +* [ ] Personal data form is completed, accurate, and provided as `PERSONAL_DATA_DISCLOSURE.md` file +* [ ] Sensitive and environment-specific information is not checked into git repository +* [ ] Module is written in a language and framework from the [officially approved technologies](https://wiki.folio.org/display/TC/Officially+Supported+Technologies) page +* [ ] Module only uses FOLIO interfaces already provided by previously accepted modules _e.g. a UI module cannot be accepted that relies on an interface only provided by a back end module that hasn't been accepted yet_ +* [ ] Module gracefully handles the absence of third party systems or related configuration +* [ ] Sonarqube hasn't identified any security issues, major code smells or excessive (>3%) duplication +* [ ] Uses [officially supported](https://wiki.folio.org/display/TC/Officially+Supported+Technologies) build tools +* [ ] Unit tests have 80% coverage or greater, and are based on [officially approved technologies](https://wiki.folio.org/display/TC/Officially+Supported+Technologies) + +## Backend +* [ ] Module's repository includes a compliant Module Descriptor + * -_note: read more at https://github.com/folio-org/okapi/blob/master/okapi-core/src/main/raml/ModuleDescriptor.json_ +* [ ] Environment vars are documented in the ModuleDescriptor + * -_note: read more at [https://wiki.folio.org/pages/viewpage.action?pageId=65110683](https://wiki.folio.org/pages/viewpage.action?pageId=65110683)_ +* [ ] If a module provides interfaces intended to be consumed by other FOLIO Modules, they must be defined in the Module Descriptor "provides" section +* [ ] All API endpoints are documented in RAML or OpenAPI +* [ ] All API endpoints protected with appropriate permissions as per the following guidelines and recommendations, e.g. avoid using `*.all` permissions, all necessary module permissions are assigned, etc. + * -_note: read more at https://dev.folio.org/guidelines/naming-conventions/ and https://wiki.folio.org/display/DD/Permission+Set+Guidelines_ +* [ ] Module provides reference data (if applicable), e.g. if there is a controlled vocabulary where the module requires at least one value +* [ ] If provided, integration (API) tests must be written in an [officially approved technology](https://wiki.folio.org/display/TC/Officially+Supported+Technologies) + * -_note: while it's strongly recommended that modules implement integration tests, it's not a requirement_ + * -_note: these tests are defined in https://github.com/folio-org/folio-integration-tests_ +* [ ] Data is segregated by tenant at the storage layer +* [ ] The module doesn't access data in DB schemas other than its own and public +* [ ] The module responds with a tenant's content based on x-okapi-tenant header +* [ ] Standard GET `/admin/health` endpoint returning a 200 response + * -_note: read more at https://wiki.folio.org/display/DD/Back+End+Module+Health+Check+Protocol_ +* [ ] High Availability (HA) compliant + * Possible red flags: + * Connection affinity / sticky sessions / etc. are used + * Local container storage is used + * Services are stateful +* [ ] Module only uses infrastructure / platform technologies on the [officially approved technologies](https://wiki.folio.org/display/TC/Officially+Supported+Technologies) list. + * _e.g. PostgreSQL, ElasticSearch, etc._ diff --git a/NEWS.md b/NEWS.md new file mode 100644 index 0000000..cb20da0 --- /dev/null +++ b/NEWS.md @@ -0,0 +1 @@ +## 1.0.0 ? diff --git a/PERSONAL_DATA_DISCLOSURE.md b/PERSONAL_DATA_DISCLOSURE.md new file mode 100644 index 0000000..79692b5 --- /dev/null +++ b/PERSONAL_DATA_DISCLOSURE.md @@ -0,0 +1,57 @@ +## Overview +The purpose of this form is to disclose the types of personal data stored by each module. This information enables those hosting FOLIO to better manage and comply with various privacy laws and restrictions, e.g. GDPR. + +It's important to note that personal data is not limited to that which can be used to identify a person on it's own (e.g. Social security number), but also data used in conjunction with other data to identify a person (e.g. date of birth + city + gender). + +For the purposes of this form, "store" includes the following: +* Persisting to storage - Either internal (e.g. Postgres) or external (e.g. S3, etc.) to FOLIO +* Caching - In-memory, etc. +* Logging +* Sending to an external piece of infrastructure such as a queue (e.g. Kafka), search engine (e.g. Elasticsearch), distributed table, etc. + +## Personal Data Stored by This Module +- [ ] This module does not store any personal data. +- [ ] This module provides [custom fields](https://github.com/folio-org/folio-custom-fields). +- [x] This module stores fields with free-form text (tags, notes, descriptions, etc.) +- [ ] This module caches personal data +--- +- [x] First name +- [x] Last name +- [x] Middle name +- [ ] Pseudonym / Alias / Nickname / Username / User ID +- [ ] Gender +- [ ] Date of birth +- [ ] Place of birth +- [ ] Racial or ethnic origin +- [x] Address +- [ ] Location information +- [ ] Phone numbers +- [ ] Passport number / National identification numbers +- [ ] Driver’s license number +- [ ] Social security number +- [ ] Email address +- [ ] Web cookies +- [ ] IP address +- [ ] Geolocation data +- [ ] Financial information +- [ ] Logic or algorithms used to build a user/profile +- [ ] User search queries + + + +**NOTE** This is not intended to be a comprehensive list, but instead provide a starting point for module developers/maintainers to use. + +## Privacy Laws, Regulations, and Policies +The following laws and policies were considered when creating the list of personal data fields above. +* [General Data Protection Regulation (GDPR)](https://gdpr.eu/) +* [California Consumer Privacy Act (CCPA)](https://oag.ca.gov/privacy/ccpa) +* [U.S. Department of Labor: Guidance on the Protection of Personal Identifiable Information](https://www.dol.gov/general/ppii) +* Cybersecurity Law of the People's Republic of China + * https://www.newamerica.org/cybersecurity-initiative/digichina/blog/translation-cybersecurity-law-peoples-republic-china/ + * http://en.east-concord.com/zygd/Article/20203/ArticleContent_1690.html?utm_source=Mondaq&utm_medium=syndication&utm_campaign=LinkedIn-integration +* [Personal Data Protection Bill, 2019 (India)](https://www.prsindia.org/billtrack/personal-data-protection-bill-2019) +* [Data protection act 2018 (UK)](https://www.legislation.gov.uk/ukpga/2018/12/section/3/enacted) + +--- + +v1.0 diff --git a/README.md b/README.md new file mode 100644 index 0000000..1c4cb09 --- /dev/null +++ b/README.md @@ -0,0 +1,121 @@ +# mod-batch-print + +Copyright (C) 2022-2023 The Open Library Foundation + +This software is distributed under the terms of the Apache License, +Version 2.0. See the file "[LICENSE](LICENSE)" for more information. + +## Introduction + +mod-batch-print is a service to provide option to print notices in +daily batch approach. + +It is currently implemented with PostgresQL as storage. + + +## Compilation + +Requirements: + +* Java 17 or later +* Maven 3.6.3 or later +* Docker (unless `-DskipTests` is used) + +Note: Debian package maven-3.6.3-1 +[does not work with Java16/Java17](https://bugs.launchpad.net/ubuntu/+source/maven/+bug/1930541) + + +You need `JAVA_HOME` set, e.g.: + + * Linux: `export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:bin/javac::")` + * macOS: `export JAVA_HOME=$(/usr/libexec/java_home -v 17)` + +Build all components with: `mvn install` + +## Server + +You will need Postgres 12 or later. + +You can create an empty database and a user with, e.g: + +``` +CREATE DATABASE folio_modules; +CREATE USER folio WITH CREATEROLE PASSWORD 'folio'; +GRANT ALL PRIVILEGES ON DATABASE folio_modules TO folio; +``` + +The module's database connection is then configured by setting environment +variables: +`DB_HOST`, `DB_PORT`, `DB_USERNAME`, `DB_PASSWORD`, `DB_DATABASE`, +`DB_MAXPOOLSIZE`, `DB_SERVER_PEM`. + +Once configured, start the module with: + +``` +java -Dport=8081 -jar target/mod-batch-print-fat.jar +``` + +## Running with Docker + +If you feel adventurous and want to run mod-batch-print in a docker container, build the container first: + +``` +docker build -t mod-batch-print:latest . +``` + +And run with the module port exposed (`8081` by default): + +``` +docker run -e DB_HOST=host.docker.internal \ + -e DB_USERNAME=folio \ + -e DB_PASSWORD=folio \ + -e DB_DATABASE=folio_modules \ + -p 8081:8081 --name batch-print mod-batch-print:latest +``` + +**Note**: The magic host `host.docker.internal` is required to access +the DB and may be only available in Docker Desktop. +If it's not defined you can specify it by passing +`--add-host=host.docker.internal:` to the run command. + +**Note**: Those docker build and run commands do work as-is with +[Colima](https://github.com/abiosoft/colima). + +## Additional information + +### Issue tracker + +See project [MODBATPRNT](https://issues.folio.org/browse/MODBATPRNT) +at the [FOLIO issue tracker](https://dev.folio.org/guidelines/issue-tracker). + +### Code of Conduct + +Refer to the Wiki +[FOLIO Code of Conduct](https://wiki.folio.org/display/COMMUNITY/FOLIO+Code+of+Conduct). + +### ModuleDescriptor + +See the [ModuleDescriptor](descriptors/ModuleDescriptor-template.json) +for the interfaces that this module requires and provides, the permissions, +and the additional module metadata. + +### API documentation + +API descriptions: + + * [OpenAPI](src/main/resources/openapi/batchPrint.yaml) + * [Schemas](src/main/resources/openapi/schemas/) + +Generated [API documentation](https://dev.folio.org/reference/api/#mod-batch-print). + +### Code analysis + +[SonarQube analysis](https://sonarcloud.io/dashboard?id=org.folio%3Amod-batch-print). + +### Download and configuration + +The built artifacts for this module are available. +See [configuration](https://dev.folio.org/download/artifacts) for repository access, +and the Docker images for [released versions](https://hub.docker.com/r/folioorg/mod-batch-print/) +and for [snapshot versions](https://hub.docker.com/r/folioci/mod-batch-print/). + diff --git a/checkstyle/folio_checks.xml b/checkstyle/folio_checks.xml new file mode 100644 index 0000000..a86fce0 --- /dev/null +++ b/checkstyle/folio_checks.xml @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/descriptors/DeploymentDescriptor-template.json b/descriptors/DeploymentDescriptor-template.json new file mode 100644 index 0000000..295a91e --- /dev/null +++ b/descriptors/DeploymentDescriptor-template.json @@ -0,0 +1,7 @@ +{ + "srvcId": "${artifactId}-${version}", + "nodeId": "localhost", + "descriptor": { + "exec": "java -jar ../${artifactId}/target/${artifactId}-fat.jar -Dport=%p" + } +} diff --git a/descriptors/ModuleDescriptor-template.json b/descriptors/ModuleDescriptor-template.json new file mode 100644 index 0000000..04e84ed --- /dev/null +++ b/descriptors/ModuleDescriptor-template.json @@ -0,0 +1,216 @@ +{ + "id": "${artifactId}-${version}", + "name": "Batch printing", + "provides": [ + { + "id": "_tenant", + "version": "2.0", + "interfaceType": "system", + "handlers": [ + { + "methods": [ + "POST" + ], + "pathPattern": "/_/tenant" + }, + { + "methods": [ + "GET", + "DELETE" + ], + "pathPattern": "/_/tenant/{id}" + } + ] + }, + { + "id": "mail", + "version": "1.0", + "handlers": [ + { + "methods": [ + "POST" + ], + "pathPattern": "/print/entries", + "permissionsRequired": [ + "mod-batch-print.entries.item.post" + ], + "permissionsDesired": [ + "mod-batch-print.print.write" + ] + }, + { + "methods": [ + "GET" + ], + "pathPattern": "/print/entries", + "permissionsRequired": [ + "mod-batch-print.entries.collection.get" + ], + "permissionsDesired": [ + "mod-batch-print.print.read" + ] + }, + { + "methods": [ + "GET" + ], + "pathPattern": "/print/entries/{id}", + "permissionsRequired": [ + "mod-batch-print.entries.item.get" + ], + "permissionsDesired": [ + "mod-batch-print.print.read" + ] + }, + { + "methods": [ + "PUT" + ], + "pathPattern": "/print/entries/{id}", + "permissionsRequired": [ + "mod-batch-print.entries.item.put" + ], + "permissionsDesired": [ + "mod-batch-print.print.write" + ] + }, + { + "methods": [ + "DELETE" + ], + "pathPattern": "/print/entries/{id}", + "permissionsRequired": [ + "mod-batch-print.entries.item.delete" + ], + "permissionsDesired": [ + "mod-batch-print.print.write" + ] + }, + { + "methods": [ + "POST" + ], + "pathPattern": "/mail", + "permissionsRequired": [ + "mod-batch-print.entries.mail.post" + ], + "permissionsDesired": [ + "mod-batch-print.print.write" + ] + } + ] + }, + { + "id": "_timer", + "version": "1.0", + "interfaceType": "system", + "handlers": [ + { + "methods": [ + "POST" + ], + "pathPattern": "/print/batch-creation", + "modulePermissions": [ + "mod-batch-print.print.write", + "mod-batch-print.print.read" + ], + "schedule": { + "cron": "1 7 * * *", + "zone": "CET" + } + } + ] + } + ], + "requires": [], + "permissionSets": [ + { + "permissionName": "mod-batch-print.entries.mail.post", + "displayName": "batch print - send mail", + "description": "Send mail to print" + }, + { + "permissionName": "mod-batch-print.entries.item.post", + "displayName": "batch print - create print entry", + "description": "Create print entry" + }, + { + "permissionName": "mod-batch-print.entries.item.put", + "displayName": "batch print - update print entry", + "description": "Update print entry" + }, + { + "permissionName": "mod-batch-print.entries.collection.get", + "displayName": "batch print - get print entries", + "description": "Get batch print" + }, + { + "permissionName": "mod-batch-print.entries.item.get", + "displayName": "batch print - get print entry", + "description": "Get print entry" + }, + { + "permissionName": "mod-batch-print.entries.item.delete", + "displayName": "batch print - delete print entry", + "description": "Delete print entry" + }, + { + "permissionName": "mod-batch-print.entries.all", + "displayName": "batch print - all batch print permissions", + "description": "All batch print permissions", + "subPermissions": [ + "mod-batch-print.entries.item.post", + "mod-batch-print.entries.collection.get", + "mod-batch-print.entries.item.get", + "mod-batch-print.entries.item.put", + "mod-batch-print.entries.item.delete" + ] + } + ], + "launchDescriptor": { + "dockerImage": "${artifactId}:${version}", + "dockerPull": false, + "dockerArgs": { + "HostConfig": { + "Memory": 2147483648, + "PortBindings": { + "8081/tcp": [ + { + "HostPort": "%p" + } + ] + } + } + }, + "env": [ + { + "name": "JAVA_OPTIONS", + "value": "-XX:MaxRAMPercentage=66.0" + }, + { + "name": "DB_HOST", + "value": "postgres" + }, + { + "name": "DB_PORT", + "value": "5432" + }, + { + "name": "DB_USERNAME", + "value": "folio_admin" + }, + { + "name": "DB_PASSWORD", + "value": "folio_admin" + }, + { + "name": "DB_DATABASE", + "value": "okapi_modules" + }, + { + "name": "DB_MAXPOOLSIZE", + "value": "5" + } + ] + } +} diff --git a/mod-batch-print.iml b/mod-batch-print.iml new file mode 100644 index 0000000..9e3449c --- /dev/null +++ b/mod-batch-print.iml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/mod-settings.iml b/mod-settings.iml new file mode 100644 index 0000000..9e3449c --- /dev/null +++ b/mod-settings.iml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..dd88ade --- /dev/null +++ b/pom.xml @@ -0,0 +1,429 @@ + + 4.0.0 + org.folio + mod-batch-print + 1.1.0-SNAPSHOT + jar + + mod-batch-print + https://github.com/folio-org/mod-batch-print + Batch print module + 2023 + + The Open Library Foundation + https://dev.folio.org/ + + + https://github.com/folio-org/mod-batch-print + scm:git:git://github.com/folio-org/mod-batch-print.git + scm:git:git@github.com:folio-org/mod-batch-print.git + HEAD + + + + + Apache License 2.0 + https://spdx.org/licenses/Apache-2.0 + repo + + + + + UTF-8 + 4.14.10 + 3.1.2 + 1.18.28 + 2.0.28 + 2.10.1 + 9.1.22 + io.vertx.core.Launcher + org.folio.print.server.main.MainVerticle + + + + + io.vertx + vertx-core + + + io.vertx + vertx-web + + + io.vertx + vertx-web-openapi + + + io.vertx + vertx-rx-java2 + + + io.vertx + vertx-web-api-contract + + + io.vertx + vertx-pg-client + + + org.folio + vertx-lib + + + org.apache.logging.log4j + log4j-api + + + org.apache.logging.log4j + log4j-core + + + org.folio.okapi + okapi-common + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.apache.pdfbox + pdfbox + ${pdfbox.version} + + + org.xhtmlrenderer + flying-saucer-pdf + ${flying-saucer-pdf.version} + + + + junit + junit + test + + + io.vertx + vertx-unit + test + + + io.rest-assured + rest-assured + test + + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + org.folio + vertx-lib-pg-testing + test + + + org.folio.okapi + okapi-testing + test + + + org.folio.okapi + okapi-core + test + + + org.testcontainers + postgresql + test + + + org.awaitility + awaitility + test + + + + + + + io.vertx + vertx-stack-depchain + 4.3.6 + pom + import + + + org.folio + vertx-lib + ${vertxlib.version} + + + org.folio + vertx-lib-pg-testing + ${vertxlib.version} + + + org.apache.logging.log4j + log4j-bom + 2.19.0 + pom + import + + + org.folio.okapi + okapi-common + ${okapi.version} + + + org.folio.okapi + okapi-core + ${okapi.version} + + + org.folio.okapi + okapi-testing + ${okapi.version} + + + io.rest-assured + rest-assured + 4.5.1 + + + org.testcontainers + testcontainers-bom + 1.17.6 + pom + import + + + junit + junit + 4.13.2 + + + org.awaitility + awaitility + 4.2.0 + + + com.fasterxml.jackson + jackson-bom + ${jackson.version} + import + pom + + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + + + + ${vertx.launcher} + ${vertx.verticle} + true + + + + + ${project.build.directory}/${project.artifactId}-fat.jar + + + + + + + maven-resources-plugin + 3.0.1 + + + filter-descriptor-inputs + generate-resources + + copy-resources + + + ${project.build.directory} + + + ${basedir}/descriptors + *Descriptor*-template.json + true + + + + + + + + + com.coderplus.maven.plugins + copy-rename-maven-plugin + 1.0 + + + rename-descriptor-outputs + generate-resources + + rename + + + + + ${project.build.directory}/ModuleDescriptor-template.json + ${project.build.directory}/ModuleDescriptor.json + + + ${project.build.directory}/DeploymentDescriptor-template.json + ${project.build.directory}/DeploymentDescriptor.json + + + + + + + + + maven-compiler-plugin + 3.8.1 + + 17 + UTF-8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.22.2 + + + + integration-test + verify + + + + + + + org.apache.maven.plugins + maven-release-plugin + + clean verify + v@{project.version} + false + true + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.2 + + + com.puppycrawl.tools + checkstyle + 10.3 + + + + checkstyle/folio_checks.xml + UTF-8 + warning + false + true + true + false + + ${project.build.sourceDirectory} + + + + + check + compile + + check + + + + + + pl.project13.maven + git-commit-id-plugin + 4.9.10 + + + get-the-git-infos + + revision + + + + + true + ${project.build.outputDirectory}/git.properties + + + + + + + folio-nexus + FOLIO Maven repository + https://repository.folio.org/repository/maven-folio + + + indexdata + Index Data + https://maven.indexdata.com/ + + + + + + folio-nexus + FOLIO Release Repository + https://repository.folio.org/repository/maven-releases/ + false + default + + + folio-nexus + FOLIO Snapshot Repository + true + https://repository.folio.org/repository/maven-snapshots/ + default + + + + + JIRA + https://issues.folio.org/browse/MODSET + + diff --git a/src/main/java/org/folio/print/server/data/Message.java b/src/main/java/org/folio/print/server/data/Message.java new file mode 100644 index 0000000..84d6989 --- /dev/null +++ b/src/main/java/org/folio/print/server/data/Message.java @@ -0,0 +1,17 @@ +package org.folio.print.server.data; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +@Data +public class Message { + private String deliveryChannel; + private String from; + private String outputFormat; + private String header; + private String body; + +} diff --git a/src/main/java/org/folio/print/server/data/PrintEntry.java b/src/main/java/org/folio/print/server/data/PrintEntry.java new file mode 100644 index 0000000..10fd79c --- /dev/null +++ b/src/main/java/org/folio/print/server/data/PrintEntry.java @@ -0,0 +1,49 @@ +package org.folio.print.server.data; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.time.ZonedDateTime; +import java.util.UUID; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PrintEntry { + + private UUID id; + + private ZonedDateTime created; + + private PrintEntryType type; + + private String content; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public ZonedDateTime getCreated() { + return created; + } + + public void setCreated(ZonedDateTime created) { + this.created = created; + } + + public PrintEntryType getType() { + return type; + } + + public void setType(PrintEntryType type) { + this.type = type; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } +} diff --git a/src/main/java/org/folio/print/server/data/PrintEntryType.java b/src/main/java/org/folio/print/server/data/PrintEntryType.java new file mode 100644 index 0000000..be6af18 --- /dev/null +++ b/src/main/java/org/folio/print/server/data/PrintEntryType.java @@ -0,0 +1,6 @@ +package org.folio.print.server.data; + +public enum PrintEntryType { + SINGLE, + BATCH; +} diff --git a/src/main/java/org/folio/print/server/main/MainVerticle.java b/src/main/java/org/folio/print/server/main/MainVerticle.java new file mode 100644 index 0000000..f621840 --- /dev/null +++ b/src/main/java/org/folio/print/server/main/MainVerticle.java @@ -0,0 +1,74 @@ +package org.folio.print.server.main; + +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import io.vertx.core.AbstractVerticle; +import io.vertx.core.Promise; +import io.vertx.core.http.HttpServerOptions; +import io.vertx.core.json.jackson.DatabindCodec; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.okapi.common.Config; +import org.folio.okapi.common.ModuleVersionReporter; +import org.folio.print.server.resources.BatchCreationResource; +import org.folio.print.server.service.PrintService; +import org.folio.tlib.RouterCreator; +import org.folio.tlib.api.HealthApi; +import org.folio.tlib.api.Tenant2Api; +import org.folio.tlib.postgres.TenantPgPool; + +public class MainVerticle extends AbstractVerticle { + final Logger log = LogManager.getLogger(MainVerticle.class); + + @Override + public void start(Promise promise) { + TenantPgPool.setModule("mod-batch-print"); + ModuleVersionReporter m = new ModuleVersionReporter("org.folio/mod-batch-print"); + log.info("Starting {} {} {}", m.getModule(), m.getVersion(), m.getCommitId()); + final int port = Integer.parseInt( + Config.getSysConf("http.port", "port", "8081", config())); + log.info("Listening on port {}", port); + + var printServiceService = new PrintService(); + var batchCreationResource = new BatchCreationResource(); + + RouterCreator[] routerCreators = { + printServiceService, + batchCreationResource, + new Tenant2Api(printServiceService), + new HealthApi(), + }; + + RouterCreator.mountAll(vertx, routerCreators) + .compose(router -> { + HttpServerOptions so = new HttpServerOptions() + .setCompressionSupported(true) + .setDecompressionSupported(true) + .setHandle100ContinueAutomatically(true); + return vertx.createHttpServer(so) + .requestHandler(router) + .listen(port).mapEmpty(); + }) + .onComplete(x -> promise.handle(x.mapEmpty())); + configureObjectMapper(); + } + + private void configureObjectMapper() { + JavaTimeModule javaTimeModule = new JavaTimeModule(); + javaTimeModule.addDeserializer(LocalDateTime.class, + new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME)); + DatabindCodec.mapper().registerModule(javaTimeModule) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + DatabindCodec.prettyMapper().registerModule(javaTimeModule) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + } + + @Override + public void stop(Promise promise) { + TenantPgPool.closeAll() + .onComplete(promise); + } +} diff --git a/src/main/java/org/folio/print/server/resources/BatchCreationResource.java b/src/main/java/org/folio/print/server/resources/BatchCreationResource.java new file mode 100644 index 0000000..89aa4a5 --- /dev/null +++ b/src/main/java/org/folio/print/server/resources/BatchCreationResource.java @@ -0,0 +1,89 @@ +package org.folio.print.server.resources; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.BodyHandler; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.List; +import java.util.UUID; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.pdfbox.util.Hex; +import org.folio.print.server.data.PrintEntry; +import org.folio.print.server.data.PrintEntryType; +import org.folio.print.server.service.PdfService; +import org.folio.print.server.service.PrintService; +import org.folio.print.server.storage.PrintStorage; +import org.folio.tlib.RouterCreator; + + +public class BatchCreationResource implements RouterCreator { + private static final Logger LOGGER = LogManager.getLogger(BatchCreationResource.class); + private static final int MAX_COUNT_IN_BATCH = 1000; + + public BatchCreationResource() { + } + + @Override + public Future createRouter(Vertx vertx) { + Router router = Router.router(vertx); + String rootPath = "/print/batch-creation"; + router.post(rootPath + "*").handler(BodyHandler.create()); + router.post(rootPath).handler(this::process) + .failureHandler(this::failureResponder); + return Future.succeededFuture(router); + } + + private void process(RoutingContext ctx) { + PrintStorage storage = PrintService.create(ctx); + LocalDateTime localDateTime = LocalDateTime.now().with(LocalTime.MIDNIGHT); + + storage.getEntriesByQuery("type=\"SINGLE\" and created > " + localDateTime + + " order by created", 0, MAX_COUNT_IN_BATCH) + .onSuccess(l -> processListAndSaveResult(l, storage)) + .onFailure(e -> LOGGER.error("Failed to create print batch", e)); + } + + private void processListAndSaveResult(List entries, PrintStorage storage) { + if (!entries.isEmpty()) { + byte[] merged = PdfService.combinePdfFiles(entries); + PrintEntry batch = new PrintEntry(); + batch.setId(UUID.randomUUID()); + batch.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + batch.setType(PrintEntryType.BATCH); + batch.setContent(Hex.getString(merged)); + storage.createEntry(batch); + } + } + + private void failureResponder(RoutingContext context) { + Throwable failure = context.failure(); + + if (failure != null) { + if (StringUtils.isNotBlank(failure.getMessage())) { + internalError(context.response(), failure.getMessage()); + } else { + internalError(context.response(), failure.toString()); + } + } else { + internalError(context.response(), "Unknown failure occurred"); + } + } + + private static void internalError(HttpServerResponse response, String reason) { + response.setStatusCode(500); + response.putHeader("content-type", "text/plain; ISO_8859_1"); + if (reason != null) { + response.end(reason); + } else { + response.end(); + } + } +} diff --git a/src/main/java/org/folio/print/server/service/PdfService.java b/src/main/java/org/folio/print/server/service/PdfService.java new file mode 100644 index 0000000..998f26a --- /dev/null +++ b/src/main/java/org/folio/print/server/service/PdfService.java @@ -0,0 +1,71 @@ +package org.folio.print.server.service; + +import com.lowagie.text.DocumentException; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.pdfbox.multipdf.PDFMergerUtility; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.util.Hex; +import org.folio.print.server.data.PrintEntry; +import org.xhtmlrenderer.pdf.ITextRenderer; + +public class PdfService { + private static final Logger LOGGER = LogManager.getLogger(PdfService.class); + + /** + * Create PDF content from HTML input. + * @param htmlContent HTML input + * @return Byte array of PDF content + */ + public static byte[] createPdfFile(String htmlContent) { + if (htmlContent != null && !htmlContent.isBlank()) { + try (PDDocument document = new PDDocument(); + ByteArrayOutputStream os = new ByteArrayOutputStream()) { + htmlContent = "
" + htmlContent + "
"; + htmlContent = htmlContent.replaceAll("
", "
"); + PDPage page = new PDPage(PDRectangle.A4); + document.addPage(page); + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocumentFromString(htmlContent); + renderer.layout(); + renderer.createPDF(os); + return os.toByteArray(); + } catch (IOException | DocumentException e) { + LOGGER.error("Error creating PDF", e); + } + } + return new byte[0]; + } + + /** + * Combine single print entries in batch print file. + * @param entries Entries to combine + * @return Byte array of combined PDF file + */ + public static byte[] combinePdfFiles(List entries) { + try (ByteArrayOutputStream mergedOutputStream = new ByteArrayOutputStream()) { + PDFMergerUtility pdfMerger = new PDFMergerUtility(); + entries.forEach(e -> { + if (e.getContent() != null && !e.getContent().isBlank()) { + try { + pdfMerger.addSource(new ByteArrayInputStream(Hex.decodeHex(e.getContent()))); + } catch (IOException ex) { + LOGGER.error("Failed to merge entry: " + e.getId(), ex); + } + } + }); + pdfMerger.setDestinationStream(mergedOutputStream); + pdfMerger.mergeDocuments(null); + return mergedOutputStream.toByteArray(); + } catch (IOException e) { + LOGGER.error("Error merging PDFs", e); + } + return new byte[0]; + } +} diff --git a/src/main/java/org/folio/print/server/service/PrintService.java b/src/main/java/org/folio/print/server/service/PrintService.java new file mode 100644 index 0000000..d9e2f8e --- /dev/null +++ b/src/main/java/org/folio/print/server/service/PrintService.java @@ -0,0 +1,237 @@ +package org.folio.print.server.service; + +import io.netty.handler.codec.http.HttpResponseStatus; +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.BodyHandler; +import io.vertx.ext.web.openapi.RouterBuilder; +import io.vertx.ext.web.validation.RequestParameter; +import io.vertx.ext.web.validation.RequestParameters; +import io.vertx.ext.web.validation.ValidationHandler; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.UUID; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.pdfbox.util.Hex; +import org.folio.okapi.common.HttpResponse; +import org.folio.okapi.common.XOkapiHeaders; +import org.folio.print.server.data.Message; +import org.folio.print.server.data.PrintEntry; +import org.folio.print.server.data.PrintEntryType; +import org.folio.print.server.storage.ForbiddenException; +import org.folio.print.server.storage.NotFoundException; +import org.folio.print.server.storage.PrintStorage; +import org.folio.print.server.storage.UserException; +import org.folio.tlib.RouterCreator; +import org.folio.tlib.TenantInitHooks; + +public class PrintService implements RouterCreator, TenantInitHooks { + + public static final int BODY_LIMIT = 67108864; // 64 Mb + + private static final Logger log = LogManager.getLogger(PrintService.class); + + @Override + public Future createRouter(Vertx vertx) { + return RouterBuilder.create(vertx, "openapi/batchPrint.yaml") + .map(routerBuilder -> { + // https://vertx.io/docs/vertx-web/java/#_limiting_body_size + routerBuilder.rootHandler(BodyHandler.create().setBodyLimit(BODY_LIMIT)); + handlers(routerBuilder); + Router router = Router.router(vertx); + router.route("/*").subRouter(routerBuilder.createRouter()); + return router; + }); + } + + private void failureHandler(RoutingContext ctx) { + commonError(ctx, ctx.failure(), ctx.statusCode()); + } + + void commonError(RoutingContext ctx, Throwable cause) { + commonError(ctx, cause, 500); + } + + void commonError(RoutingContext ctx, Throwable cause, int defaultCode) { + log.debug("commonError"); + if (cause == null) { + HttpResponse.responseError(ctx, defaultCode, + HttpResponseStatus.valueOf(defaultCode).reasonPhrase()); + } else if (cause instanceof ForbiddenException) { + HttpResponse.responseError(ctx, 403, cause.getMessage()); + } else if (cause instanceof NotFoundException) { + HttpResponse.responseError(ctx, 404, cause.getMessage()); + } else if (cause instanceof UserException) { + HttpResponse.responseError(ctx, 400, cause.getMessage()); + } else { + HttpResponse.responseError(ctx, defaultCode, cause.getMessage()); + } + } + + private void handlers(RouterBuilder routerBuilder) { + routerBuilder + .operation("getPrintEntries") + .handler(ctx -> getPrintEntries(ctx) + .onFailure(cause -> commonError(ctx, cause)) + ) + .failureHandler(this::failureHandler); + + routerBuilder + .operation("postPrintEntry") + .handler(ctx -> postPrintEntry(ctx) + .onFailure(cause -> commonError(ctx, cause)) + ) + .failureHandler(this::failureHandler); + routerBuilder + .operation("getPrintEntry") + .handler(ctx -> getPrintEntry(ctx) + .onFailure(cause -> commonError(ctx, cause)) + ) + .failureHandler(this::failureHandler); + routerBuilder + .operation("deletePrintEntry") + .handler(ctx -> deletePrintEntry(ctx) + .onFailure(cause -> commonError(ctx, cause)) + ) + .failureHandler(this::failureHandler); + + routerBuilder + .operation("updatePrintEntry") + .handler(ctx -> updatePrintEntry(ctx) + .onFailure(cause -> commonError(ctx, cause)) + ) + .failureHandler(this::failureHandler); + + routerBuilder + .operation("saveMail") + .handler(ctx -> saveMail(ctx) + .onFailure(cause -> commonError(ctx, cause)) + ) + .failureHandler(this::failureHandler); + } + + static PrintStorage createFromParams(Vertx vertx, RequestParameters params) { + // get tenant + RequestParameter tenantParameter = params.headerParameter(XOkapiHeaders.TENANT); + String tenant = tenantParameter.getString(); + + // get user Id + RequestParameter userIdParameter = params.headerParameter(XOkapiHeaders.USER_ID); + UUID currentUserId = null; + if (userIdParameter != null) { + currentUserId = UUID.fromString(userIdParameter.getString()); + } + + // get permissions which is required in OpenAPI spec + RequestParameter okapiPermissions = params.headerParameter(XOkapiHeaders.PERMISSIONS); + JsonArray permissions = new JsonArray(okapiPermissions.getString()); + return new PrintStorage(vertx, tenant, currentUserId, permissions); + } + + public static PrintStorage create(RoutingContext ctx) { + return createFromParams(ctx.vertx(), ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY)); + } + + Future postPrintEntry(RoutingContext ctx) { + PrintStorage storage = create(ctx); + RequestParameters params = ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY); + RequestParameter body = params.body(); + PrintEntry entry = body.getJsonObject().mapTo(PrintEntry.class); + return storage.createEntry(entry) + .map(entity -> { + ctx.response().setStatusCode(204); + ctx.response().end(); + return null; + }); + } + + Future saveMail(RoutingContext ctx) { + final PrintStorage storage = create(ctx); + RequestParameters params = ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY); + RequestParameter body = params.body(); + Message message = body.getJsonObject().mapTo(Message.class); + PrintEntry entry = new PrintEntry(); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setContent(Hex.getString(PdfService.createPdfFile(message.getBody()))); + return storage.createEntry(entry) + .map(entity -> { + ctx.response().setStatusCode(HttpResponseStatus.OK.code()); + ctx.response().end(new JsonObject().put("id", entry.getId()).encode()); + return null; + }); + } + + Future getPrintEntry(RoutingContext ctx) { + PrintStorage storage = create(ctx); + RequestParameters params = ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY); + String id = params.pathParameter("id").getString(); + return storage.getEntry(UUID.fromString(id)) + .map(entity -> { + HttpResponse.responseJson(ctx, 200) + .end(JsonObject.mapFrom(entity).encode()); + return null; + }); + } + + Future deletePrintEntry(RoutingContext ctx) { + PrintStorage printStorage = create(ctx); + RequestParameters params = ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY); + String id = params.pathParameter("id").getString(); + return printStorage.deleteEntry(UUID.fromString(id)) + .map(res -> { + ctx.response().setStatusCode(204); + ctx.response().end(); + return null; + }); + } + + Future updatePrintEntry(RoutingContext ctx) { + PrintStorage printStorage = create(ctx); + RequestParameters params = ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY); + RequestParameter body = params.body(); + PrintEntry entry = body.getJsonObject().mapTo(PrintEntry.class); + UUID id = UUID.fromString(params.pathParameter("id").getString()); + if (!id.equals(entry.getId())) { + return Future.failedFuture(new UserException("id mismatch")); + } + return printStorage.updateEntry(entry) + .map(entity -> { + ctx.response().setStatusCode(204); + ctx.response().end(); + return null; + }); + } + + Future getPrintEntries(RoutingContext ctx) { + PrintStorage storage = create(ctx); + RequestParameters params = ctx.get(ValidationHandler.REQUEST_CONTEXT_KEY); + RequestParameter queryParameter = params.queryParameter("query"); + String query = queryParameter != null ? queryParameter.getString() : null; + RequestParameter limitParameter = params.queryParameter("limit"); + int limit = limitParameter != null ? limitParameter.getInteger() : 10; + RequestParameter offsetParameter = params.queryParameter("offset"); + int offset = offsetParameter != null ? offsetParameter.getInteger() : 0; + return storage.getEntries(ctx.response(), query, offset, limit); + } + + @Override + public Future postInit(Vertx vertx, String tenant, JsonObject tenantAttributes) { + if (!tenantAttributes.containsKey("module_to")) { + return Future.succeededFuture(); // doing nothing for disable + } + PrintStorage storage = new PrintStorage(vertx, tenant, null, null); + return storage.init(); + } + + @Override + public Future preInit(Vertx vertx, String tenant, JsonObject tenantAttributes) { + return Future.succeededFuture(); + } +} diff --git a/src/main/java/org/folio/print/server/storage/ForbiddenException.java b/src/main/java/org/folio/print/server/storage/ForbiddenException.java new file mode 100644 index 0000000..a6d5b61 --- /dev/null +++ b/src/main/java/org/folio/print/server/storage/ForbiddenException.java @@ -0,0 +1,8 @@ +package org.folio.print.server.storage; + +public class ForbiddenException extends RuntimeException { + public ForbiddenException() { + super("Forbidden"); + } + +} diff --git a/src/main/java/org/folio/print/server/storage/NotFoundException.java b/src/main/java/org/folio/print/server/storage/NotFoundException.java new file mode 100644 index 0000000..0abd57f --- /dev/null +++ b/src/main/java/org/folio/print/server/storage/NotFoundException.java @@ -0,0 +1,7 @@ +package org.folio.print.server.storage; + +public class NotFoundException extends RuntimeException { + public NotFoundException() { + super("Not Found"); + } +} diff --git a/src/main/java/org/folio/print/server/storage/PrintStorage.java b/src/main/java/org/folio/print/server/storage/PrintStorage.java new file mode 100644 index 0000000..cb3acb3 --- /dev/null +++ b/src/main/java/org/folio/print/server/storage/PrintStorage.java @@ -0,0 +1,357 @@ +package org.folio.print.server.storage; + +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpHeaders; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.pgclient.PgException; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowIterator; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.RowStream; +import io.vertx.sqlclient.SqlConnection; +import io.vertx.sqlclient.Tuple; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.print.server.data.PrintEntry; +import org.folio.print.server.data.PrintEntryType; +import org.folio.tlib.postgres.PgCqlDefinition; +import org.folio.tlib.postgres.PgCqlQuery; +import org.folio.tlib.postgres.TenantPgPool; +import org.folio.tlib.postgres.cqlfield.PgCqlFieldText; +import org.folio.tlib.postgres.cqlfield.PgCqlFieldTimestamp; +import org.folio.tlib.postgres.cqlfield.PgCqlFieldUuid; + +public class PrintStorage { + + private static final Logger log = LogManager.getLogger(PrintStorage.class); + + private static final String CREATE_IF_NO_EXISTS = "CREATE TABLE IF NOT EXISTS "; + + private static final String PERM_PREFIX = "mod-batch-print"; + private static final String PERM_PRINT = "print"; + private static final String PERM_READ = "read"; + private static final String PERM_WRITE = "write"; + + private final TenantPgPool pool; + + private final String printTable; + + private final JsonArray permissions; + + private final UUID currentUser; + + + /** + * Construct storage request for a user with given okapi permissions. + * + * @param vertx Vert.x handle + * @param tenant tenant + * @param currentUser UUID of user as it comes from X-Okapi-User-Id + * @param permissions permissions as it comes from X-Okapi-Permissions + */ + public PrintStorage(Vertx vertx, String tenant, UUID currentUser, JsonArray permissions) { + this.pool = TenantPgPool.pool(vertx, tenant); + this.permissions = permissions; + this.currentUser = currentUser; + this.printTable = pool.getSchema() + ".printing"; + } + + /** + * Prepares storage for a tenant, AKA tenant init. + * + * @return async result + */ + public Future init() { + return pool.execute(List.of( + CREATE_IF_NO_EXISTS + printTable + + "(id uuid NOT NULL PRIMARY KEY," + + " created TIMESTAMP NOT NULL," + + " type VARCHAR NOT NULL," + + " content JSONB NOT NULL" + + ")" + )); + } + + /** + * Checks if access is allowed. + * + * @param type read/write value + * @param permissions permissions given at runtime + * @return true if access is OK; false otherwise (forbidden) + */ + static boolean checkDesiredPermissions(String type, JsonArray permissions) { + return permissions.contains(PERM_PREFIX + "." + PERM_PRINT + "." + type); + } + + PrintEntry fromRow(Row row) { + PrintEntry entry = new PrintEntry(); + entry.setId(row.getUUID("id")); + entry.setCreated(row.getLocalDateTime("created").atZone(ZoneId.of(ZoneOffset.UTC.getId()))); + entry.setType(PrintEntryType.valueOf(row.getString("type"))); + entry.setContent(row.getString("content")); + return entry; + } + + /** + * Create print entry. + * + * @param entry to be created + * @return async result with success if created; failed otherwise + */ + public Future createEntry(PrintEntry entry) { + if (!checkDesiredPermissions(PERM_WRITE, permissions)) { + return Future.failedFuture(new ForbiddenException()); + } + return pool.preparedQuery( + "INSERT INTO " + printTable + + " (id, created, type, content)" + + " VALUES ($1, $2, $3, $4)" + ) + .execute(Tuple.of(entry.getId(), toLocalDateTime(entry.getCreated()), + entry.getType(), entry.getContent())) + .map(rowSet -> { + if (rowSet.rowCount() == 0) { + throw new ForbiddenException(); + } + return null; + }); + } + + private LocalDateTime toLocalDateTime(ZonedDateTime zonedDateTime) { + return zonedDateTime == null ? null : + zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime(); + } + + /** + * Get print entry. + * + * @param id entry identifier + * @return async result with entry value; failure otherwise + */ + public Future getEntry(UUID id) { + return getEntryWoCheck(id) + .map(entry -> { + if (entry == null) { + throw new NotFoundException(); + } + if (!checkDesiredPermissions(PERM_READ, permissions)) { + throw new ForbiddenException(); + } + return entry; + }); + } + + Future getEntryWoCheck(UUID id) { + return pool.preparedQuery( + "SELECT * FROM " + printTable + " WHERE id = $1") + .execute(Tuple.of(id)) + .map(rowSet -> { + RowIterator iterator = rowSet.iterator(); + if (!iterator.hasNext()) { + return null; + } + return fromRow(iterator.next()); + }); + } + + /** + * Delete print entry. + * + * @param id entry identifier + * @return async result; exception if not found or forbidden + */ + public Future deleteEntry(UUID id) { + return getEntryWoCheck(id).compose(entry -> { + if (entry == null) { + return Future.failedFuture(new NotFoundException()); + } + if (!checkDesiredPermissions(PERM_WRITE, permissions)) { + return Future.failedFuture(new ForbiddenException()); + } + return pool.preparedQuery( + "DELETE FROM " + printTable + " WHERE id = $1") + .execute(Tuple.of(id)) + .map(res -> { + if (res.rowCount() == 0) { + throw new NotFoundException(); + } + return null; + }); + }); + } + + /** + * Update print entry. + * + * @param entry to be updated + * @return async result with success if created; failed otherwise + */ + public Future updateEntry(PrintEntry entry) { + if (!checkDesiredPermissions(PERM_WRITE, permissions)) { + return Future.failedFuture(new ForbiddenException()); + } + return pool.preparedQuery( + "UPDATE " + printTable + + " SET created = $2, type = $3, content = $4" + + " WHERE id = $1" + ) + .execute(Tuple.of(entry.getId(), toLocalDateTime(entry.getCreated()), + entry.getType(), entry.getContent())) + .map(rowSet -> { + if (rowSet.rowCount() == 0) { + throw new NotFoundException(); + } + return null; + }) + .recover(e -> { + if (e instanceof PgException pgException + && pgException.getMessage().contains("(23505)")) { + return Future.failedFuture(new NotFoundException()); + + } + return Future.failedFuture(e); + }) + .mapEmpty(); + } + + /** + * Get entries with optional cqlQuery. + * + * @param response HTTP response for result + * @param cqlQuery CQL cqlQuery; null if no cqlQuery is provided + * @param offset starting offset of entries returned + * @param limit maximum number of entries returned + * @return async result + */ + public Future getEntries(HttpServerResponse response, String cqlQuery, + int offset, int limit) { + if (!checkDesiredPermissions(PERM_READ, permissions)) { + return Future.failedFuture(new ForbiddenException()); + } + + Pair sqlQuery = createSqlQuery(cqlQuery, offset, limit); + String countQuery = "SELECT COUNT(*) FROM " + sqlQuery.getRight(); + return pool.getConnection() + .compose(connection -> + streamResult(response, connection, sqlQuery.getLeft(), countQuery) + .onFailure(x -> connection.close()) + ); + } + + Future streamResult(HttpServerResponse response, + SqlConnection connection, String query, String cnt) { + + String property = "items"; + Tuple tuple = Tuple.tuple(); + int sqlStreamFetchSize = 100; + + return connection.prepare(query) + .compose(pq -> + connection.begin().map(tx -> { + response.setChunked(true); + response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); + response.write("{ \"" + property + "\" : ["); + AtomicBoolean first = new AtomicBoolean(true); + RowStream stream = pq.createStream(sqlStreamFetchSize, tuple); + stream.handler(row -> { + if (!first.getAndSet(false)) { + response.write(","); + } + PrintEntry entry = fromRow(row); + response.write(JsonObject.mapFrom(entry).encode()); + }); + stream.endHandler(end -> { + Future> cntFuture = cnt != null + ? connection.preparedQuery(cnt).execute(tuple) + : Future.succeededFuture(null); + cntFuture + .onSuccess(cntRes -> resultFooter(response, cntRes, null)) + .onFailure(f -> { + log.error(f.getMessage(), f); + resultFooter(response, null, f.getMessage()); + }) + .eventually(x -> tx.commit().compose(y -> connection.close())); + }); + stream.exceptionHandler(e -> { + log.error("stream error {}", e.getMessage(), e); + resultFooter(response, null, e.getMessage()); + tx.commit().compose(y -> connection.close()); + }); + return null; + }) + ); + } + + void resultFooter(HttpServerResponse response, RowSet rowSet, String diagnostic) { + JsonObject resultInfo = new JsonObject(); + if (rowSet != null) { + int pos = 0; + Row row = rowSet.iterator().next(); + int count = row.getInteger(pos); + resultInfo.put("totalRecords", count); + } + JsonArray diagnostics = new JsonArray(); + if (diagnostic != null) { + diagnostics.add(new JsonObject().put("message", diagnostic)); + } + resultInfo.put("diagnostics", diagnostics); + response.write("], \"resultInfo\": " + resultInfo.encode() + "}"); + response.end(); + } + + /** + * Get print entries as list by query. + * @param cqlQuery Query to perform + * @param offset Offset + * @param limit Limit + * @return Result list + */ + public Future> getEntriesByQuery(String cqlQuery, int offset, int limit) { + if (!checkDesiredPermissions(PERM_READ, permissions)) { + return Future.failedFuture(new ForbiddenException()); + } + + Pair sqlQuery = createSqlQuery(cqlQuery, offset, limit); + + return pool.preparedQuery(sqlQuery.getLeft()) + .execute() + .map(rowSet -> { + RowIterator iterator = rowSet.iterator(); + List results = new ArrayList<>(); + while (iterator.hasNext()) { + results.add(fromRow(iterator.next())); + } + return results; + }); + } + + private Pair createSqlQuery(String cqlQuery, int offset, int limit) { + PgCqlDefinition definition = PgCqlDefinition.create(); + definition.addField("id", new PgCqlFieldUuid()); + definition.addField("type", new PgCqlFieldText().withExact()); + definition.addField("created", new PgCqlFieldTimestamp()); + + PgCqlQuery pgCqlQuery = definition.parse(cqlQuery); + String sqlOrderBy = pgCqlQuery.getOrderByClause(); + String from = printTable + " WHERE " + + (pgCqlQuery.getWhereClause() == null ? "1 = 1" : pgCqlQuery.getWhereClause()); + String sqlQuery = "SELECT * FROM " + from + + (sqlOrderBy == null ? "" : " ORDER BY " + sqlOrderBy) + + " LIMIT " + limit + " OFFSET " + offset; + + log.debug("createSqlQuery: SQL: {}", sqlQuery); + return Pair.of(sqlQuery, from); + } +} diff --git a/src/main/java/org/folio/print/server/storage/UserException.java b/src/main/java/org/folio/print/server/storage/UserException.java new file mode 100644 index 0000000..1f61369 --- /dev/null +++ b/src/main/java/org/folio/print/server/storage/UserException.java @@ -0,0 +1,7 @@ +package org.folio.print.server.storage; + +public class UserException extends RuntimeException { + public UserException(String msg) { + super(msg); + } +} diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties new file mode 100644 index 0000000..faaac39 --- /dev/null +++ b/src/main/resources/log4j2.properties @@ -0,0 +1,18 @@ +status = error +name = PropertiesConfig + +filters = threshold + +filter.threshold.type = ThresholdFilter +filter.threshold.level = info + +appenders = console + +appender.console.type = Console +appender.console.name = STDOUT +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %d{HH:mm:ss} %-5p %-20.20C{1} %m%n + +rootLogger.level = info +rootLogger.appenderRefs = info +rootLogger.appenderRef.stdout.ref = STDOUT diff --git a/src/main/resources/openapi/batchPrint.yaml b/src/main/resources/openapi/batchPrint.yaml new file mode 100644 index 0000000..db7453c --- /dev/null +++ b/src/main/resources/openapi/batchPrint.yaml @@ -0,0 +1,233 @@ +openapi: 3.0.0 +info: + title: Batch printing + version: v1 +paths: + /print/entries: + parameters: + - $ref: headers/okapi-permissions.yaml + - $ref: headers/okapi-tenant.yaml + - $ref: headers/okapi-token.yaml + - $ref: headers/okapi-url.yaml + - $ref: headers/okapi-user.yaml + - $ref: parameters/limit.yaml + - $ref: parameters/offset.yaml + - $ref: parameters/query.yaml + get: + description: > + Get batch printing entries with optional CQL query. + X-Okapi-Permissions must include mod-batch-print.print.read + operationId: getPrintEntries + responses: + "200": + description: Print entries + content: + application/json: + schema: + $ref: schemas/entries.json + "400": + $ref: "#/components/responses/trait_400" + "404": + $ref: "#/components/responses/trait_404" + "500": + $ref: "#/components/responses/trait_500" + post: + description: > + Create print entry. + X-Okapi-Permissions must include mod-batch-print.print.write + operationId: postPrintEntry + requestBody: + content: + application/json: + schema: + $ref: schemas/entry.json + responses: + "204": + description: Print entry created + "400": + $ref: "#/components/responses/trait_400" + "403": + $ref: "#/components/responses/trait_403" + "413": + $ref: "#/components/responses/trait_413" + "500": + $ref: "#/components/responses/trait_500" + /print/entries/{id}: + parameters: + - $ref: headers/okapi-permissions.yaml + - $ref: headers/okapi-tenant.yaml + - $ref: headers/okapi-token.yaml + - $ref: headers/okapi-url.yaml + - $ref: headers/okapi-user.yaml + - in: path + name: id + required: true + description: Print entry identifier + schema: + type: string + format: uuid + get: + description: > + Get print entry by id. + X-Okapi-Permissions must include mod-batch-print.print.read + operationId: getPrintEntry + responses: + "200": + description: Print entry + content: + application/json: + schema: + $ref: schemas/entry.json + "400": + $ref: "#/components/responses/trait_400" + "403": + $ref: "#/components/responses/trait_403" + "404": + $ref: "#/components/responses/trait_404" + "500": + $ref: "#/components/responses/trait_500" + delete: + description: > + Delete print entry. + X-Okapi-Permissions must include mod-batch-print.print.write + operationId: deletePrintEntry + responses: + "204": + description: Print entry deleted + "400": + $ref: "#/components/responses/trait_400" + "404": + $ref: "#/components/responses/trait_404" + "500": + $ref: "#/components/responses/trait_500" + put: + description: > + Update print entry. + X-Okapi-Permissions must include mod-batch-print.print.write + operationId: updatePrintEntry + requestBody: + content: + application/json: + schema: + $ref: schemas/entry.json + responses: + "204": + description: Print entry update + "400": + $ref: "#/components/responses/trait_400" + "404": + $ref: "#/components/responses/trait_404" + "500": + $ref: "#/components/responses/trait_500" + /mail: + parameters: + - $ref: headers/okapi-permissions.yaml + - $ref: headers/okapi-tenant.yaml + - $ref: headers/okapi-token.yaml + - $ref: headers/okapi-url.yaml + - $ref: headers/okapi-user.yaml + post: + description: > + Send mail to create print entry. + X-Okapi-Permissions must include mod-batch-print.print.write + operationId: saveMail + requestBody: + content: + application/json: + schema: + $ref: schemas/messageRequest.json + responses: + "200": + description: Print entry created + content: + application/json: + schema: + $ref: schemas/messageResponse.json + "400": + $ref: "#/components/responses/trait_400" + "403": + $ref: "#/components/responses/trait_403" + "500": + $ref: "#/components/responses/trait_500" + /print/batch-creation: + parameters: + - $ref: headers/okapi-permissions.yaml + - $ref: headers/okapi-tenant.yaml + - $ref: headers/okapi-token.yaml + - $ref: headers/okapi-url.yaml + - $ref: headers/okapi-user.yaml + post: + description: > + Create batch print entry for day. + X-Okapi-Permissions must include mod-batch-print.print.write and mod-batch-print.print.read + requestBody: + content: + application/json: + schema: + $ref: schemas/messageRequest.json + responses: + "200": + description: Batch created + content: + application/json: + schema: + $ref: schemas/messageRequest.json + "400": + $ref: "#/components/responses/trait_400" + "403": + $ref: "#/components/responses/trait_403" + "500": + $ref: "#/components/responses/trait_500" + +components: + responses: + trait_400: + description: Bad request + content: + text/plain: + schema: + type: string + example: Invalid JSON in request + application/json: + schema: + type: object + example: {"error":"Invalid JSON in request"} + trait_403: + description: Forbidden + content: + text/plain: + schema: + type: string + example: Insufficient permissions to access resource + application/json: + schema: + type: object + example: {"error":"Insufficient permissions to access resource"} + trait_404: + description: Not Found + content: + text/plain: + schema: + type: string + example: Identifier 596d9f60-cda3-44d2-a4a1-2f48b7d4d23c not found + application/json: + schema: + type: object + example: {"error":"Identifier 596d9f60-cda3-44d2-a4a1-2f48b7d4d23c not found"} + trait_413: + description: Payload Too Large + content: + text/plain: + schema: + type: string + trait_500: + description: Internal error + content: + text/plain: + schema: + type: string + example: Internal server error, contact administrator + schemas: + errors: + $ref: schemas/errors.json + diff --git a/src/main/resources/openapi/examples/errors.sample b/src/main/resources/openapi/examples/errors.sample new file mode 100644 index 0000000..03d7c12 --- /dev/null +++ b/src/main/resources/openapi/examples/errors.sample @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "message": "may not be null", + "type": "1", + "code": "-1", + "parameters": [ + { + "key": "moduleTo", + "value": "null" + } + ] + } + ] +} diff --git a/src/main/resources/openapi/examples/tenantAttributes.sample b/src/main/resources/openapi/examples/tenantAttributes.sample new file mode 100644 index 0000000..3b92024 --- /dev/null +++ b/src/main/resources/openapi/examples/tenantAttributes.sample @@ -0,0 +1,7 @@ +{ + "module_to": "module-1.1", + "module_from": "module-1.0", + "parameters": [ + {"ref": "core"} + ] +} diff --git a/src/main/resources/openapi/headers/okapi-permissions.yaml b/src/main/resources/openapi/headers/okapi-permissions.yaml new file mode 100644 index 0000000..e76d721 --- /dev/null +++ b/src/main/resources/openapi/headers/okapi-permissions.yaml @@ -0,0 +1,6 @@ +in: header +name: X-Okapi-Permissions +description: A JSON array with client permissions +required: true +schema: + type: string diff --git a/src/main/resources/openapi/headers/okapi-tenant.yaml b/src/main/resources/openapi/headers/okapi-tenant.yaml new file mode 100644 index 0000000..cd447f3 --- /dev/null +++ b/src/main/resources/openapi/headers/okapi-tenant.yaml @@ -0,0 +1,7 @@ +in: header +name: X-Okapi-Tenant +description: Okapi Tenant +required: true +schema: + type: string + pattern: '^[_a-z][_a-z0-9]*$' diff --git a/src/main/resources/openapi/headers/okapi-token.yaml b/src/main/resources/openapi/headers/okapi-token.yaml new file mode 100644 index 0000000..6de6cb2 --- /dev/null +++ b/src/main/resources/openapi/headers/okapi-token.yaml @@ -0,0 +1,6 @@ +in: header +name: X-Okapi-Token +description: Okapi Token +required: false +schema: + type: string diff --git a/src/main/resources/openapi/headers/okapi-url.yaml b/src/main/resources/openapi/headers/okapi-url.yaml new file mode 100644 index 0000000..4febf2b --- /dev/null +++ b/src/main/resources/openapi/headers/okapi-url.yaml @@ -0,0 +1,6 @@ +in: header +name: X-Okapi-Url +description: Okapi URL +required: false +schema: + type: string diff --git a/src/main/resources/openapi/headers/okapi-user.yaml b/src/main/resources/openapi/headers/okapi-user.yaml new file mode 100644 index 0000000..d25ed73 --- /dev/null +++ b/src/main/resources/openapi/headers/okapi-user.yaml @@ -0,0 +1,6 @@ +in: header +name: X-Okapi-User-Id +description: Okapi user identifier +required: false +schema: + type: string diff --git a/src/main/resources/openapi/parameters/count.yaml b/src/main/resources/openapi/parameters/count.yaml new file mode 100644 index 0000000..dc7b9ad --- /dev/null +++ b/src/main/resources/openapi/parameters/count.yaml @@ -0,0 +1,10 @@ +in: query +name: count +description: control of counting in queries +required: false +schema: + type: string + default: none + enum: + - exact + - none diff --git a/src/main/resources/openapi/parameters/limit.yaml b/src/main/resources/openapi/parameters/limit.yaml new file mode 100644 index 0000000..362dd04 --- /dev/null +++ b/src/main/resources/openapi/parameters/limit.yaml @@ -0,0 +1,8 @@ +in: query +name: limit +description: Limit the number of elements returned in the response +required: false +schema: + type: integer + default: 10 + minimum: 0 diff --git a/src/main/resources/openapi/parameters/offset.yaml b/src/main/resources/openapi/parameters/offset.yaml new file mode 100644 index 0000000..ff9864f --- /dev/null +++ b/src/main/resources/openapi/parameters/offset.yaml @@ -0,0 +1,8 @@ +in: query +name: offset +description: Skip over number of elements (default is first element) +required: false +schema: + type: integer + default: 0 + minimum: 0 diff --git a/src/main/resources/openapi/parameters/query.yaml b/src/main/resources/openapi/parameters/query.yaml new file mode 100644 index 0000000..46f1447 --- /dev/null +++ b/src/main/resources/openapi/parameters/query.yaml @@ -0,0 +1,6 @@ +in: query +name: query +description: CQL query +required: false +schema: + type: string diff --git a/src/main/resources/openapi/schemas/entries.json b/src/main/resources/openapi/schemas/entries.json new file mode 100644 index 0000000..908f182 --- /dev/null +++ b/src/main/resources/openapi/schemas/entries.json @@ -0,0 +1,23 @@ +{ + "description": "Print entries response", + "type": "object", + "properties": { + "items": { + "description": "List of print entries", + "type": "array", + "items": { + "type": "object", + "$ref": "entry.json" + } + }, + "resultInfo": { + "description": "Common result set information", + "type": "object", + "$ref" : "resultInfo.json" + } + }, + "additionalProperties": false, + "required": [ + "items" + ] +} diff --git a/src/main/resources/openapi/schemas/entry.json b/src/main/resources/openapi/schemas/entry.json new file mode 100644 index 0000000..a9d2b1f --- /dev/null +++ b/src/main/resources/openapi/schemas/entry.json @@ -0,0 +1,27 @@ +{ + "description": "Print entry", + "type": "object", + "properties": { + "id": { + "description": "Identifier", + "type": "string", + "format": "uuid" + }, + "created": { + "type": "string", + "description": "Creation date time" + }, + "type": { + "type": "string", + "description": "Print entry type" + }, + "content": { + "type": "string", + "description": "Print entry content" + } + }, + "additionalProperties": false, + "required": [ + "id", "created", "type", "content" + ] +} diff --git a/src/main/resources/openapi/schemas/error.json b/src/main/resources/openapi/schemas/error.json new file mode 100644 index 0000000..97a99a9 --- /dev/null +++ b/src/main/resources/openapi/schemas/error.json @@ -0,0 +1,27 @@ +{ + "description": "An error", + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "Error message text" + }, + "type": { + "type": "string", + "description": "Error message type" + }, + "code": { + "type": "string", + "description": "Error message code" + }, + "parameters": { + "type": "object", + "description": "Error message parameters", + "$ref": "parameters.json" + } + }, + "additionalProperties": false, + "required": [ + "message" + ] +} diff --git a/src/main/resources/openapi/schemas/errors.json b/src/main/resources/openapi/schemas/errors.json new file mode 100644 index 0000000..b358d4f --- /dev/null +++ b/src/main/resources/openapi/schemas/errors.json @@ -0,0 +1,19 @@ +{ + "description": "A set of errors", + "type": "object", + "properties": { + "errors": { + "description": "List of errors", + "type": "array", + "items": { + "type": "object", + "$ref": "error.json" + } + }, + "total_records": { + "description": "Total number of errors", + "type": "integer" + } + }, + "additionalProperties": false +} diff --git a/src/main/resources/openapi/schemas/messageRequest.json b/src/main/resources/openapi/schemas/messageRequest.json new file mode 100644 index 0000000..9de6025 --- /dev/null +++ b/src/main/resources/openapi/schemas/messageRequest.json @@ -0,0 +1,27 @@ +{ + "description": "The mail message that can be sent via mail", + "title": "Mail Entity Schema", + "type": "object", + "properties": { + "deliveryChannel": { + "description":"Delivery channel", + "type": "string" + }, + "from": { + "description":"sender's address", + "type": "string" + }, + "outputFormat": { + "description":"format type: `text/html` or `text/plain`", + "type": "string" + }, + "body": { + "description":"text of email", + "type": "string" + } + }, + "additionalProperties": true, + "required": [ + "body" + ] +} diff --git a/src/main/resources/openapi/schemas/messageResponse.json b/src/main/resources/openapi/schemas/messageResponse.json new file mode 100644 index 0000000..eec7309 --- /dev/null +++ b/src/main/resources/openapi/schemas/messageResponse.json @@ -0,0 +1,15 @@ +{ + "description": "Mail message response", + "type": "object", + "properties": { + "id": { + "description": "Identifier", + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": true, + "required": [ + "id" + ] +} diff --git a/src/main/resources/openapi/schemas/parameter.json b/src/main/resources/openapi/schemas/parameter.json new file mode 100644 index 0000000..a1a8f55 --- /dev/null +++ b/src/main/resources/openapi/schemas/parameter.json @@ -0,0 +1,18 @@ +{ + "description": "List of key/value parameters of an error", + "type": "object", + "properties": { + "key": { + "description": "The key for this parameter", + "type": "string" + }, + "value": { + "description": "The value of this parameter", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "key" + ] +} diff --git a/src/main/resources/openapi/schemas/parameters.json b/src/main/resources/openapi/schemas/parameters.json new file mode 100644 index 0000000..23d8eac --- /dev/null +++ b/src/main/resources/openapi/schemas/parameters.json @@ -0,0 +1,9 @@ +{ + "description": "List of key/value parameters of an error", + "type": "array", + "items": { + "type": "object", + "$ref": "parameter.json" + }, + "additionalProperties": false +} diff --git a/src/main/resources/openapi/schemas/resultInfo.json b/src/main/resources/openapi/schemas/resultInfo.json new file mode 100644 index 0000000..93081b4 --- /dev/null +++ b/src/main/resources/openapi/schemas/resultInfo.json @@ -0,0 +1,55 @@ +{ + "description": "Common result set information for streaming response", + "type": "object", + "properties": { + "totalRecords": { + "description": "Total number of entries in response", + "type": "integer" + }, + "diagnostics": { + "description": "Diagnostics for response", + "type": "array", + "items": { + "type": "object", + "properties": { + "message": { + "description": "single diagnostic message", + "type": "string" + } + } + } + }, + "facets": { + "type": "array", + "description": "Array of facets", + "items": { + "type": "object", + "description": "A facet", + "properties": { + "facetValues": { + "type": "array", + "description": "Array of facet values", + "items": { + "type": "object", + "description": "A facet value", + "properties": { + "count": { + "type": "integer", + "description": "Count of facet values" + }, + "value": { + "description": "Value Object" + } + } + } + }, + "type": { + "type": "string", + "description": "Type of facet" + } + } + } + } + }, + "additionalProperties": false +} diff --git a/src/test/java/org/folio/print/server/TestBase.java b/src/test/java/org/folio/print/server/TestBase.java new file mode 100644 index 0000000..f5af6be --- /dev/null +++ b/src/test/java/org/folio/print/server/TestBase.java @@ -0,0 +1,147 @@ +package org.folio.print.server; + +import io.restassured.RestAssured; +import io.restassured.builder.RequestSpecBuilder; +import io.restassured.config.HttpClientConfig; +import io.restassured.config.RestAssuredConfig; +import io.vertx.core.DeploymentOptions; +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.web.Route; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.client.WebClient; +import io.vertx.ext.web.client.predicate.ResponsePredicate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.folio.print.server.main.MainVerticle; +import org.folio.tlib.postgres.testing.TenantPgPoolContainer; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.testcontainers.containers.PostgreSQLContainer; +import org.xml.sax.SAXException; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class TestBase { + protected final static Logger log = LogManager.getLogger("TestBase"); + protected static Vertx vertx; + protected static WebClient webClient; + protected static final int OKAPI_PORT = 9230; + protected static final String OKAPI_URL = "http://localhost:" + OKAPI_PORT; + protected static final int MODULE_PORT = 9231; + protected static final String MODULE_URL = "http://localhost:" + MODULE_PORT; + protected static final String TENANT_1 = "tenant1"; + protected static final String TENANT_2 = "tenant2"; + protected static final String MODULE_PREFIX = "mod-batch-print"; + protected static final String MODULE_VERSION = "1.0.0"; + protected static final String MODULE_ID = MODULE_PREFIX + "-" + MODULE_VERSION; + + public static PostgreSQLContainer postgresSQLContainer; + + @AfterClass + public static void afterClass(TestContext context) { + postgresSQLContainer.close(); + Future.succeededFuture() + .compose(x -> vertx.close()) + .onComplete(x -> log.info("vertx close completed")) + .onComplete(context.asyncAssertSuccess()); + } + + @BeforeClass + public static void beforeClass(TestContext context) throws IOException, SAXException { + postgresSQLContainer = TenantPgPoolContainer.create(); + + vertx = Vertx.vertx(); + webClient = WebClient.create(vertx); + + RestAssured.config = RestAssuredConfig.config() + .httpClient(HttpClientConfig.httpClientConfig() + .setParam("http.socket.timeout", 15000) + .setParam("http.connection.timeout", 5000)); + + RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); + RestAssured.baseURI = OKAPI_URL; + RestAssured.requestSpecification = new RequestSpecBuilder().build(); + + Future f = Future.succeededFuture(); + + // deploy this module + f = f.compose(e -> { + DeploymentOptions deploymentOptions = new DeploymentOptions(); + deploymentOptions.setConfig(new JsonObject().put("port", Integer.toString(MODULE_PORT))); + return vertx.deployVerticle(new MainVerticle(), deploymentOptions) + .mapEmpty(); + }); + + // deploy okapi + DeploymentOptions okapiOptions = new DeploymentOptions(); + okapiOptions.setConfig(new JsonObject() + .put("port", Integer.toString(OKAPI_PORT)) + .put("mode", "proxy") + ); + f = f.compose(e -> vertx.deployVerticle(new org.folio.okapi.MainVerticle(), okapiOptions)) + .mapEmpty(); + + String md = Files.readString(Path.of("descriptors/ModuleDescriptor-template.json")) + .replace("${artifactId}", MODULE_PREFIX) + .replace("${version}", MODULE_VERSION); + log.info("Module .. {}", md); + + // register module + f = f.compose(t -> + webClient.postAbs(OKAPI_URL + "/_/proxy/modules") + .expect(ResponsePredicate.SC_CREATED) + .sendJsonObject(new JsonObject(md)) + .mapEmpty()); + + // tell okapi where our module is running + f = f.compose(t -> + webClient.postAbs(OKAPI_URL + "/_/discovery/modules") + .expect(ResponsePredicate.SC_CREATED) + .sendJsonObject(new JsonObject() + .put("instId", MODULE_ID) + .put("srvcId", MODULE_ID) + .put("url", MODULE_URL)) + .mapEmpty()); + + // create tenant 1 + f = f.compose(t -> + webClient.postAbs(OKAPI_URL + "/_/proxy/tenants") + .expect(ResponsePredicate.SC_CREATED) + .sendJsonObject(new JsonObject().put("id", TENANT_1)) + .mapEmpty()); + + // enable module for tenant 1 + f = f.compose(e -> + webClient.postAbs(OKAPI_URL + "/_/proxy/tenants/" + TENANT_1 + "/install") + .expect(ResponsePredicate.SC_OK) + .sendJson(new JsonArray().add(new JsonObject() + .put("id", MODULE_PREFIX) + .put("action", "enable"))) + .mapEmpty()); + + // create tenant 2 + f = f.compose(t -> + webClient.postAbs(OKAPI_URL + "/_/proxy/tenants") + .expect(ResponsePredicate.SC_CREATED) + .sendJsonObject(new JsonObject().put("id", TENANT_2)) + .mapEmpty()); + + // enable module for tenant 2 + f = f.compose(e -> + webClient.postAbs(OKAPI_URL + "/_/proxy/tenants/" + TENANT_2 + "/install") + .expect(ResponsePredicate.SC_OK) + .sendJson(new JsonArray().add(new JsonObject() + .put("id", MODULE_PREFIX) + .put("action", "enable"))) + .mapEmpty()); + + f.onComplete(context.asyncAssertSuccess()); + } + +} diff --git a/src/test/java/org/folio/print/server/main/MainVerticleTest.java b/src/test/java/org/folio/print/server/main/MainVerticleTest.java new file mode 100644 index 0000000..d814162 --- /dev/null +++ b/src/test/java/org/folio/print/server/main/MainVerticleTest.java @@ -0,0 +1,403 @@ +package org.folio.print.server.main; + +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.unit.junit.VertxUnitRunner; + +import java.io.IOException; +import java.io.InputStream; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Optional; +import java.util.UUID; +import org.folio.okapi.common.XOkapiHeaders; +import org.folio.print.server.TestBase; +import org.folio.print.server.data.Message; +import org.folio.print.server.data.PrintEntry; +import org.folio.print.server.data.PrintEntryType; +import org.folio.print.server.service.PrintService; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; + +@RunWith(VertxUnitRunner.class) +public class MainVerticleTest extends TestBase { + + private JsonArray permRead = new JsonArray().add("mod-batch-print.print.read"); + private JsonArray permWrite = new JsonArray().add("mod-batch-print.print.write"); + @Test + public void testAdminHealth() { + RestAssured.given() + .baseUri(MODULE_URL) + .get("/admin/health") + .then() + .statusCode(200) + .contentType(ContentType.TEXT); + } + + @Test + public void testCrudGlobalOk() { + PrintEntry entry = new PrintEntry(); + entry.setContent("AA"); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + + JsonObject en = JsonObject.mapFrom(entry); + + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(204); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .get("/print/entries/" + entry.getId()) + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body(is(en.encode())); + + entry.setContent("BB"); + en = JsonObject.mapFrom(entry); + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .put("/print/entries/" + entry.getId()) + .then() + .statusCode(204); + + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .delete("/print/entries/" + entry.getId()) + .then() + .statusCode(204); + } + + @Test + public void testPostMissingTenant() { + PrintEntry entry = new PrintEntry(); + entry.setContent("AA"); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + + JsonObject en = JsonObject.mapFrom(entry); + JsonArray permWrite = new JsonArray().add("mod-batch-print.print.write"); + + RestAssured.given() + .baseUri(MODULE_URL) // if not, Okapi will intercept + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(400) + .contentType(ContentType.TEXT) + .body(containsString("Missing parameter X-Okapi-Tenant")); + } + + @Test + public void testMissingPermissionsHeader() { + PrintEntry entry = new PrintEntry(); + entry.setContent("AA"); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + + JsonObject en = JsonObject.mapFrom(entry); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(400) + .contentType(ContentType.TEXT) + .body(containsString("Missing parameter X-Okapi-Permissions in HEADER")); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .contentType(ContentType.JSON) + .get("/print/entries") + .then() + .statusCode(400) + .contentType(ContentType.TEXT) + .body(containsString("Missing parameter X-Okapi-Permissions in HEADER")); + } + + @Test + public void testPostInvalidEntry() { + PrintEntry entry = new PrintEntry(); + entry.setId(UUID.randomUUID()); + + JsonObject en = JsonObject.mapFrom(entry); + JsonArray permWrite = new JsonArray().add("mod-batch-print.print.write"); + + RestAssured.given() + .baseUri(MODULE_URL) // if not, Okapi will intercept + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(400) + .contentType(ContentType.TEXT) + .body(containsString("provided object should contain property created")); + } + + @Test + public void testPostBodyTooBig() { + PrintEntry entry = new PrintEntry(); + entry.setContent("A".repeat(PrintService.BODY_LIMIT)); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + + JsonObject en = JsonObject.mapFrom(entry); + + RestAssured.given() + .baseUri(MODULE_URL) // if not, Okapi will intercept + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(413) + .contentType(ContentType.TEXT) + .body(is("Request Entity Too Large")); + } + + @Test + public void testMissingPermissions() { + PrintEntry entry = new PrintEntry(); + entry.setContent("AA"); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + + JsonObject en = JsonObject.mapFrom(entry); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(403); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .put("/print/entries/" + en.getString("id")) + .then() + .statusCode(403); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(204); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .get("/print/entries/" + en.getString("id")) + .then() + .statusCode(403); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .delete("/print/entries/" + en.getString("id")) + .then() + .statusCode(403); + } + + @Test + public void testNotFound() { + PrintEntry entry = new PrintEntry(); + entry.setContent("AA"); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setId(UUID.randomUUID()); + entry.setType(PrintEntryType.SINGLE); + + JsonObject en = JsonObject.mapFrom(entry); + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead) + .get("/print/entries/" + UUID.randomUUID()) + .then() + .statusCode(404); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead) + .delete("/print/entries/" + UUID.randomUUID()) + .then() + .statusCode(404); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .put("/print/entries/" + en.getString("id")) + .then() + .statusCode(404); + } + + @Test + public void testGetPrintEntries() { + PrintEntry entry = new PrintEntry(); + entry.setCreated(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC)); + entry.setType(PrintEntryType.SINGLE); + String[] ids = new String[3]; + for (int i = 0; i < 3; i++) { + entry.setId(UUID.randomUUID()); + entry.setContent("A" + i); + entry.setType(i % 2 == 0 ? PrintEntryType.SINGLE : PrintEntryType.BATCH); + JsonObject en = JsonObject.mapFrom(entry); + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(en.encode()) + .post("/print/entries") + .then() + .statusCode(204); + ids[0] = entry.getId().toString(); + } + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .get("/print/entries") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("items", hasSize(3)) + .body("resultInfo.totalRecords", is(3)); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .queryParam("limit", 0) + .get("/print/entries") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("items", hasSize(0)) + .body("resultInfo.totalRecords", is(3)); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .queryParam("query", "type=\"SINGLE\"") + .get("/print/entries") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("items", hasSize(2)) + .body("resultInfo.totalRecords", is(2)); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .queryParam("query", "type=\"BATCH\"") + .get("/print/entries") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("items", hasSize(1)) + .body("resultInfo.totalRecords", is(1)); + + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .queryParam("query", "type=\"SINGLE\" and created > " + ZonedDateTime.now() + .withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime().minusHours(2)) + .get("/print/entries") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("items", hasSize(2)) + .body("resultInfo.totalRecords", is(2)); + cleanEntries(ids); + } + + @Test + public void testSaveMailMessage() throws IOException { + String message = getResourceAsString("mail/mail.json"); + + String id = RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .contentType(ContentType.JSON) + .body(message) + .post("/mail") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("id", notNullValue()) + .extract() + .path("id"); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permRead.encode()) + .get("/print/entries") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("items", hasSize(1)) + .body("resultInfo.totalRecords", is(1)); + + cleanEntries(id); + } + + private String getResourceAsString(String name) throws IOException { + try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name)) { + if (inputStream == null) { + throw new IOException("Resource not found: " + name); + } + return new String(inputStream.readAllBytes()); + } + } + + private void cleanEntries(String... ids){ + for(String id : ids){ + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, permWrite.encode()) + .delete("/print/entries/" + id) + .then() + .statusCode(204); + } + } +} diff --git a/src/test/java/org/folio/print/server/resources/BatchCreationResourceTest.java b/src/test/java/org/folio/print/server/resources/BatchCreationResourceTest.java new file mode 100644 index 0000000..47ee9e1 --- /dev/null +++ b/src/test/java/org/folio/print/server/resources/BatchCreationResourceTest.java @@ -0,0 +1,53 @@ +package org.folio.print.server.resources; + +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.vertx.core.json.JsonArray; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import org.folio.okapi.common.XOkapiHeaders; +import org.folio.print.server.TestBase; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.IOException; +import java.io.InputStream; + +import static org.hamcrest.Matchers.notNullValue; + +@RunWith(VertxUnitRunner.class) +public class BatchCreationResourceTest extends TestBase { + @Test + public void createBatch() throws IOException { + String message = getResourceAsString("mail/mail.json"); + + JsonArray perm = new JsonArray().add("mod-batch-print.print.write").add("mod-batch-print.print.read"); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, perm.encode()) + .contentType(ContentType.JSON) + .body(message) + .post("/mail") + .then() + .statusCode(200) + .contentType(ContentType.JSON) + .body("id", notNullValue()); + + RestAssured.given() + .header(XOkapiHeaders.TENANT, TENANT_1) + .header(XOkapiHeaders.PERMISSIONS, perm.encode()) + .contentType(ContentType.JSON) + .post("/print/batch-creation") + .then() + .statusCode(200); + } + + private String getResourceAsString(String name) throws IOException { + try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name)) { + if (inputStream == null) { + throw new IOException("Resource not found: " + name); + } + return new String(inputStream.readAllBytes()); + } + } +} diff --git a/src/test/resources/mail/mail.json b/src/test/resources/mail/mail.json new file mode 100644 index 0000000..6d3bacc --- /dev/null +++ b/src/test/resources/mail/mail.json @@ -0,0 +1,8 @@ +{ + "deliveryChannel": "mail", + "from": "user@mail.com", + "outputFormat": "text/html", + "header": "okapi", + "body": "
Dear James

you were charged a Lost item fee
amount: 10.00

Owner: Test owner for cd1
Type: Lost item fee
Status: Cancelled item returned
Date: 1/4/24
Time: 1/4/24, 12:12 PM
Amount: 10.00
Remaining: 0.00
Info:
", + "attachments": [] +}