Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7874d18f32 | ||
|
|
1e968c79f6 | ||
|
|
e2b88cf8b4 | ||
|
|
da49b50d27 | ||
|
|
970679640d | ||
|
|
4883573e87 | ||
|
|
18f571291b | ||
|
|
0abcc0ccb8 | ||
|
|
a99c104053 | ||
|
|
95fbd4647d | ||
|
|
8d4f5f16cb | ||
|
|
63fdb958ef | ||
|
|
2ee43b2070 | ||
|
|
55b9286958 | ||
|
|
3cc3037408 | ||
|
|
70a9b5f009 | ||
|
|
92f5c5de7a | ||
|
|
b08bc191fc | ||
|
|
d12aca0ca6 | ||
|
|
5ec78b5425 | ||
|
|
3bec51f4e5 | ||
|
|
d83d8b4748 | ||
|
|
03d27013d6 | ||
|
|
679ecdd50d | ||
|
|
02aad40aa0 | ||
|
|
0328333d81 | ||
|
|
631c4fef0b | ||
|
|
209c76d885 | ||
|
|
3293d0d8a1 | ||
|
|
45462dc5d4 | ||
|
|
c0e93cd5e5 | ||
|
|
2217cfb95d | ||
|
|
214404b5c9 | ||
|
|
ddc2daea52 | ||
|
|
ff602a20a0 | ||
|
|
85ac1259af | ||
|
|
4acfc713e9 | ||
|
|
e9f46aec53 | ||
|
|
909c0aed7a | ||
|
|
c9879c1d28 | ||
|
|
38e472a631 | ||
|
|
bedc3d02d7 | ||
|
|
be1a9cc8da | ||
|
|
055c642136 | ||
|
|
61521b5bf3 | ||
|
|
ccf1b23d67 | ||
|
|
14f76b6146 | ||
|
|
6780bb4a30 | ||
|
|
feb84f001c | ||
|
|
8c061ea644 | ||
|
|
ea5515b614 | ||
|
|
b1a6e1b481 |
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(mkdir:*)",
|
||||||
|
"Bash(./gradlew:*)",
|
||||||
|
"Bash(grep:*)",
|
||||||
|
"Bash(find:*)",
|
||||||
|
"Bash(chmod:*)",
|
||||||
|
"Bash(rm:*)",
|
||||||
|
"Bash(cat:*)",
|
||||||
|
"Bash(if [ -d logs ])",
|
||||||
|
"Bash(then ls -la logs/)",
|
||||||
|
"Bash(fi)",
|
||||||
|
"Bash(ls:*)",
|
||||||
|
"Bash(./testing/cucumber/features/environment.py -v)",
|
||||||
|
"Bash(./testing/cucumber/features/autojob.feature -v)"
|
||||||
|
],
|
||||||
|
"deny": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
name: 'Setup GitHub App Bot'
|
||||||
|
description: 'Generates a GitHub App Token and configures Git for a bot'
|
||||||
|
inputs:
|
||||||
|
app-id:
|
||||||
|
description: 'GitHub App ID'
|
||||||
|
required: True
|
||||||
|
private-key:
|
||||||
|
description: 'GitHub App Private Key'
|
||||||
|
required: True
|
||||||
|
outputs:
|
||||||
|
token:
|
||||||
|
description: 'Generated GitHub App Token'
|
||||||
|
value: ${{ steps.generate-token.outputs.token }}
|
||||||
|
committer:
|
||||||
|
description: 'Committer string for Git'
|
||||||
|
value: "${{ steps.generate-token.outputs.app-slug }}[bot] <${{ steps.generate-token.outputs.app-slug }}[bot]@users.noreply.github.com>"
|
||||||
|
app-slug:
|
||||||
|
description: 'GitHub App slug'
|
||||||
|
value: ${{ steps.generate-token.outputs.app-slug }}
|
||||||
|
runs:
|
||||||
|
using: 'composite'
|
||||||
|
steps:
|
||||||
|
- name: Generate a GitHub App Token
|
||||||
|
id: generate-token
|
||||||
|
uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6
|
||||||
|
with:
|
||||||
|
app-id: ${{ inputs.app-id }}
|
||||||
|
private-key: ${{ inputs.private-key }}
|
||||||
|
- name: Configure Git
|
||||||
|
run: |
|
||||||
|
git config --global user.name "${{ steps.generate-token.outputs.app-slug }}[bot]"
|
||||||
|
git config --global user.email "${{ steps.generate-token.outputs.app-slug }}[bot]@users.noreply.github.com"
|
||||||
|
shell: bash
|
||||||
@@ -180,7 +180,7 @@ jobs:
|
|||||||
password: ${{ secrets.DOCKER_HUB_API }}
|
password: ${{ secrets.DOCKER_HUB_API }}
|
||||||
|
|
||||||
- name: Build and push PR-specific image
|
- name: Build and push PR-specific image
|
||||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
|
|||||||
@@ -56,6 +56,9 @@ jobs:
|
|||||||
build/reports/tests/
|
build/reports/tests/
|
||||||
build/test-results/
|
build/test-results/
|
||||||
build/reports/problems/
|
build/reports/problems/
|
||||||
|
common/build/reports/tests/
|
||||||
|
common/build/test-results/
|
||||||
|
common/build/reports/problems/
|
||||||
retention-days: 3
|
retention-days: 3
|
||||||
|
|
||||||
check-licence:
|
check-licence:
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
issues: write # Allow posting comments on issues/PRs
|
issues: write # Allow posting comments on issues/PRs
|
||||||
pull-requests: write
|
pull-requests: write # Allow writing to pull requests
|
||||||
steps:
|
steps:
|
||||||
- name: Harden Runner
|
- name: Harden Runner
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
@@ -25,15 +25,18 @@ jobs:
|
|||||||
- name: Checkout main branch first
|
- name: Checkout main branch first
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Setup GitHub App Bot
|
||||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
id: setup-bot
|
||||||
|
uses: ./.github/actions/setup-bot
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
app-id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
- name: Get PR data
|
- name: Get PR data
|
||||||
id: get-pr-data
|
id: get-pr-data
|
||||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||||
with:
|
with:
|
||||||
|
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||||
script: |
|
script: |
|
||||||
const prNumber = context.payload.pull_request.number;
|
const prNumber = context.payload.pull_request.number;
|
||||||
const repoOwner = context.payload.repository.owner.login;
|
const repoOwner = context.payload.repository.owner.login;
|
||||||
@@ -54,7 +57,7 @@ jobs:
|
|||||||
- name: Fetch PR changed files
|
- name: Fetch PR changed files
|
||||||
id: fetch-pr-changes
|
id: fetch-pr-changes
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ steps.setup-bot.outputs.token }}
|
||||||
run: |
|
run: |
|
||||||
echo "Fetching PR changed files..."
|
echo "Fetching PR changed files..."
|
||||||
echo "Getting list of changed files from PR..."
|
echo "Getting list of changed files from PR..."
|
||||||
@@ -64,6 +67,7 @@ jobs:
|
|||||||
id: determine-file
|
id: determine-file
|
||||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||||
with:
|
with:
|
||||||
|
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||||
script: |
|
script: |
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@@ -204,6 +208,7 @@ jobs:
|
|||||||
if: env.SCRIPT_OUTPUT != ''
|
if: env.SCRIPT_OUTPUT != ''
|
||||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||||
with:
|
with:
|
||||||
|
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||||
script: |
|
script: |
|
||||||
const { GITHUB_REPOSITORY, SCRIPT_OUTPUT } = process.env;
|
const { GITHUB_REPOSITORY, SCRIPT_OUTPUT } = process.env;
|
||||||
const [repoOwner, repoName] = GITHUB_REPOSITORY.split('/');
|
const [repoOwner, repoName] = GITHUB_REPOSITORY.split('/');
|
||||||
@@ -219,7 +224,7 @@ jobs:
|
|||||||
const comment = comments.data.find(c => c.body.includes("## 🚀 Translation Verification Summary"));
|
const comment = comments.data.find(c => c.body.includes("## 🚀 Translation Verification Summary"));
|
||||||
|
|
||||||
// Only update or create comments by the action user
|
// Only update or create comments by the action user
|
||||||
const expectedActor = "github-actions[bot]";
|
const expectedActor = "${{ steps.setup-bot.outputs.app-slug }}[bot]";
|
||||||
|
|
||||||
if (comment && comment.user.login === expectedActor) {
|
if (comment && comment.user.login === expectedActor) {
|
||||||
// Update existing comment
|
// Update existing comment
|
||||||
|
|||||||
@@ -16,52 +16,50 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
repository-projects: write # Required for enabling automerge
|
||||||
steps:
|
steps:
|
||||||
- name: Harden Runner
|
- name: Harden Runner
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Generate GitHub App Token
|
- name: Check out code
|
||||||
id: generate-token
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Setup GitHub App Bot
|
||||||
|
id: setup-bot
|
||||||
|
uses: ./.github/actions/setup-bot
|
||||||
with:
|
with:
|
||||||
app-id: ${{ secrets.GH_APP_ID }}
|
app-id: ${{ secrets.GH_APP_ID }}
|
||||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
- name: Check out code
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
|
|
||||||
- name: Set up JDK 17
|
- name: Set up JDK 17
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
||||||
with:
|
with:
|
||||||
java-version: "17"
|
java-version: "17"
|
||||||
distribution: "adopt"
|
distribution: "adopt"
|
||||||
|
|
||||||
- uses: gradle/actions/setup-gradle@8379f6a1328ee0e06e2bb424dadb7b159856a326 # v4.4.0
|
- name: Setup Gradle
|
||||||
|
uses: gradle/actions/setup-gradle@8379f6a1328ee0e06e2bb424dadb7b159856a326 # v4.4.0
|
||||||
|
|
||||||
- name: check the licenses for compatibility
|
- name: Check licenses for compatibility
|
||||||
run: ./gradlew clean checkLicense
|
run: ./gradlew clean checkLicense
|
||||||
|
|
||||||
- name: FAILED - check the licenses for compatibility
|
- name: Upload artifact on failure
|
||||||
if: failure()
|
if: failure()
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||||
with:
|
with:
|
||||||
name: dependencies-without-allowed-license.json
|
name: dependencies-without-allowed-license.json
|
||||||
path: |
|
path: build/reports/dependency-license/dependencies-without-allowed-license.json
|
||||||
build/reports/dependency-license/dependencies-without-allowed-license.json
|
|
||||||
retention-days: 3
|
retention-days: 3
|
||||||
|
|
||||||
- name: Move and Rename License File
|
- name: Move and rename license file
|
||||||
run: |
|
run: |
|
||||||
mv build/reports/dependency-license/index.json src/main/resources/static/3rdPartyLicenses.json
|
mv build/reports/dependency-license/index.json src/main/resources/static/3rdPartyLicenses.json
|
||||||
|
|
||||||
- name: Set up git config
|
- name: Commit changes
|
||||||
run: |
|
|
||||||
git config --global user.name "stirlingbot[bot]"
|
|
||||||
git config --global user.email "1113334+stirlingbot[bot]@users.noreply.github.com"
|
|
||||||
|
|
||||||
- name: Run git add
|
|
||||||
run: |
|
run: |
|
||||||
git add src/main/resources/static/3rdPartyLicenses.json
|
git add src/main/resources/static/3rdPartyLicenses.json
|
||||||
git diff --staged --quiet || echo "CHANGES_DETECTED=true" >> $GITHUB_ENV
|
git diff --staged --quiet || echo "CHANGES_DETECTED=true" >> $GITHUB_ENV
|
||||||
@@ -71,15 +69,15 @@ jobs:
|
|||||||
if: env.CHANGES_DETECTED == 'true'
|
if: env.CHANGES_DETECTED == 'true'
|
||||||
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
||||||
with:
|
with:
|
||||||
token: ${{ steps.generate-token.outputs.token }}
|
token: ${{ steps.setup-bot.outputs.token }}
|
||||||
commit-message: "Update 3rd Party Licenses"
|
commit-message: "Update 3rd Party Licenses"
|
||||||
committer: "stirlingbot[bot] <1113334+stirlingbot[bot]@users.noreply.github.com>"
|
committer: ${{ steps.setup-bot.outputs.committer }}
|
||||||
author: "stirlingbot[bot] <1113334+stirlingbot[bot]@users.noreply.github.com>"
|
author: ${{ steps.setup-bot.outputs.committer }}
|
||||||
signoff: true
|
signoff: true
|
||||||
branch: update-3rd-party-licenses
|
branch: update-3rd-party-licenses
|
||||||
title: "Update 3rd Party Licenses"
|
title: "Update 3rd Party Licenses"
|
||||||
body: |
|
body: |
|
||||||
Auto-generated by StirlingBot
|
Auto-generated by ${{ steps.setup-bot.outputs.app-slug }}[bot]
|
||||||
labels: licenses,github-actions
|
labels: licenses,github-actions
|
||||||
draft: false
|
draft: false
|
||||||
delete-branch: true
|
delete-branch: true
|
||||||
@@ -89,4 +87,4 @@ jobs:
|
|||||||
if: steps.cpr.outputs.pull-request-operation == 'created'
|
if: steps.cpr.outputs.pull-request-operation == 'created'
|
||||||
run: gh pr merge --squash --auto "${{ steps.cpr.outputs.pull-request-number }}"
|
run: gh pr merge --squash --auto "${{ steps.cpr.outputs.pull-request-number }}"
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ steps.generate-token.outputs.token }}
|
GH_TOKEN: ${{ steps.setup-bot.outputs.token }}
|
||||||
|
|||||||
@@ -20,58 +20,49 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Generate GitHub App Token
|
|
||||||
id: generate-token
|
|
||||||
uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6
|
|
||||||
with:
|
|
||||||
app-id: ${{ secrets.GH_APP_ID }}
|
|
||||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
|
||||||
|
|
||||||
- name: Get GitHub App User ID
|
|
||||||
id: get-user-id
|
|
||||||
run: echo "user-id=$(gh api "/users/${{ steps.generate-token.outputs.app-slug }}[bot]" --jq .id)" >> $GITHUB_OUTPUT
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ steps.generate-token.outputs.token }}
|
|
||||||
|
|
||||||
- id: committer
|
|
||||||
run: |
|
|
||||||
echo "string=${{ steps.generate-token.outputs.app-slug }}[bot] <${{ steps.get-user-id.outputs.user-id }}+${{ steps.generate-token.outputs.app-slug }}[bot]@users.noreply.github.com>" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Setup GitHub App Bot
|
||||||
|
id: setup-bot
|
||||||
|
uses: ./.github/actions/setup-bot
|
||||||
|
with:
|
||||||
|
app-id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||||
with:
|
with:
|
||||||
python-version: 3.12
|
python-version: 3.12
|
||||||
cache: 'pip' # caching pip dependencies
|
cache: 'pip' # caching pip dependencies
|
||||||
|
|
||||||
- name: Run Pre-Commit Hooks
|
- name: Run Pre-Commit Hooks
|
||||||
run: |
|
run: |
|
||||||
pip install --require-hashes -r ./.github/scripts/requirements_pre_commit.txt
|
pip install --require-hashes -r ./.github/scripts/requirements_pre_commit.txt
|
||||||
|
|
||||||
- run: pre-commit run --all-files -c .pre-commit-config.yaml
|
- run: pre-commit run --all-files -c .pre-commit-config.yaml
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
- name: Set up git config
|
|
||||||
run: |
|
|
||||||
git config --global user.name ${{ steps.generate-token.outputs.app-slug }}[bot]
|
|
||||||
git config --global user.email "${{ steps.get-user-id.outputs.user-id }}+${{ steps.generate-token.outputs.app-slug }}[bot]@users.noreply.github.com"
|
|
||||||
- name: git add
|
- name: git add
|
||||||
run: |
|
run: |
|
||||||
git add .
|
git add .
|
||||||
git diff --staged --quiet || echo "CHANGES_DETECTED=true" >> $GITHUB_ENV
|
git diff --staged --quiet || echo "CHANGES_DETECTED=true" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
if: env.CHANGES_DETECTED == 'true'
|
if: env.CHANGES_DETECTED == 'true'
|
||||||
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
||||||
with:
|
with:
|
||||||
token: ${{ steps.generate-token.outputs.token }}
|
token: ${{ steps.setup-bot.outputs.token }}
|
||||||
commit-message: ":file_folder: pre-commit"
|
commit-message: ":file_folder: pre-commit"
|
||||||
committer: ${{ steps.committer.outputs.string }}
|
committer: ${{ steps.setup-bot.outputs.committer }}
|
||||||
author: ${{ steps.committer.outputs.string }}
|
author: ${{ steps.setup-bot.outputs.committer }}
|
||||||
signoff: true
|
signoff: true
|
||||||
branch: pre-commit
|
branch: pre-commit
|
||||||
title: "🤖 format everything with pre-commit by <${{ steps.generate-token.outputs.app-slug }}>"
|
title: "🤖 format everything with pre-commit by ${{ steps.setup-bot.outputs.app-slug }}"
|
||||||
body: |
|
body: |
|
||||||
Auto-generated by [create-pull-request][1] with **${{ steps.generate-token.outputs.app-slug }}**
|
Auto-generated by [create-pull-request][1] with **${{ steps.setup-bot.outputs.app-slug }}**
|
||||||
|
|
||||||
[1]: https://github.com/peter-evans/create-pull-request
|
[1]: https://github.com/peter-evans/create-pull-request
|
||||||
draft: false
|
draft: false
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Build and push main Dockerfile
|
- name: Build and push main Dockerfile
|
||||||
id: build-push-regular
|
id: build-push-regular
|
||||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
with:
|
with:
|
||||||
builder: ${{ steps.buildx.outputs.name }}
|
builder: ${{ steps.buildx.outputs.name }}
|
||||||
context: .
|
context: .
|
||||||
@@ -135,7 +135,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Build and push Dockerfile-ultra-lite
|
- name: Build and push Dockerfile-ultra-lite
|
||||||
id: build-push-lite
|
id: build-push-lite
|
||||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
if: github.ref != 'refs/heads/main'
|
if: github.ref != 'refs/heads/main'
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
@@ -166,7 +166,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Build and push main Dockerfile fat
|
- name: Build and push main Dockerfile fat
|
||||||
id: build-push-fat
|
id: build-push-fat
|
||||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
if: github.ref != 'refs/heads/main'
|
if: github.ref != 'refs/heads/main'
|
||||||
with:
|
with:
|
||||||
builder: ${{ steps.buildx.outputs.name }}
|
builder: ${{ steps.buildx.outputs.name }}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ jobs:
|
|||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
- name: "Run analysis"
|
- name: "Run analysis"
|
||||||
uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1
|
uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2
|
||||||
with:
|
with:
|
||||||
results_file: results.sarif
|
results_file: results.sarif
|
||||||
results_format: sarif
|
results_format: sarif
|
||||||
|
|||||||
@@ -16,79 +16,37 @@ permissions:
|
|||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
read_bot_entries:
|
sync-files:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
|
||||||
userName: ${{ steps.get-user-id.outputs.user_name }}
|
|
||||||
userEmail: ${{ steps.get-user-id.outputs.user_email }}
|
|
||||||
committer: ${{ steps.committer.outputs.committer }}
|
|
||||||
steps:
|
steps:
|
||||||
- name: Harden Runner
|
- name: Harden Runner
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Generate GitHub App Token
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
id: generate-token
|
|
||||||
uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6
|
- name: Setup GitHub App Bot
|
||||||
|
id: setup-bot
|
||||||
|
uses: ./.github/actions/setup-bot
|
||||||
with:
|
with:
|
||||||
app-id: ${{ secrets.GH_APP_ID }}
|
app-id: ${{ secrets.GH_APP_ID }}
|
||||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
- name: Get GitHub App User ID
|
|
||||||
id: get-user-id
|
|
||||||
run: |
|
|
||||||
USER_NAME="${{ steps.generate-token.outputs.app-slug }}[bot]"
|
|
||||||
USER_ID=$(gh api "/users/$USER_NAME" --jq .id)
|
|
||||||
USER_EMAIL="$USER_ID+$USER_NAME@users.noreply.github.com"
|
|
||||||
echo "user_name=$USER_NAME" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "user_email=$USER_EMAIL" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "user-id=$USER_ID" >> "$GITHUB_OUTPUT"
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ steps.generate-token.outputs.token }}
|
|
||||||
|
|
||||||
- id: committer
|
|
||||||
run: |
|
|
||||||
COMMITTER="${{ steps.get-user-id.outputs.user_name }} <${{ steps.get-user-id.outputs.user_email }}>"
|
|
||||||
echo "committer=$COMMITTER" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
sync-files:
|
|
||||||
needs: ["read_bot_entries"]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Harden Runner
|
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: Generate GitHub App Token
|
|
||||||
id: generate-token
|
|
||||||
uses: actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e # v2.0.6
|
|
||||||
with:
|
|
||||||
app-id: ${{ vars.GH_APP_ID }}
|
|
||||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
|
||||||
|
|
||||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: "3.12"
|
||||||
cache: 'pip' # caching pip dependencies
|
cache: "pip" # caching pip dependencies
|
||||||
|
|
||||||
- name: Sync translation property files
|
- name: Sync translation property files
|
||||||
run: |
|
run: |
|
||||||
python .github/scripts/check_language_properties.py --reference-file "src/main/resources/messages_en_GB.properties" --branch main
|
python .github/scripts/check_language_properties.py --reference-file "src/main/resources/messages_en_GB.properties" --branch main
|
||||||
|
|
||||||
- name: Set up git config
|
- name: Commit translation files
|
||||||
run: |
|
|
||||||
git config --global user.name ${{ needs.read_bot_entries.outputs.userName }}
|
|
||||||
git config --global user.email ${{ needs.read_bot_entries.outputs.userEmail }}
|
|
||||||
|
|
||||||
- name: Run git add
|
|
||||||
run: |
|
run: |
|
||||||
git add src/main/resources/messages_*.properties
|
git add src/main/resources/messages_*.properties
|
||||||
git diff --staged --quiet || git commit -m ":memo: Sync translation files" || echo "no changes"
|
git diff --staged --quiet || git commit -m ":memo: Sync translation files" || echo "No changes detected"
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pip install --require-hashes -r ./.github/scripts/requirements_sync_readme.txt
|
run: pip install --require-hashes -r ./.github/scripts/requirements_sync_readme.txt
|
||||||
@@ -100,15 +58,16 @@ jobs:
|
|||||||
- name: Run git add
|
- name: Run git add
|
||||||
run: |
|
run: |
|
||||||
git add README.md
|
git add README.md
|
||||||
git diff --staged --quiet || git commit -m ":memo: Sync README.md" || echo "no changes"
|
git diff --staged --quiet || git commit -m ":memo: Sync README.md" || echo "No changes detected"
|
||||||
|
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
|
if: always()
|
||||||
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
||||||
with:
|
with:
|
||||||
token: ${{ steps.generate-token.outputs.token }}
|
token: ${{ steps.setup-bot.outputs.token }}
|
||||||
commit-message: Update files
|
commit-message: Update files
|
||||||
committer: ${{ needs.read_bot_entries.outputs.committer }}
|
committer: ${{ steps.setup-bot.outputs.committer }}
|
||||||
author: ${{ needs.read_bot_entries.outputs.committer }}
|
author: ${{ steps.setup-bot.outputs.committer }}
|
||||||
signoff: true
|
signoff: true
|
||||||
branch: sync_readme
|
branch: sync_readme
|
||||||
title: ":globe_with_meridians: Sync Translations + Update README Progress Table"
|
title: ":globe_with_meridians: Sync Translations + Update README Progress Table"
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ jobs:
|
|||||||
password: ${{ secrets.DOCKER_HUB_API }}
|
password: ${{ secrets.DOCKER_HUB_API }}
|
||||||
|
|
||||||
- name: Build and push test image
|
- name: Build and push test image
|
||||||
uses: docker/build-push-action@1dc73863535b631f98b2378be8619f83b136f4a0 # v6.17.0
|
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.11.6
|
rev: v0.11.11
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
args:
|
args:
|
||||||
@@ -22,7 +22,7 @@ repos:
|
|||||||
files: \.(html|css|js|py|md)$
|
files: \.(html|css|js|py|md)$
|
||||||
exclude: (.vscode|.devcontainer|src/main/resources|Dockerfile|.*/pdfjs.*|.*/thirdParty.*|bootstrap.*|.*\.min\..*|.*diff\.js)
|
exclude: (.vscode|.devcontainer|src/main/resources|Dockerfile|.*/pdfjs.*|.*/thirdParty.*|bootstrap.*|.*\.min\..*|.*diff\.js)
|
||||||
- repo: https://github.com/gitleaks/gitleaks
|
- repo: https://github.com/gitleaks/gitleaks
|
||||||
rev: v8.24.3
|
rev: v8.26.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: gitleaks
|
- id: gitleaks
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
|||||||
Vendored
+4
-1
@@ -10,7 +10,7 @@
|
|||||||
"java.configuration.updateBuildConfiguration": "interactive",
|
"java.configuration.updateBuildConfiguration": "interactive",
|
||||||
"java.format.enabled": true,
|
"java.format.enabled": true,
|
||||||
"java.format.settings.profile": "GoogleStyle",
|
"java.format.settings.profile": "GoogleStyle",
|
||||||
"java.format.settings.google.version": "1.26.0",
|
"java.format.settings.google.version": "1.27.0",
|
||||||
"java.format.settings.google.extra": "--aosp --skip-sorting-imports --skip-javadoc-formatting",
|
"java.format.settings.google.extra": "--aosp --skip-sorting-imports --skip-javadoc-formatting",
|
||||||
// (DE) Aktiviert Kommentare im Java-Format.
|
// (DE) Aktiviert Kommentare im Java-Format.
|
||||||
// (EN) Enables comments in Java formatting.
|
// (EN) Enables comments in Java formatting.
|
||||||
@@ -49,7 +49,9 @@
|
|||||||
".venv*/",
|
".venv*/",
|
||||||
".vscode/",
|
".vscode/",
|
||||||
"bin/",
|
"bin/",
|
||||||
|
"common/bin/",
|
||||||
"build/",
|
"build/",
|
||||||
|
"common/build/",
|
||||||
"configs/",
|
"configs/",
|
||||||
"customFiles/",
|
"customFiles/",
|
||||||
"docs/",
|
"docs/",
|
||||||
@@ -63,6 +65,7 @@
|
|||||||
".git-blame-ignore-revs",
|
".git-blame-ignore-revs",
|
||||||
".gitattributes",
|
".gitattributes",
|
||||||
".gitignore",
|
".gitignore",
|
||||||
|
"common/.gitignore",
|
||||||
".pre-commit-config.yaml",
|
".pre-commit-config.yaml",
|
||||||
],
|
],
|
||||||
// Enables signature help in Java.
|
// Enables signature help in Java.
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
# Main stage
|
# Main stage
|
||||||
FROM alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
|
FROM alpine:3.22.0@sha256:8a1f59ffb675680d47db6337b49d22281a139e9d709335b492be023728e11715
|
||||||
|
|
||||||
# Copy necessary files
|
# Copy necessary files
|
||||||
COPY scripts /scripts
|
COPY scripts /scripts
|
||||||
@@ -73,7 +73,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
|||||||
py3-pillow@testing \
|
py3-pillow@testing \
|
||||||
py3-pdf2image@testing && \
|
py3-pdf2image@testing && \
|
||||||
python3 -m venv /opt/venv && \
|
python3 -m venv /opt/venv && \
|
||||||
/opt/venv/bin/pip install --upgrade pip && \
|
/opt/venv/bin/pip install --upgrade pip setuptools && \
|
||||||
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
||||||
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||||
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ ENV SETUPTOOLS_USE_DISTUTILS=local
|
|||||||
# Installation der benötigten Python-Pakete
|
# Installation der benötigten Python-Pakete
|
||||||
RUN python3 -m venv --system-site-packages /opt/venv \
|
RUN python3 -m venv --system-site-packages /opt/venv \
|
||||||
&& . /opt/venv/bin/activate \
|
&& . /opt/venv/bin/activate \
|
||||||
|
&& pip install --upgrade pip setuptools \
|
||||||
&& pip install --no-cache-dir WeasyPrint pdf2image pillow unoserver opencv-python-headless pre-commit
|
&& pip install --no-cache-dir WeasyPrint pdf2image pillow unoserver opencv-python-headless pre-commit
|
||||||
|
|
||||||
# Füge den venv-Pfad zur globalen PATH-Variable hinzu, damit die Tools verfügbar sind
|
# Füge den venv-Pfad zur globalen PATH-Variable hinzu, damit die Tools verfügbar sind
|
||||||
|
|||||||
+2
-2
@@ -19,7 +19,7 @@ RUN DOCKER_ENABLE_SECURITY=true \
|
|||||||
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||||
|
|
||||||
# Main stage
|
# Main stage
|
||||||
FROM alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
|
FROM alpine:3.22.0@sha256:8a1f59ffb675680d47db6337b49d22281a139e9d709335b492be023728e11715
|
||||||
|
|
||||||
# Copy necessary files
|
# Copy necessary files
|
||||||
COPY scripts /scripts
|
COPY scripts /scripts
|
||||||
@@ -83,7 +83,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
|||||||
py3-pillow@testing \
|
py3-pillow@testing \
|
||||||
py3-pdf2image@testing && \
|
py3-pdf2image@testing && \
|
||||||
python3 -m venv /opt/venv && \
|
python3 -m venv /opt/venv && \
|
||||||
/opt/venv/bin/pip install --upgrade pip && \
|
/opt/venv/bin/pip install --upgrade pip setuptools && \
|
||||||
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
||||||
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||||
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# use alpine
|
# use alpine
|
||||||
FROM alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
|
FROM alpine:3.22.0@sha256:8a1f59ffb675680d47db6337b49d22281a139e9d709335b492be023728e11715
|
||||||
|
|
||||||
ARG VERSION_TAG
|
ARG VERSION_TAG
|
||||||
|
|
||||||
|
|||||||
@@ -116,47 +116,47 @@ Stirling-PDF currently supports 40 languages!
|
|||||||
|
|
||||||
| Language | Progress |
|
| Language | Progress |
|
||||||
| -------------------------------------------- | -------------------------------------- |
|
| -------------------------------------------- | -------------------------------------- |
|
||||||
| Arabic (العربية) (ar_AR) |  |
|
| Arabic (العربية) (ar_AR) |  |
|
||||||
| Azerbaijani (Azərbaycan Dili) (az_AZ) |  |
|
| Azerbaijani (Azərbaycan Dili) (az_AZ) |  |
|
||||||
| Basque (Euskara) (eu_ES) |  |
|
| Basque (Euskara) (eu_ES) |  |
|
||||||
| Bulgarian (Български) (bg_BG) |  |
|
| Bulgarian (Български) (bg_BG) |  |
|
||||||
| Catalan (Català) (ca_CA) |  |
|
| Catalan (Català) (ca_CA) |  |
|
||||||
| Croatian (Hrvatski) (hr_HR) |  |
|
| Croatian (Hrvatski) (hr_HR) |  |
|
||||||
| Czech (Česky) (cs_CZ) |  |
|
| Czech (Česky) (cs_CZ) |  |
|
||||||
| Danish (Dansk) (da_DK) |  |
|
| Danish (Dansk) (da_DK) |  |
|
||||||
| Dutch (Nederlands) (nl_NL) |  |
|
| Dutch (Nederlands) (nl_NL) |  |
|
||||||
| English (English) (en_GB) |  |
|
| English (English) (en_GB) |  |
|
||||||
| English (US) (en_US) |  |
|
| English (US) (en_US) |  |
|
||||||
| French (Français) (fr_FR) |  |
|
| French (Français) (fr_FR) |  |
|
||||||
| German (Deutsch) (de_DE) |  |
|
| German (Deutsch) (de_DE) |  |
|
||||||
| Greek (Ελληνικά) (el_GR) |  |
|
| Greek (Ελληνικά) (el_GR) |  |
|
||||||
| Hindi (हिंदी) (hi_IN) |  |
|
| Hindi (हिंदी) (hi_IN) |  |
|
||||||
| Hungarian (Magyar) (hu_HU) |  |
|
| Hungarian (Magyar) (hu_HU) |  |
|
||||||
| Indonesian (Bahasa Indonesia) (id_ID) |  |
|
| Indonesian (Bahasa Indonesia) (id_ID) |  |
|
||||||
| Irish (Gaeilge) (ga_IE) |  |
|
| Irish (Gaeilge) (ga_IE) |  |
|
||||||
| Italian (Italiano) (it_IT) |  |
|
| Italian (Italiano) (it_IT) |  |
|
||||||
| Japanese (日本語) (ja_JP) |  |
|
| Japanese (日本語) (ja_JP) |  |
|
||||||
| Korean (한국어) (ko_KR) |  |
|
| Korean (한국어) (ko_KR) |  |
|
||||||
| Norwegian (Norsk) (no_NB) |  |
|
| Norwegian (Norsk) (no_NB) |  |
|
||||||
| Persian (فارسی) (fa_IR) |  |
|
| Persian (فارسی) (fa_IR) |  |
|
||||||
| Polish (Polski) (pl_PL) |  |
|
| Polish (Polski) (pl_PL) |  |
|
||||||
| Portuguese (Português) (pt_PT) |  |
|
| Portuguese (Português) (pt_PT) |  |
|
||||||
| Portuguese Brazilian (Português) (pt_BR) |  |
|
| Portuguese Brazilian (Português) (pt_BR) |  |
|
||||||
| Romanian (Română) (ro_RO) |  |
|
| Romanian (Română) (ro_RO) |  |
|
||||||
| Russian (Русский) (ru_RU) |  |
|
| Russian (Русский) (ru_RU) |  |
|
||||||
| Serbian Latin alphabet (Srpski) (sr_LATN_RS) |  |
|
| Serbian Latin alphabet (Srpski) (sr_LATN_RS) |  |
|
||||||
| Simplified Chinese (简体中文) (zh_CN) |  |
|
| Simplified Chinese (简体中文) (zh_CN) |  |
|
||||||
| Slovakian (Slovensky) (sk_SK) |  |
|
| Slovakian (Slovensky) (sk_SK) |  |
|
||||||
| Slovenian (Slovenščina) (sl_SI) |  |
|
| Slovenian (Slovenščina) (sl_SI) |  |
|
||||||
| Spanish (Español) (es_ES) |  |
|
| Spanish (Español) (es_ES) |  |
|
||||||
| Swedish (Svenska) (sv_SE) |  |
|
| Swedish (Svenska) (sv_SE) |  |
|
||||||
| Thai (ไทย) (th_TH) |  |
|
| Thai (ไทย) (th_TH) |  |
|
||||||
| Tibetan (བོད་ཡིག་) (zh_BO) |  |
|
| Tibetan (བོད་ཡིག་) (bo_CN) |  |
|
||||||
| Traditional Chinese (繁體中文) (zh_TW) |  |
|
| Traditional Chinese (繁體中文) (zh_TW) |  |
|
||||||
| Turkish (Türkçe) (tr_TR) |  |
|
| Turkish (Türkçe) (tr_TR) |  |
|
||||||
| Ukrainian (Українська) (uk_UA) |  |
|
| Ukrainian (Українська) (uk_UA) |  |
|
||||||
| Vietnamese (Tiếng Việt) (vi_VN) |  |
|
| Vietnamese (Tiếng Việt) (vi_VN) |  |
|
||||||
| Malayalam (മലയാളം) (ml_ML) |  |
|
| Malayalam (മലയാളം) (ml_IN) |  |
|
||||||
|
|
||||||
## Stirling PDF Enterprise
|
## Stirling PDF Enterprise
|
||||||
|
|
||||||
|
|||||||
+15
-16
@@ -1,12 +1,12 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id "java"
|
id "java"
|
||||||
id 'jacoco'
|
id "jacoco"
|
||||||
id "org.springframework.boot" version "3.4.5"
|
id "org.springframework.boot" version "3.5.0"
|
||||||
id "io.spring.dependency-management" version "1.1.7"
|
id "io.spring.dependency-management" version "1.1.7"
|
||||||
id "org.springdoc.openapi-gradle-plugin" version "1.9.0"
|
id "org.springdoc.openapi-gradle-plugin" version "1.9.0"
|
||||||
id "io.swagger.swaggerhub" version "1.3.2"
|
id "io.swagger.swaggerhub" version "1.3.2"
|
||||||
id "edu.sc.seis.launch4j" version "3.0.6"
|
id "edu.sc.seis.launch4j" version "3.0.6"
|
||||||
id "com.diffplug.spotless" version "7.0.3"
|
id "com.diffplug.spotless" version "7.0.4"
|
||||||
id "com.github.jk1.dependency-license-report" version "2.9"
|
id "com.github.jk1.dependency-license-report" version "2.9"
|
||||||
//id "nebula.lint" version "19.0.3"
|
//id "nebula.lint" version "19.0.3"
|
||||||
id("org.panteleyev.jpackageplugin") version "1.6.1"
|
id("org.panteleyev.jpackageplugin") version "1.6.1"
|
||||||
@@ -19,7 +19,7 @@ import java.nio.file.Files
|
|||||||
import java.time.Year
|
import java.time.Year
|
||||||
|
|
||||||
ext {
|
ext {
|
||||||
springBootVersion = "3.4.5"
|
springBootVersion = "3.5.0"
|
||||||
pdfboxVersion = "3.0.5"
|
pdfboxVersion = "3.0.5"
|
||||||
imageioVersion = "3.12.0"
|
imageioVersion = "3.12.0"
|
||||||
lombokVersion = "1.18.38"
|
lombokVersion = "1.18.38"
|
||||||
@@ -374,9 +374,10 @@ launch4j {
|
|||||||
|
|
||||||
spotless {
|
spotless {
|
||||||
java {
|
java {
|
||||||
target project.fileTree('src').include('**/*.java')
|
target sourceSets.main.allJava
|
||||||
|
target project(':common').sourceSets.main.allJava
|
||||||
|
|
||||||
googleJavaFormat("1.26.0").aosp().reorderImports(false)
|
googleJavaFormat("1.27.0").aosp().reorderImports(false)
|
||||||
|
|
||||||
importOrder("java", "javax", "org", "com", "net", "io", "jakarta", "lombok", "me", "stirling")
|
importOrder("java", "javax", "org", "com", "net", "io", "jakarta", "lombok", "me", "stirling")
|
||||||
toggleOffOn()
|
toggleOffOn()
|
||||||
@@ -413,13 +414,14 @@ configurations.all {
|
|||||||
// Exclude Tomcat
|
// Exclude Tomcat
|
||||||
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
|
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
implementation project(':common')
|
||||||
|
|
||||||
//tmp for security bumps
|
//tmp for security bumps
|
||||||
implementation 'ch.qos.logback:logback-core:1.5.18'
|
implementation 'ch.qos.logback:logback-core:1.5.18'
|
||||||
implementation 'ch.qos.logback:logback-classic:1.5.18'
|
implementation 'ch.qos.logback:logback-classic:1.5.18'
|
||||||
|
|
||||||
|
|
||||||
// Exclude vulnerable BouncyCastle version used in tableau
|
// Exclude vulnerable BouncyCastle version used in tableau
|
||||||
configurations.all {
|
configurations.all {
|
||||||
exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on'
|
exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on'
|
||||||
@@ -428,7 +430,7 @@ dependencies {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (System.getenv("STIRLING_PDF_DESKTOP_UI") != "false") {
|
if (System.getenv("STIRLING_PDF_DESKTOP_UI") != "false") {
|
||||||
implementation "me.friwi:jcefmaven:132.3.1"
|
implementation "me.friwi:jcefmaven:135.0.20"
|
||||||
implementation "org.openjfx:javafx-controls:21"
|
implementation "org.openjfx:javafx-controls:21"
|
||||||
implementation "org.openjfx:javafx-swing:21"
|
implementation "org.openjfx:javafx-swing:21"
|
||||||
}
|
}
|
||||||
@@ -448,8 +450,6 @@ dependencies {
|
|||||||
|
|
||||||
|
|
||||||
if (System.getenv("DOCKER_ENABLE_SECURITY") != "false") {
|
if (System.getenv("DOCKER_ENABLE_SECURITY") != "false") {
|
||||||
|
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
|
||||||
implementation 'io.micrometer:micrometer-registry-prometheus'
|
implementation 'io.micrometer:micrometer-registry-prometheus'
|
||||||
|
|
||||||
implementation "org.springframework.boot:spring-boot-starter-security:$springBootVersion"
|
implementation "org.springframework.boot:spring-boot-starter-security:$springBootVersion"
|
||||||
@@ -458,13 +458,13 @@ dependencies {
|
|||||||
implementation "org.springframework.boot:spring-boot-starter-oauth2-client:$springBootVersion"
|
implementation "org.springframework.boot:spring-boot-starter-oauth2-client:$springBootVersion"
|
||||||
implementation "org.springframework.boot:spring-boot-starter-mail:$springBootVersion"
|
implementation "org.springframework.boot:spring-boot-starter-mail:$springBootVersion"
|
||||||
|
|
||||||
implementation "org.springframework.session:spring-session-core:3.4.3"
|
implementation "org.springframework.session:spring-session-core:3.5.0"
|
||||||
implementation "org.springframework:spring-jdbc:6.2.7"
|
implementation "org.springframework:spring-jdbc:6.2.7"
|
||||||
|
|
||||||
implementation 'com.unboundid.product.scim2:scim2-sdk-client:2.3.5'
|
implementation 'com.unboundid.product.scim2:scim2-sdk-client:2.3.5'
|
||||||
// Don't upgrade h2database
|
// Don't upgrade h2database
|
||||||
runtimeOnly "com.h2database:h2:2.3.232"
|
runtimeOnly "com.h2database:h2:2.3.232"
|
||||||
runtimeOnly "org.postgresql:postgresql:42.7.5"
|
runtimeOnly "org.postgresql:postgresql:42.7.6"
|
||||||
constraints {
|
constraints {
|
||||||
implementation "org.opensaml:opensaml-core:$openSamlVersion"
|
implementation "org.opensaml:opensaml-core:$openSamlVersion"
|
||||||
implementation "org.opensaml:opensaml-saml-api:$openSamlVersion"
|
implementation "org.opensaml:opensaml-saml-api:$openSamlVersion"
|
||||||
@@ -521,6 +521,7 @@ dependencies {
|
|||||||
exclude group: "org.slf4j", module: "slf4j-simple"
|
exclude group: "org.slf4j", module: "slf4j-simple"
|
||||||
exclude group: "org.bouncycastle", module: "bcprov-jdk15on"
|
exclude group: "org.bouncycastle", module: "bcprov-jdk15on"
|
||||||
exclude group: "com.google.code.gson", module: "gson"
|
exclude group: "com.google.code.gson", module: "gson"
|
||||||
|
exclude group: "commons-io", module: "commons-io"
|
||||||
}
|
}
|
||||||
|
|
||||||
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4'
|
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4'
|
||||||
@@ -543,10 +544,8 @@ dependencies {
|
|||||||
compileOnly "org.projectlombok:lombok:$lombokVersion"
|
compileOnly "org.projectlombok:lombok:$lombokVersion"
|
||||||
annotationProcessor "org.projectlombok:lombok:$lombokVersion"
|
annotationProcessor "org.projectlombok:lombok:$lombokVersion"
|
||||||
|
|
||||||
// Mockito (core)
|
// Mockito (core)
|
||||||
testImplementation 'org.mockito:mockito-core:5.17.0'
|
testImplementation 'org.mockito:mockito-core:5.18.0'
|
||||||
|
|
||||||
|
|
||||||
testRuntimeOnly 'org.mockito:mockito-inline:5.2.0'
|
testRuntimeOnly 'org.mockito:mockito-inline:5.2.0'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
### Eclipse ###
|
||||||
|
.metadata
|
||||||
|
bin/
|
||||||
|
tmp/
|
||||||
|
*.tmp
|
||||||
|
*.bak
|
||||||
|
*.exe
|
||||||
|
*.swp
|
||||||
|
*~.nib
|
||||||
|
local.properties
|
||||||
|
.settings/
|
||||||
|
.loadpath
|
||||||
|
.recommenders
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
version.properties
|
||||||
|
|
||||||
|
#### Stirling-PDF Files ###
|
||||||
|
pipeline/watchedFolders/
|
||||||
|
pipeline/finishedFolders/
|
||||||
|
customFiles/
|
||||||
|
configs/
|
||||||
|
watchedFolders/
|
||||||
|
clientWebUI/
|
||||||
|
!cucumber/
|
||||||
|
!cucumber/exampleFiles/
|
||||||
|
!cucumber/exampleFiles/example_html.zip
|
||||||
|
exampleYmlFiles/stirling/
|
||||||
|
/testing/file_snapshots
|
||||||
|
SwaggerDoc.json
|
||||||
|
|
||||||
|
# Gradle
|
||||||
|
.gradle
|
||||||
|
.lock
|
||||||
|
|
||||||
|
# External tool builders
|
||||||
|
.externalToolBuilders/
|
||||||
|
|
||||||
|
# Locally stored "Eclipse launch configurations"
|
||||||
|
*.launch
|
||||||
|
|
||||||
|
# PyDev specific (Python IDE for Eclipse)
|
||||||
|
*.pydevproject
|
||||||
|
|
||||||
|
# CDT-specific (C/C++ Development Tooling)
|
||||||
|
.cproject
|
||||||
|
|
||||||
|
# CDT- autotools
|
||||||
|
.autotools
|
||||||
|
|
||||||
|
# Java annotation processor (APT)
|
||||||
|
.factorypath
|
||||||
|
|
||||||
|
# PDT-specific (PHP Development Tools)
|
||||||
|
.buildpath
|
||||||
|
|
||||||
|
# sbteclipse plugin
|
||||||
|
.target
|
||||||
|
|
||||||
|
# Tern plugin
|
||||||
|
.tern-project
|
||||||
|
|
||||||
|
# TeXlipse plugin
|
||||||
|
.texlipse
|
||||||
|
|
||||||
|
# STS (Spring Tool Suite)
|
||||||
|
.springBeans
|
||||||
|
|
||||||
|
# Code Recommenders
|
||||||
|
.recommenders/
|
||||||
|
|
||||||
|
# Annotation Processing
|
||||||
|
.apt_generated/
|
||||||
|
.apt_generated_test/
|
||||||
|
|
||||||
|
# Scala IDE specific (Scala & Java development for Eclipse)
|
||||||
|
.cache-main
|
||||||
|
.scala_dependencies
|
||||||
|
.worksheet
|
||||||
|
|
||||||
|
# Uncomment this line if you wish to ignore the project description file.
|
||||||
|
# Typically, this file would be tracked if it contains build/dependency configurations:
|
||||||
|
#.project
|
||||||
|
|
||||||
|
### Eclipse Patch ###
|
||||||
|
# Spring Boot Tooling
|
||||||
|
.sts4-cache/
|
||||||
|
|
||||||
|
### Git ###
|
||||||
|
# Created by git for backups. To disable backups in Git:
|
||||||
|
# $ git config --global mergetool.keepBackup false
|
||||||
|
*.orig
|
||||||
|
|
||||||
|
# Created by git when using merge tools for conflicts
|
||||||
|
*.BACKUP.*
|
||||||
|
*.BASE.*
|
||||||
|
*.LOCAL.*
|
||||||
|
*.REMOTE.*
|
||||||
|
*_BACKUP_*.txt
|
||||||
|
*_BASE_*.txt
|
||||||
|
*_LOCAL_*.txt
|
||||||
|
*_REMOTE_*.txt
|
||||||
|
|
||||||
|
### Java ###
|
||||||
|
# Compiled class file
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# Log file
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# BlueJ files
|
||||||
|
*.ctxt
|
||||||
|
|
||||||
|
# Mobile Tools for Java (J2ME)
|
||||||
|
.mtj.tmp/
|
||||||
|
|
||||||
|
# Package Files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.nar
|
||||||
|
*.ear
|
||||||
|
*.zip
|
||||||
|
*.tar.gz
|
||||||
|
*.rar
|
||||||
|
*.db
|
||||||
|
/build
|
||||||
|
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.pyo
|
||||||
|
|
||||||
|
# Virtual environments
|
||||||
|
.env*
|
||||||
|
.venv*
|
||||||
|
env*/
|
||||||
|
venv*/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# VS Code
|
||||||
|
/.vscode/**/*
|
||||||
|
!/.vscode/settings.json
|
||||||
|
!/.vscode/extensions.json
|
||||||
|
|
||||||
|
# IntelliJ IDEA
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
out/
|
||||||
|
|
||||||
|
# Ignore Mac DS_Store files
|
||||||
|
.DS_Store
|
||||||
|
**/.DS_Store
|
||||||
|
|
||||||
|
# cucumber
|
||||||
|
/cucumber/reports/**
|
||||||
|
|
||||||
|
# Certs and Security Files
|
||||||
|
*.p12
|
||||||
|
*.pk8
|
||||||
|
*.pem
|
||||||
|
*.crt
|
||||||
|
*.cer
|
||||||
|
*.cert
|
||||||
|
*.der
|
||||||
|
*.key
|
||||||
|
*.csr
|
||||||
|
*.kdbx
|
||||||
|
*.jks
|
||||||
|
*.asc
|
||||||
|
|
||||||
|
# SSH Keys
|
||||||
|
*.pub
|
||||||
|
*.priv
|
||||||
|
id_rsa
|
||||||
|
id_rsa.pub
|
||||||
|
id_ecdsa
|
||||||
|
id_ecdsa.pub
|
||||||
|
id_ed25519
|
||||||
|
id_ed25519.pub
|
||||||
|
.ssh/
|
||||||
|
*ssh
|
||||||
|
|
||||||
|
# cache
|
||||||
|
.cache
|
||||||
|
.ruff_cache
|
||||||
|
.mypy_cache
|
||||||
|
.pytest_cache
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
**/jcef-bundle/
|
||||||
|
|
||||||
|
# node_modules
|
||||||
|
node_modules/
|
||||||
|
*.mjs
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java-library'
|
||||||
|
id 'io.spring.dependency-management' version '1.1.7'
|
||||||
|
}
|
||||||
|
|
||||||
|
group = 'stirling.software'
|
||||||
|
version = '0.46.2'
|
||||||
|
|
||||||
|
ext {
|
||||||
|
lombokVersion = "1.18.38"
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
configurations.all {
|
||||||
|
exclude group: 'commons-logging', module: 'commons-logging'
|
||||||
|
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyManagement {
|
||||||
|
imports {
|
||||||
|
mavenBom 'org.springframework.boot:spring-boot-dependencies:3.5.0'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-aop'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-websocket'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-test'
|
||||||
|
implementation 'com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer:20240325.1'
|
||||||
|
implementation 'com.fathzer:javaluator:3.0.6'
|
||||||
|
implementation 'com.posthog.java:posthog:1.2.0'
|
||||||
|
implementation 'io.github.pixee:java-security-toolkit:1.2.1'
|
||||||
|
implementation 'org.apache.commons:commons-lang3:3.17.0'
|
||||||
|
implementation 'com.drewnoakes:metadata-extractor:2.19.0' // Image metadata extractor
|
||||||
|
implementation 'com.vladsch.flexmark:flexmark-html2md-converter:0.64.8'
|
||||||
|
implementation "org.apache.pdfbox:pdfbox:$pdfboxVersion"
|
||||||
|
implementation 'jakarta.servlet:jakarta.servlet-api:6.1.0'
|
||||||
|
implementation 'org.snakeyaml:snakeyaml-engine:2.9'
|
||||||
|
implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8"
|
||||||
|
|
||||||
|
compileOnly "org.projectlombok:lombok:$lombokVersion"
|
||||||
|
annotationProcessor "org.projectlombok:lombok:$lombokVersion"
|
||||||
|
|
||||||
|
testImplementation "org.springframework.boot:spring-boot-starter-test"
|
||||||
|
testImplementation 'org.mockito:mockito-core:5.18.0'
|
||||||
|
testImplementation 'org.mockito:mockito-junit-jupiter:5.18.0'
|
||||||
|
testRuntimeOnly 'org.mockito:mockito-inline:5.2.0'
|
||||||
|
}
|
||||||
|
|
||||||
|
test {
|
||||||
|
useJUnitPlatform()
|
||||||
|
testLogging {
|
||||||
|
events "passed", "skipped", "failed"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package stirling.software.common.annotations;
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
import org.springframework.core.annotation.AliasFor;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Documented
|
||||||
|
@RequestMapping(method = RequestMethod.POST)
|
||||||
|
public @interface AutoJobPostMapping {
|
||||||
|
@AliasFor(annotation = RequestMapping.class, attribute = "value")
|
||||||
|
String[] value() default {};
|
||||||
|
|
||||||
|
@AliasFor(annotation = RequestMapping.class, attribute = "consumes")
|
||||||
|
String[] consumes() default {"multipart/form-data"};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom timeout in milliseconds for this specific job. If not specified, the default system
|
||||||
|
* timeout will be used.
|
||||||
|
*/
|
||||||
|
long timeout() default -1;
|
||||||
|
|
||||||
|
/** Maximum number of times to retry the job on failure. Default is 1 (no retries). */
|
||||||
|
int retryCount() default 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether to track and report progress for this job. If enabled, the job will send progress
|
||||||
|
* updates through WebSocket.
|
||||||
|
*/
|
||||||
|
boolean trackProgress() default true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this job can be queued when system resources are limited. If enabled, jobs will be
|
||||||
|
* queued instead of rejected when the system is under high load. The queue size is dynamically
|
||||||
|
* adjusted based on available memory and CPU resources.
|
||||||
|
*/
|
||||||
|
boolean queueable() default false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional resource weight of this job (1-100). Higher values indicate more resource-intensive
|
||||||
|
* jobs that may need stricter queuing. Default is 50 (medium weight).
|
||||||
|
*/
|
||||||
|
int resourceWeight() default 50;
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
package stirling.software.common.aop;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import org.aspectj.lang.ProceedingJoinPoint;
|
||||||
|
import org.aspectj.lang.annotation.*;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
|
import stirling.software.common.controller.WebSocketProgressController;
|
||||||
|
import stirling.software.common.model.api.PDFFile;
|
||||||
|
import stirling.software.common.model.job.JobProgress;
|
||||||
|
import stirling.software.common.service.FileOrUploadService;
|
||||||
|
import stirling.software.common.service.FileStorage;
|
||||||
|
import stirling.software.common.service.JobExecutorService;
|
||||||
|
|
||||||
|
@Aspect
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class AutoJobAspect {
|
||||||
|
|
||||||
|
private final JobExecutorService jobExecutorService;
|
||||||
|
private final HttpServletRequest request;
|
||||||
|
private final FileOrUploadService fileOrUploadService;
|
||||||
|
private final FileStorage fileStorage;
|
||||||
|
private final WebSocketProgressController webSocketSender;
|
||||||
|
|
||||||
|
@Around("@annotation(autoJobPostMapping)")
|
||||||
|
public Object wrapWithJobExecution(
|
||||||
|
ProceedingJoinPoint joinPoint, AutoJobPostMapping autoJobPostMapping) {
|
||||||
|
// Extract parameters from the request and annotation
|
||||||
|
boolean async = Boolean.parseBoolean(request.getParameter("async"));
|
||||||
|
long timeout = autoJobPostMapping.timeout();
|
||||||
|
int retryCount = autoJobPostMapping.retryCount();
|
||||||
|
boolean trackProgress = autoJobPostMapping.trackProgress();
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"AutoJobPostMapping execution with async={}, timeout={}, retryCount={}, trackProgress={}",
|
||||||
|
async,
|
||||||
|
timeout > 0 ? timeout : "default",
|
||||||
|
retryCount,
|
||||||
|
trackProgress);
|
||||||
|
|
||||||
|
// Inspect and possibly mutate arguments
|
||||||
|
Object[] args = joinPoint.getArgs();
|
||||||
|
|
||||||
|
for (int i = 0; i < args.length; i++) {
|
||||||
|
Object arg = args[i];
|
||||||
|
|
||||||
|
if (arg instanceof PDFFile pdfFile) {
|
||||||
|
// Case 1: fileId is provided but no fileInput
|
||||||
|
if (pdfFile.getFileInput() == null && pdfFile.getFileId() != null) {
|
||||||
|
try {
|
||||||
|
log.debug("Using fileId {} to get file content", pdfFile.getFileId());
|
||||||
|
MultipartFile file = fileStorage.retrieveFile(pdfFile.getFileId());
|
||||||
|
pdfFile.setFileInput(file);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
"Failed to resolve file by ID: " + pdfFile.getFileId(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Case 2: For async requests, we need to make a copy of the MultipartFile
|
||||||
|
else if (async && pdfFile.getFileInput() != null) {
|
||||||
|
try {
|
||||||
|
log.debug("Making persistent copy of uploaded file for async processing");
|
||||||
|
MultipartFile originalFile = pdfFile.getFileInput();
|
||||||
|
String fileId = fileStorage.storeFile(originalFile);
|
||||||
|
|
||||||
|
// Store the fileId for later reference
|
||||||
|
pdfFile.setFileId(fileId);
|
||||||
|
|
||||||
|
// Replace the original MultipartFile with our persistent copy
|
||||||
|
MultipartFile persistentFile = fileStorage.retrieveFile(fileId);
|
||||||
|
pdfFile.setFileInput(persistentFile);
|
||||||
|
|
||||||
|
log.debug("Created persistent file copy with fileId: {}", fileId);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
"Failed to create persistent copy of uploaded file", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract queueable and resourceWeight parameters
|
||||||
|
boolean queueable = autoJobPostMapping.queueable();
|
||||||
|
int resourceWeight = autoJobPostMapping.resourceWeight();
|
||||||
|
|
||||||
|
// Integrate with the enhanced JobExecutorService
|
||||||
|
if (retryCount <= 1) {
|
||||||
|
// No retries needed, simple execution
|
||||||
|
return jobExecutorService.runJobGeneric(
|
||||||
|
async,
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
if (trackProgress && async) {
|
||||||
|
String jobId = (String) request.getAttribute("jobId");
|
||||||
|
if (jobId != null) {
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId,
|
||||||
|
new JobProgress(
|
||||||
|
jobId,
|
||||||
|
"Processing",
|
||||||
|
50,
|
||||||
|
"Executing operation"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return joinPoint.proceed(args);
|
||||||
|
} catch (Throwable ex) {
|
||||||
|
log.error(
|
||||||
|
"AutoJobAspect caught exception during job execution: {}",
|
||||||
|
ex.getMessage(),
|
||||||
|
ex);
|
||||||
|
throw new RuntimeException(ex);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
timeout,
|
||||||
|
queueable,
|
||||||
|
resourceWeight);
|
||||||
|
} else {
|
||||||
|
// Use retry logic
|
||||||
|
return executeWithRetries(
|
||||||
|
joinPoint,
|
||||||
|
args,
|
||||||
|
async,
|
||||||
|
timeout,
|
||||||
|
retryCount,
|
||||||
|
trackProgress,
|
||||||
|
queueable,
|
||||||
|
resourceWeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object executeWithRetries(
|
||||||
|
ProceedingJoinPoint joinPoint,
|
||||||
|
Object[] args,
|
||||||
|
boolean async,
|
||||||
|
long timeout,
|
||||||
|
int maxRetries,
|
||||||
|
boolean trackProgress,
|
||||||
|
boolean queueable,
|
||||||
|
int resourceWeight) {
|
||||||
|
|
||||||
|
AtomicInteger attempts = new AtomicInteger(0);
|
||||||
|
// Use AtomicReference to make the jobId effectively final for lambda usage
|
||||||
|
AtomicReference<String> jobIdRef = new AtomicReference<>();
|
||||||
|
|
||||||
|
return jobExecutorService.runJobGeneric(
|
||||||
|
async,
|
||||||
|
() -> {
|
||||||
|
int currentAttempt = attempts.incrementAndGet();
|
||||||
|
try {
|
||||||
|
if (trackProgress && async) {
|
||||||
|
// Only get the jobId once and store it in the AtomicReference
|
||||||
|
if (jobIdRef.get() == null) {
|
||||||
|
jobIdRef.set(getJobIdFromContext());
|
||||||
|
}
|
||||||
|
String jobId = jobIdRef.get();
|
||||||
|
if (jobId != null) {
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId,
|
||||||
|
new JobProgress(
|
||||||
|
jobId,
|
||||||
|
"Started",
|
||||||
|
0,
|
||||||
|
"Executing (attempt "
|
||||||
|
+ currentAttempt
|
||||||
|
+ " of "
|
||||||
|
+ Math.max(1, maxRetries)
|
||||||
|
+ ")"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return joinPoint.proceed(args);
|
||||||
|
} catch (Throwable ex) {
|
||||||
|
log.error(
|
||||||
|
"AutoJobAspect caught exception during job execution (attempt {}/{}): {}",
|
||||||
|
currentAttempt,
|
||||||
|
Math.max(1, maxRetries),
|
||||||
|
ex.getMessage(),
|
||||||
|
ex);
|
||||||
|
|
||||||
|
// Check if we should retry
|
||||||
|
if (currentAttempt < maxRetries) {
|
||||||
|
log.info(
|
||||||
|
"Retrying operation, attempt {}/{}",
|
||||||
|
currentAttempt + 1,
|
||||||
|
maxRetries);
|
||||||
|
String jobId = jobIdRef.get();
|
||||||
|
if (trackProgress && async && jobId != null) {
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId,
|
||||||
|
new JobProgress(
|
||||||
|
jobId,
|
||||||
|
"Retrying",
|
||||||
|
(int) (currentAttempt * 100.0 / maxRetries),
|
||||||
|
"Retry attempt "
|
||||||
|
+ (currentAttempt + 1)
|
||||||
|
+ " of "
|
||||||
|
+ maxRetries));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Simple exponential backoff
|
||||||
|
Thread.sleep(100 * currentAttempt);
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursive call to retry
|
||||||
|
return executeWithRetries(
|
||||||
|
joinPoint,
|
||||||
|
args,
|
||||||
|
async,
|
||||||
|
timeout,
|
||||||
|
maxRetries,
|
||||||
|
trackProgress,
|
||||||
|
queueable,
|
||||||
|
resourceWeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
// No more retries, throw the exception
|
||||||
|
throw new RuntimeException("Job failed: " + ex.getMessage(), ex);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
timeout,
|
||||||
|
queueable,
|
||||||
|
resourceWeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to get the job ID from the context (if this is an async job)
|
||||||
|
private String getJobIdFromContext() {
|
||||||
|
try {
|
||||||
|
return (String) request.getAttribute("jobId");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Could not retrieve job ID from context: {}", e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package stirling.software.common.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||||
|
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||||
|
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||||
|
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSocketMessageBroker
|
||||||
|
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||||
|
config.enableSimpleBroker("/topic");
|
||||||
|
config.setApplicationDestinationPrefixes("/app");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||||
|
registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS();
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
-4
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@@ -22,20 +22,33 @@ import org.springframework.core.io.Resource;
|
|||||||
import org.springframework.core.io.ResourceLoader;
|
import org.springframework.core.io.ResourceLoader;
|
||||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.ApplicationProperties;
|
import stirling.software.common.model.ApplicationProperties;
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@Lazy
|
@Lazy
|
||||||
@Slf4j
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class AppConfig {
|
public class AppConfig {
|
||||||
|
|
||||||
|
private final Environment env;
|
||||||
|
|
||||||
private final ApplicationProperties applicationProperties;
|
private final ApplicationProperties applicationProperties;
|
||||||
|
|
||||||
private final Environment env;
|
@Getter
|
||||||
|
@Value("${baseUrl:http://localhost}")
|
||||||
|
private String baseUrl;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Value("${server.servlet.context-path:/}")
|
||||||
|
private String contextPath;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Value("${server.port:8080}")
|
||||||
|
private String serverPort;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnProperty(name = "system.customHTMLFiles", havingValue = "true")
|
@ConditionalOnProperty(name = "system.customHTMLFiles", havingValue = "true")
|
||||||
@@ -198,6 +211,31 @@ public class AppConfig {
|
|||||||
return applicationProperties.getAutomaticallyGenerated().getUUID();
|
return applicationProperties.getAutomaticallyGenerated().getUUID();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ApplicationProperties.Security security() {
|
||||||
|
return applicationProperties.getSecurity();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ApplicationProperties.Security.OAUTH2 oAuth2() {
|
||||||
|
return applicationProperties.getSecurity().getOauth2();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ApplicationProperties.Premium premium() {
|
||||||
|
return applicationProperties.getPremium();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ApplicationProperties.System system() {
|
||||||
|
return applicationProperties.getSystem();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ApplicationProperties.Datasource datasource() {
|
||||||
|
return applicationProperties.getSystem().getDatasource();
|
||||||
|
}
|
||||||
|
|
||||||
@Bean(name = "disablePixel")
|
@Bean(name = "disablePixel")
|
||||||
public boolean disablePixel() {
|
public boolean disablePixel() {
|
||||||
return Boolean.getBoolean(env.getProperty("DISABLE_PIXEL"));
|
return Boolean.getBoolean(env.getProperty("DISABLE_PIXEL"));
|
||||||
+4
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import java.io.FileNotFoundException;
|
import java.io.FileNotFoundException;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -13,6 +13,8 @@ import java.util.List;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.util.YamlHelper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A naive, line-based approach to merging "settings.yml" with "settings.yml.template" while
|
* A naive, line-based approach to merging "settings.yml" with "settings.yml.template" while
|
||||||
* preserving exact whitespace, blank lines, and inline comments -- but we only rewrite the file if
|
* preserving exact whitespace, blank lines, and inline comments -- but we only rewrite the file if
|
||||||
@@ -76,7 +78,7 @@ public class ConfigInitializer {
|
|||||||
Path customSettingsPath = Paths.get(InstallationPathConfig.getCustomSettingsPath());
|
Path customSettingsPath = Paths.get(InstallationPathConfig.getCustomSettingsPath());
|
||||||
if (Files.notExists(customSettingsPath)) {
|
if (Files.notExists(customSettingsPath)) {
|
||||||
Files.createFile(customSettingsPath);
|
Files.createFile(customSettingsPath);
|
||||||
log.info("Created custom_settings file: {}", customSettingsPath.toString());
|
log.info("Created custom_settings file: {}", customSettingsPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -13,7 +13,7 @@ import org.thymeleaf.templateresource.ITemplateResource;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.InputStreamTemplateResource;
|
import stirling.software.common.model.InputStreamTemplateResource;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class FileFallbackTemplateResolver extends AbstractConfigurableTemplateResolver {
|
public class FileFallbackTemplateResolver extends AbstractConfigurableTemplateResolver {
|
||||||
+10
-13
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
@@ -48,24 +48,21 @@ public class InstallationPathConfig {
|
|||||||
String os = System.getProperty("os.name").toLowerCase();
|
String os = System.getProperty("os.name").toLowerCase();
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
return Paths.get(
|
return Paths.get(
|
||||||
System.getenv("APPDATA"), // parent path
|
System.getenv("APPDATA"), // parent path
|
||||||
"Stirling-PDF")
|
"Stirling-PDF")
|
||||||
.toString()
|
|
||||||
+ File.separator;
|
+ File.separator;
|
||||||
} else if (os.contains("mac")) {
|
} else if (os.contains("mac")) {
|
||||||
return Paths.get(
|
return Paths.get(
|
||||||
System.getProperty("user.home"),
|
System.getProperty("user.home"),
|
||||||
"Library",
|
"Library",
|
||||||
"Application Support",
|
"Application Support",
|
||||||
"Stirling-PDF")
|
"Stirling-PDF")
|
||||||
.toString()
|
|
||||||
+ File.separator;
|
+ File.separator;
|
||||||
} else {
|
} else {
|
||||||
return Paths.get(
|
return Paths.get(
|
||||||
System.getProperty("user.home"), // parent path
|
System.getProperty("user.home"), // parent path
|
||||||
".config",
|
".config",
|
||||||
"Stirling-PDF")
|
"Stirling-PDF")
|
||||||
.toString()
|
|
||||||
+ File.separator;
|
+ File.separator;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
+4
-4
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
@@ -9,9 +9,9 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.ApplicationProperties;
|
import stirling.software.common.model.ApplicationProperties;
|
||||||
import stirling.software.SPDF.model.ApplicationProperties.CustomPaths.Operations;
|
import stirling.software.common.model.ApplicationProperties.CustomPaths.Operations;
|
||||||
import stirling.software.SPDF.model.ApplicationProperties.CustomPaths.Pipeline;
|
import stirling.software.common.model.ApplicationProperties.CustomPaths.Pipeline;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Configuration
|
@Configuration
|
||||||
+2
-4
@@ -1,6 +1,5 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.configuration;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||||
@@ -12,8 +11,7 @@ import org.springframework.core.io.support.PropertySourceFactory;
|
|||||||
public class YamlPropertySourceFactory implements PropertySourceFactory {
|
public class YamlPropertySourceFactory implements PropertySourceFactory {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
|
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
|
||||||
throws IOException {
|
|
||||||
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
|
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
|
||||||
factory.setResources(encodedResource.getResource());
|
factory.setResources(encodedResource.getResource());
|
||||||
Properties properties = factory.getObject();
|
Properties properties = factory.getObject();
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package stirling.software.common.configuration.interfaces;
|
||||||
|
|
||||||
|
public interface ShowAdminInterface {
|
||||||
|
default boolean getShowUpdateOnlyAdmins() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package stirling.software.common.controller;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.model.job.JobResult;
|
||||||
|
import stirling.software.common.model.job.JobStats;
|
||||||
|
import stirling.software.common.service.FileStorage;
|
||||||
|
import stirling.software.common.service.TaskManager;
|
||||||
|
|
||||||
|
/** REST controller for job-related endpoints */
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class JobController {
|
||||||
|
|
||||||
|
private final TaskManager taskManager;
|
||||||
|
private final FileStorage fileStorage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the status of a job
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return The job result
|
||||||
|
*/
|
||||||
|
@GetMapping("/api/v1/general/job/{jobId}")
|
||||||
|
public ResponseEntity<?> getJobStatus(@PathVariable("jobId") String jobId) {
|
||||||
|
JobResult result = taskManager.getJobResult(jobId);
|
||||||
|
if (result == null) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the result of a job
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return The job result
|
||||||
|
*/
|
||||||
|
@GetMapping("/api/v1/general/job/{jobId}/result")
|
||||||
|
public ResponseEntity<?> getJobResult(@PathVariable("jobId") String jobId) {
|
||||||
|
JobResult result = taskManager.getJobResult(jobId);
|
||||||
|
if (result == null) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result.isComplete()) {
|
||||||
|
return ResponseEntity.badRequest().body("Job is not complete yet");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.getError() != null) {
|
||||||
|
return ResponseEntity.badRequest().body("Job failed: " + result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.getFileId() != null) {
|
||||||
|
try {
|
||||||
|
byte[] fileContent = fileStorage.retrieveBytes(result.getFileId());
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header("Content-Type", result.getContentType())
|
||||||
|
.header(
|
||||||
|
"Content-Disposition",
|
||||||
|
"form-data; name=\"attachment\"; filename=\""
|
||||||
|
+ result.getOriginalFileName()
|
||||||
|
+ "\"")
|
||||||
|
.body(fileContent);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error retrieving file for job {}: {}", jobId, e.getMessage(), e);
|
||||||
|
return ResponseEntity.internalServerError()
|
||||||
|
.body("Error retrieving file: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok(result.getResult());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get statistics about jobs in the system
|
||||||
|
*
|
||||||
|
* @return Job statistics
|
||||||
|
*/
|
||||||
|
@GetMapping("/api/v1/general/job/stats")
|
||||||
|
public ResponseEntity<JobStats> getJobStats() {
|
||||||
|
JobStats stats = taskManager.getJobStats();
|
||||||
|
return ResponseEntity.ok(stats);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manually trigger cleanup of old jobs
|
||||||
|
*
|
||||||
|
* @return A response indicating how many jobs were cleaned up
|
||||||
|
*/
|
||||||
|
@PostMapping("/api/v1/general/job/cleanup")
|
||||||
|
public ResponseEntity<?> cleanupOldJobs() {
|
||||||
|
int beforeCount = taskManager.getJobStats().getTotalJobs();
|
||||||
|
taskManager.cleanupOldJobs();
|
||||||
|
int afterCount = taskManager.getJobStats().getTotalJobs();
|
||||||
|
int removedCount = beforeCount - afterCount;
|
||||||
|
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
Map.of(
|
||||||
|
"message", "Cleanup complete",
|
||||||
|
"removedJobs", removedCount,
|
||||||
|
"remainingJobs", afterCount));
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package stirling.software.common.controller;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import stirling.software.common.model.job.JobProgress;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class WebSocketProgressController {
|
||||||
|
|
||||||
|
private SimpMessagingTemplate messagingTemplate;
|
||||||
|
|
||||||
|
@Autowired(required = false)
|
||||||
|
public void setMessagingTemplate(SimpMessagingTemplate messagingTemplate) {
|
||||||
|
this.messagingTemplate = messagingTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendProgress(String jobId, JobProgress progress) {
|
||||||
|
if (messagingTemplate != null) {
|
||||||
|
messagingTemplate.convertAndSend("/topic/progress/" + jobId, progress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
-34
@@ -1,6 +1,4 @@
|
|||||||
package stirling.software.SPDF.model;
|
package stirling.software.common.model;
|
||||||
|
|
||||||
import static stirling.software.SPDF.utils.validation.Validator.*;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileNotFoundException;
|
import java.io.FileNotFoundException;
|
||||||
@@ -17,7 +15,6 @@ import java.util.List;
|
|||||||
|
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.core.Ordered;
|
import org.springframework.core.Ordered;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.core.env.ConfigurableEnvironment;
|
import org.springframework.core.env.ConfigurableEnvironment;
|
||||||
@@ -26,6 +23,7 @@ import org.springframework.core.io.ClassPathResource;
|
|||||||
import org.springframework.core.io.FileSystemResource;
|
import org.springframework.core.io.FileSystemResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.core.io.support.EncodedResource;
|
import org.springframework.core.io.support.EncodedResource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
@@ -33,21 +31,37 @@ import lombok.Setter;
|
|||||||
import lombok.ToString;
|
import lombok.ToString;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.config.InstallationPathConfig;
|
import stirling.software.common.configuration.InstallationPathConfig;
|
||||||
import stirling.software.SPDF.config.YamlPropertySourceFactory;
|
import stirling.software.common.configuration.YamlPropertySourceFactory;
|
||||||
import stirling.software.SPDF.model.exception.UnsupportedProviderException;
|
import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||||
import stirling.software.SPDF.model.provider.GitHubProvider;
|
import stirling.software.common.model.oauth2.GitHubProvider;
|
||||||
import stirling.software.SPDF.model.provider.GoogleProvider;
|
import stirling.software.common.model.oauth2.GoogleProvider;
|
||||||
import stirling.software.SPDF.model.provider.KeycloakProvider;
|
import stirling.software.common.model.oauth2.KeycloakProvider;
|
||||||
import stirling.software.SPDF.model.provider.Provider;
|
import stirling.software.common.model.oauth2.Provider;
|
||||||
|
import stirling.software.common.util.ValidationUtils;
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@ConfigurationProperties(prefix = "")
|
|
||||||
@Data
|
@Data
|
||||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||||
|
@ConfigurationProperties(prefix = "")
|
||||||
public class ApplicationProperties {
|
public class ApplicationProperties {
|
||||||
|
|
||||||
|
private Legal legal = new Legal();
|
||||||
|
private Security security = new Security();
|
||||||
|
private System system = new System();
|
||||||
|
private Ui ui = new Ui();
|
||||||
|
private Endpoints endpoints = new Endpoints();
|
||||||
|
private Metrics metrics = new Metrics();
|
||||||
|
private AutomaticallyGenerated automaticallyGenerated = new AutomaticallyGenerated();
|
||||||
|
|
||||||
|
private Mail mail = new Mail();
|
||||||
|
|
||||||
|
private Premium premium = new Premium();
|
||||||
|
private EnterpriseEdition enterpriseEdition = new EnterpriseEdition();
|
||||||
|
private AutoPipeline autoPipeline = new AutoPipeline();
|
||||||
|
private ProcessExecutor processExecutor = new ProcessExecutor();
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public PropertySource<?> dynamicYamlPropertySource(ConfigurableEnvironment environment)
|
public PropertySource<?> dynamicYamlPropertySource(ConfigurableEnvironment environment)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
@@ -74,21 +88,6 @@ public class ApplicationProperties {
|
|||||||
return propertySource;
|
return propertySource;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Legal legal = new Legal();
|
|
||||||
private Security security = new Security();
|
|
||||||
private System system = new System();
|
|
||||||
private Ui ui = new Ui();
|
|
||||||
private Endpoints endpoints = new Endpoints();
|
|
||||||
private Metrics metrics = new Metrics();
|
|
||||||
private AutomaticallyGenerated automaticallyGenerated = new AutomaticallyGenerated();
|
|
||||||
|
|
||||||
private Mail mail = new Mail();
|
|
||||||
|
|
||||||
private Premium premium = new Premium();
|
|
||||||
private EnterpriseEdition enterpriseEdition = new EnterpriseEdition();
|
|
||||||
private AutoPipeline autoPipeline = new AutoPipeline();
|
|
||||||
private ProcessExecutor processExecutor = new ProcessExecutor();
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class AutoPipeline {
|
public static class AutoPipeline {
|
||||||
private String outputFolder;
|
private String outputFolder;
|
||||||
@@ -248,11 +247,11 @@ public class ApplicationProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isSettingsValid() {
|
public boolean isSettingsValid() {
|
||||||
return !isStringEmpty(this.getIssuer())
|
return !ValidationUtils.isStringEmpty(this.getIssuer())
|
||||||
&& !isStringEmpty(this.getClientId())
|
&& !ValidationUtils.isStringEmpty(this.getClientId())
|
||||||
&& !isStringEmpty(this.getClientSecret())
|
&& !ValidationUtils.isStringEmpty(this.getClientSecret())
|
||||||
&& !isCollectionEmpty(this.getScopes())
|
&& !ValidationUtils.isCollectionEmpty(this.getScopes())
|
||||||
&& !isStringEmpty(this.getUseAsUsername());
|
&& !ValidationUtils.isStringEmpty(this.getUseAsUsername());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.model;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.model;
|
package stirling.software.common.model;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package stirling.software.common.model;
|
||||||
|
|
||||||
|
import java.util.Calendar;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class PdfMetadata {
|
||||||
|
private String author;
|
||||||
|
private String producer;
|
||||||
|
private String title;
|
||||||
|
private String creator;
|
||||||
|
private String subject;
|
||||||
|
private String keywords;
|
||||||
|
private Calendar creationDate;
|
||||||
|
private Calendar modificationDate;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package stirling.software.common.model.api;
|
||||||
|
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode
|
||||||
|
public class GeneralFile {
|
||||||
|
|
||||||
|
@Schema(
|
||||||
|
description = "The input file",
|
||||||
|
requiredMode = Schema.RequiredMode.REQUIRED,
|
||||||
|
format = "binary")
|
||||||
|
private MultipartFile fileInput;
|
||||||
|
}
|
||||||
+6
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.model.api;
|
package stirling.software.common.model.api;
|
||||||
|
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
@@ -14,8 +14,12 @@ import lombok.NoArgsConstructor;
|
|||||||
public class PDFFile {
|
public class PDFFile {
|
||||||
@Schema(
|
@Schema(
|
||||||
description = "The input PDF file",
|
description = "The input PDF file",
|
||||||
requiredMode = Schema.RequiredMode.REQUIRED,
|
|
||||||
contentMediaType = "application/pdf",
|
contentMediaType = "application/pdf",
|
||||||
format = "binary")
|
format = "binary")
|
||||||
private MultipartFile fileInput;
|
private MultipartFile fileInput;
|
||||||
|
|
||||||
|
@Schema(
|
||||||
|
description = "File ID for server-side files (can be used instead of fileInput)",
|
||||||
|
example = "a1b2c3d4-5678-90ab-cdef-ghijklmnopqr")
|
||||||
|
private String fileId;
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
package stirling.software.SPDF.model.api.converters;
|
package stirling.software.common.model.api.converters;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.model.api.misc;
|
package stirling.software.common.model.api.misc;
|
||||||
|
|
||||||
public enum HighContrastColorCombination {
|
public enum HighContrastColorCombination {
|
||||||
WHITE_TEXT_ON_BLACK,
|
WHITE_TEXT_ON_BLACK,
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.model.api.misc;
|
package stirling.software.common.model.api.misc;
|
||||||
|
|
||||||
public enum ReplaceAndInvert {
|
public enum ReplaceAndInvert {
|
||||||
HIGH_CONTRAST_COLOR,
|
HIGH_CONTRAST_COLOR,
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package stirling.software.common.model.api.security;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode
|
||||||
|
public class RedactionArea {
|
||||||
|
@Schema(description = "The left edge point of the area to be redacted.")
|
||||||
|
private Double x;
|
||||||
|
|
||||||
|
@Schema(description = "The top edge point of the area to be redacted.")
|
||||||
|
private Double y;
|
||||||
|
|
||||||
|
@Schema(description = "The height of the area to be redacted.")
|
||||||
|
private Double height;
|
||||||
|
|
||||||
|
@Schema(description = "The width of the area to be redacted.")
|
||||||
|
private Double width;
|
||||||
|
|
||||||
|
@Schema(description = "The page on which the area should be redacted.")
|
||||||
|
private Integer page;
|
||||||
|
|
||||||
|
@Schema(description = "The color used to redact the specified area.")
|
||||||
|
private String color;
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package stirling.software.common.model.enumeration;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public enum Role {
|
||||||
|
|
||||||
|
// Unlimited access
|
||||||
|
ADMIN("ROLE_ADMIN", Integer.MAX_VALUE, Integer.MAX_VALUE, "adminUserSettings.admin"),
|
||||||
|
|
||||||
|
// Unlimited access
|
||||||
|
USER("ROLE_USER", Integer.MAX_VALUE, Integer.MAX_VALUE, "adminUserSettings.user"),
|
||||||
|
|
||||||
|
// 40 API calls Per Day, 40 web calls
|
||||||
|
LIMITED_API_USER("ROLE_LIMITED_API_USER", 40, 40, "adminUserSettings.apiUser"),
|
||||||
|
|
||||||
|
// 20 API calls Per Day, 20 web calls
|
||||||
|
EXTRA_LIMITED_API_USER("ROLE_EXTRA_LIMITED_API_USER", 20, 20, "adminUserSettings.extraApiUser"),
|
||||||
|
|
||||||
|
// 0 API calls per day and 20 web calls
|
||||||
|
WEB_ONLY_USER("ROLE_WEB_ONLY_USER", 0, 20, "adminUserSettings.webOnlyUser"),
|
||||||
|
|
||||||
|
INTERNAL_API_USER(
|
||||||
|
"STIRLING-PDF-BACKEND-API-USER",
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
"adminUserSettings.internalApiUser"),
|
||||||
|
|
||||||
|
DEMO_USER("ROLE_DEMO_USER", 100, 100, "adminUserSettings.demoUser");
|
||||||
|
|
||||||
|
private final String roleId;
|
||||||
|
private final int apiCallsPerDay;
|
||||||
|
private final int webCallsPerDay;
|
||||||
|
private final String roleName;
|
||||||
|
|
||||||
|
public static String getRoleNameByRoleId(String roleId) {
|
||||||
|
// Using the fromString method to get the Role enum based on the roleId
|
||||||
|
Role role = fromString(roleId);
|
||||||
|
// Return the roleName of the found Role enum
|
||||||
|
return role.getRoleName();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method to retrieve all role IDs and role names
|
||||||
|
public static Map<String, String> getAllRoleDetails() {
|
||||||
|
// Using LinkedHashMap to preserve order
|
||||||
|
Map<String, String> roleDetails = new LinkedHashMap<>();
|
||||||
|
for (Role role : Role.values()) {
|
||||||
|
roleDetails.put(role.getRoleId(), role.getRoleName());
|
||||||
|
}
|
||||||
|
return roleDetails;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Role fromString(String roleId) {
|
||||||
|
for (Role role : Role.values()) {
|
||||||
|
if (role.getRoleId().equalsIgnoreCase(roleId)) {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("No Role defined for id: " + roleId);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.model;
|
package stirling.software.common.model.enumeration;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package stirling.software.common.model.exception;
|
||||||
|
|
||||||
|
public class UnsupportedClaimException extends RuntimeException {
|
||||||
|
public UnsupportedClaimException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.model.exception;
|
package stirling.software.common.model.exception;
|
||||||
|
|
||||||
public class UnsupportedProviderException extends Exception {
|
public class UnsupportedProviderException extends Exception {
|
||||||
public UnsupportedProviderException(String message) {
|
public UnsupportedProviderException(String message) {
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package stirling.software.common.model.job;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class JobProgress {
|
||||||
|
private String jobId;
|
||||||
|
private String status;
|
||||||
|
private int percentComplete;
|
||||||
|
private String message;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package stirling.software.common.model.job;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class JobResponse<T> {
|
||||||
|
private boolean async;
|
||||||
|
private String jobId;
|
||||||
|
private T result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package stirling.software.common.model.job;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/** Represents the result of a job execution. Used by the TaskManager to store job results. */
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class JobResult {
|
||||||
|
|
||||||
|
/** The job ID */
|
||||||
|
private String jobId;
|
||||||
|
|
||||||
|
/** Flag indicating if the job is complete */
|
||||||
|
private boolean complete;
|
||||||
|
|
||||||
|
/** Error message if the job failed */
|
||||||
|
private String error;
|
||||||
|
|
||||||
|
/** The file ID of the result file, if applicable */
|
||||||
|
private String fileId;
|
||||||
|
|
||||||
|
/** Original file name, if applicable */
|
||||||
|
private String originalFileName;
|
||||||
|
|
||||||
|
/** MIME type of the result, if applicable */
|
||||||
|
private String contentType;
|
||||||
|
|
||||||
|
/** Time when the job was created */
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
/** Time when the job was completed */
|
||||||
|
private LocalDateTime completedAt;
|
||||||
|
|
||||||
|
/** The actual result object, if not a file */
|
||||||
|
private Object result;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new JobResult with the given job ID
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return A new JobResult
|
||||||
|
*/
|
||||||
|
public static JobResult createNew(String jobId) {
|
||||||
|
return JobResult.builder()
|
||||||
|
.jobId(jobId)
|
||||||
|
.complete(false)
|
||||||
|
.createdAt(LocalDateTime.now())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark this job as complete with a file result
|
||||||
|
*
|
||||||
|
* @param fileId The file ID of the result
|
||||||
|
* @param originalFileName The original file name
|
||||||
|
* @param contentType The content type of the file
|
||||||
|
*/
|
||||||
|
public void completeWithFile(String fileId, String originalFileName, String contentType) {
|
||||||
|
this.complete = true;
|
||||||
|
this.fileId = fileId;
|
||||||
|
this.originalFileName = originalFileName;
|
||||||
|
this.contentType = contentType;
|
||||||
|
this.completedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark this job as complete with a general result
|
||||||
|
*
|
||||||
|
* @param result The result object
|
||||||
|
*/
|
||||||
|
public void completeWithResult(Object result) {
|
||||||
|
this.complete = true;
|
||||||
|
this.result = result;
|
||||||
|
this.completedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark this job as failed with an error message
|
||||||
|
*
|
||||||
|
* @param error The error message
|
||||||
|
*/
|
||||||
|
public void failWithError(String error) {
|
||||||
|
this.complete = true;
|
||||||
|
this.error = error;
|
||||||
|
this.completedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package stirling.software.common.model.job;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/** Represents statistics about jobs in the system */
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class JobStats {
|
||||||
|
|
||||||
|
/** Total number of jobs (active and completed) */
|
||||||
|
private int totalJobs;
|
||||||
|
|
||||||
|
/** Number of active (incomplete) jobs */
|
||||||
|
private int activeJobs;
|
||||||
|
|
||||||
|
/** Number of completed jobs */
|
||||||
|
private int completedJobs;
|
||||||
|
|
||||||
|
/** Number of failed jobs */
|
||||||
|
private int failedJobs;
|
||||||
|
|
||||||
|
/** Number of successful jobs */
|
||||||
|
private int successfulJobs;
|
||||||
|
|
||||||
|
/** Number of jobs with file results */
|
||||||
|
private int fileResultJobs;
|
||||||
|
|
||||||
|
/** The oldest active job's creation timestamp */
|
||||||
|
private LocalDateTime oldestActiveJobTime;
|
||||||
|
|
||||||
|
/** The newest active job's creation timestamp */
|
||||||
|
private LocalDateTime newestActiveJobTime;
|
||||||
|
|
||||||
|
/** The average processing time for completed jobs in milliseconds */
|
||||||
|
private long averageProcessingTimeMs;
|
||||||
|
}
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
package stirling.software.SPDF.model.provider;
|
package stirling.software.common.model.oauth2;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.UsernameAttribute;
|
import stirling.software.common.model.enumeration.UsernameAttribute;
|
||||||
|
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class GitHubProvider extends Provider {
|
public class GitHubProvider extends Provider {
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
package stirling.software.SPDF.model.provider;
|
package stirling.software.common.model.oauth2;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.UsernameAttribute;
|
import stirling.software.common.model.enumeration.UsernameAttribute;
|
||||||
|
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class GoogleProvider extends Provider {
|
public class GoogleProvider extends Provider {
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
package stirling.software.SPDF.model.provider;
|
package stirling.software.common.model.oauth2;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.UsernameAttribute;
|
import stirling.software.common.model.enumeration.UsernameAttribute;
|
||||||
|
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class KeycloakProvider extends Provider {
|
public class KeycloakProvider extends Provider {
|
||||||
+7
-7
@@ -1,6 +1,6 @@
|
|||||||
package stirling.software.SPDF.model.provider;
|
package stirling.software.common.model.oauth2;
|
||||||
|
|
||||||
import static stirling.software.SPDF.model.UsernameAttribute.EMAIL;
|
import static stirling.software.common.model.enumeration.UsernameAttribute.EMAIL;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
@@ -9,8 +9,8 @@ import java.util.Collection;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.UsernameAttribute;
|
import stirling.software.common.model.enumeration.UsernameAttribute;
|
||||||
import stirling.software.SPDF.model.exception.UnsupportedUsernameAttribute;
|
import stirling.software.common.model.exception.UnsupportedClaimException;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@@ -83,7 +83,7 @@ public class Provider {
|
|||||||
return usernameAttribute;
|
return usernameAttribute;
|
||||||
}
|
}
|
||||||
default ->
|
default ->
|
||||||
throw new UnsupportedUsernameAttribute(
|
throw new UnsupportedClaimException(
|
||||||
String.format(EXCEPTION_MESSAGE, usernameAttribute, clientName));
|
String.format(EXCEPTION_MESSAGE, usernameAttribute, clientName));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,7 +94,7 @@ public class Provider {
|
|||||||
return usernameAttribute;
|
return usernameAttribute;
|
||||||
}
|
}
|
||||||
default ->
|
default ->
|
||||||
throw new UnsupportedUsernameAttribute(
|
throw new UnsupportedClaimException(
|
||||||
String.format(EXCEPTION_MESSAGE, usernameAttribute, clientName));
|
String.format(EXCEPTION_MESSAGE, usernameAttribute, clientName));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,7 +105,7 @@ public class Provider {
|
|||||||
return usernameAttribute;
|
return usernameAttribute;
|
||||||
}
|
}
|
||||||
default ->
|
default ->
|
||||||
throw new UnsupportedUsernameAttribute(
|
throw new UnsupportedClaimException(
|
||||||
String.format(EXCEPTION_MESSAGE, usernameAttribute, clientName));
|
String.format(EXCEPTION_MESSAGE, usernameAttribute, clientName));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.service;
|
package stirling.software.common.service;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -22,7 +22,7 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adaptive PDF document factory that optimizes memory usage based on file size and available system
|
* Adaptive PDF document factory that optimizes memory usage based on file size and available system
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class FileOrUploadService {
|
||||||
|
|
||||||
|
@Value("${stirling.tempDir:/tmp/stirling-files}")
|
||||||
|
private String tempDirPath;
|
||||||
|
|
||||||
|
public Path resolveFilePath(String fileId) {
|
||||||
|
return Path.of(tempDirPath).resolve(fileId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MultipartFile toMockMultipartFile(String name, byte[] data) throws IOException {
|
||||||
|
return new CustomMultipartFile(name, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom implementation of MultipartFile
|
||||||
|
private static class CustomMultipartFile implements MultipartFile {
|
||||||
|
private final String name;
|
||||||
|
private final byte[] content;
|
||||||
|
|
||||||
|
public CustomMultipartFile(String name, byte[] content) {
|
||||||
|
this.name = name;
|
||||||
|
this.content = content;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getOriginalFilename() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getContentType() {
|
||||||
|
return "application/pdf";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return content == null || content.length == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getSize() {
|
||||||
|
return content.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] getBytes() throws IOException {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public java.io.InputStream getInputStream() throws IOException {
|
||||||
|
return new ByteArrayInputStream(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
|
||||||
|
Files.write(dest.toPath(), content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service for storing and retrieving files with unique file IDs. Used by the AutoJobPostMapping
|
||||||
|
* system to handle file references.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class FileStorage {
|
||||||
|
|
||||||
|
@Value("${stirling.tempDir:/tmp/stirling-files}")
|
||||||
|
private String tempDirPath;
|
||||||
|
|
||||||
|
private final FileOrUploadService fileOrUploadService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store a file and return its unique ID
|
||||||
|
*
|
||||||
|
* @param file The file to store
|
||||||
|
* @return The unique ID assigned to the file
|
||||||
|
* @throws IOException If there is an error storing the file
|
||||||
|
*/
|
||||||
|
public String storeFile(MultipartFile file) throws IOException {
|
||||||
|
String fileId = generateFileId();
|
||||||
|
Path filePath = getFilePath(fileId);
|
||||||
|
|
||||||
|
// Ensure the directory exists
|
||||||
|
Files.createDirectories(filePath.getParent());
|
||||||
|
|
||||||
|
// Transfer the file to the storage location
|
||||||
|
file.transferTo(filePath.toFile());
|
||||||
|
|
||||||
|
log.debug("Stored file with ID: {}", fileId);
|
||||||
|
return fileId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store a byte array as a file and return its unique ID
|
||||||
|
*
|
||||||
|
* @param bytes The byte array to store
|
||||||
|
* @param originalName The original name of the file (for extension)
|
||||||
|
* @return The unique ID assigned to the file
|
||||||
|
* @throws IOException If there is an error storing the file
|
||||||
|
*/
|
||||||
|
public String storeBytes(byte[] bytes, String originalName) throws IOException {
|
||||||
|
String fileId = generateFileId();
|
||||||
|
Path filePath = getFilePath(fileId);
|
||||||
|
|
||||||
|
// Ensure the directory exists
|
||||||
|
Files.createDirectories(filePath.getParent());
|
||||||
|
|
||||||
|
// Write the bytes to the file
|
||||||
|
Files.write(filePath, bytes);
|
||||||
|
|
||||||
|
log.debug("Stored byte array with ID: {}", fileId);
|
||||||
|
return fileId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a file by its ID as a MultipartFile
|
||||||
|
*
|
||||||
|
* @param fileId The ID of the file to retrieve
|
||||||
|
* @return The file as a MultipartFile
|
||||||
|
* @throws IOException If the file doesn't exist or can't be read
|
||||||
|
*/
|
||||||
|
public MultipartFile retrieveFile(String fileId) throws IOException {
|
||||||
|
Path filePath = getFilePath(fileId);
|
||||||
|
|
||||||
|
if (!Files.exists(filePath)) {
|
||||||
|
throw new IOException("File not found with ID: " + fileId);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] fileData = Files.readAllBytes(filePath);
|
||||||
|
return fileOrUploadService.toMockMultipartFile(fileId, fileData);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a file by its ID as a byte array
|
||||||
|
*
|
||||||
|
* @param fileId The ID of the file to retrieve
|
||||||
|
* @return The file as a byte array
|
||||||
|
* @throws IOException If the file doesn't exist or can't be read
|
||||||
|
*/
|
||||||
|
public byte[] retrieveBytes(String fileId) throws IOException {
|
||||||
|
Path filePath = getFilePath(fileId);
|
||||||
|
|
||||||
|
if (!Files.exists(filePath)) {
|
||||||
|
throw new IOException("File not found with ID: " + fileId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Files.readAllBytes(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a file by its ID
|
||||||
|
*
|
||||||
|
* @param fileId The ID of the file to delete
|
||||||
|
* @return true if the file was deleted, false otherwise
|
||||||
|
*/
|
||||||
|
public boolean deleteFile(String fileId) {
|
||||||
|
try {
|
||||||
|
Path filePath = getFilePath(fileId);
|
||||||
|
return Files.deleteIfExists(filePath);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Error deleting file with ID: {}", fileId, e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a file exists by its ID
|
||||||
|
*
|
||||||
|
* @param fileId The ID of the file to check
|
||||||
|
* @return true if the file exists, false otherwise
|
||||||
|
*/
|
||||||
|
public boolean fileExists(String fileId) {
|
||||||
|
Path filePath = getFilePath(fileId);
|
||||||
|
return Files.exists(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the path for a file ID
|
||||||
|
*
|
||||||
|
* @param fileId The ID of the file
|
||||||
|
* @return The path to the file
|
||||||
|
*/
|
||||||
|
private Path getFilePath(String fileId) {
|
||||||
|
return Path.of(tempDirPath).resolve(fileId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a unique file ID
|
||||||
|
*
|
||||||
|
* @return A unique file ID
|
||||||
|
*/
|
||||||
|
private String generateFileId() {
|
||||||
|
return UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.controller.WebSocketProgressController;
|
||||||
|
import stirling.software.common.model.job.JobProgress;
|
||||||
|
import stirling.software.common.model.job.JobResponse;
|
||||||
|
import stirling.software.common.util.ExecutorFactory;
|
||||||
|
|
||||||
|
/** Service for executing jobs asynchronously or synchronously */
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class JobExecutorService {
|
||||||
|
|
||||||
|
private final TaskManager taskManager;
|
||||||
|
private final WebSocketProgressController webSocketSender;
|
||||||
|
private final FileStorage fileStorage;
|
||||||
|
private final HttpServletRequest request;
|
||||||
|
private final ResourceMonitor resourceMonitor;
|
||||||
|
private final JobQueue jobQueue;
|
||||||
|
private final ExecutorService executor = ExecutorFactory.newVirtualOrCachedThreadExecutor();
|
||||||
|
private final long effectiveTimeoutMs;
|
||||||
|
|
||||||
|
public JobExecutorService(
|
||||||
|
TaskManager taskManager,
|
||||||
|
WebSocketProgressController webSocketSender,
|
||||||
|
FileStorage fileStorage,
|
||||||
|
HttpServletRequest request,
|
||||||
|
ResourceMonitor resourceMonitor,
|
||||||
|
JobQueue jobQueue,
|
||||||
|
@Value("${spring.mvc.async.request-timeout:1200000}") long asyncRequestTimeoutMs,
|
||||||
|
@Value("${server.servlet.session.timeout:30m}") String sessionTimeout) {
|
||||||
|
this.taskManager = taskManager;
|
||||||
|
this.webSocketSender = webSocketSender;
|
||||||
|
this.fileStorage = fileStorage;
|
||||||
|
this.request = request;
|
||||||
|
this.resourceMonitor = resourceMonitor;
|
||||||
|
this.jobQueue = jobQueue;
|
||||||
|
|
||||||
|
// Parse session timeout and calculate effective timeout once during initialization
|
||||||
|
long sessionTimeoutMs = parseSessionTimeout(sessionTimeout);
|
||||||
|
this.effectiveTimeoutMs = Math.min(asyncRequestTimeoutMs, sessionTimeoutMs);
|
||||||
|
log.debug(
|
||||||
|
"Job executor configured with effective timeout of {} ms", this.effectiveTimeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a job either asynchronously or synchronously
|
||||||
|
*
|
||||||
|
* @param async Whether to run the job asynchronously
|
||||||
|
* @param work The work to be done
|
||||||
|
* @return The response
|
||||||
|
*/
|
||||||
|
public ResponseEntity<?> runJobGeneric(boolean async, Supplier<Object> work) {
|
||||||
|
return runJobGeneric(async, work, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a job either asynchronously or synchronously with a custom timeout
|
||||||
|
*
|
||||||
|
* @param async Whether to run the job asynchronously
|
||||||
|
* @param work The work to be done
|
||||||
|
* @param customTimeoutMs Custom timeout in milliseconds, or -1 to use the default
|
||||||
|
* @return The response
|
||||||
|
*/
|
||||||
|
public ResponseEntity<?> runJobGeneric(
|
||||||
|
boolean async, Supplier<Object> work, long customTimeoutMs) {
|
||||||
|
return runJobGeneric(async, work, customTimeoutMs, false, 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a job either asynchronously or synchronously with custom parameters
|
||||||
|
*
|
||||||
|
* @param async Whether to run the job asynchronously
|
||||||
|
* @param work The work to be done
|
||||||
|
* @param customTimeoutMs Custom timeout in milliseconds, or -1 to use the default
|
||||||
|
* @param queueable Whether this job can be queued when system resources are limited
|
||||||
|
* @param resourceWeight The resource weight of this job (1-100)
|
||||||
|
* @return The response
|
||||||
|
*/
|
||||||
|
public ResponseEntity<?> runJobGeneric(
|
||||||
|
boolean async,
|
||||||
|
Supplier<Object> work,
|
||||||
|
long customTimeoutMs,
|
||||||
|
boolean queueable,
|
||||||
|
int resourceWeight) {
|
||||||
|
String jobId = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
// Store the job ID in the request for potential use by other components
|
||||||
|
if (request != null) {
|
||||||
|
request.setAttribute("jobId", jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine which timeout to use
|
||||||
|
long timeoutToUse = customTimeoutMs > 0 ? customTimeoutMs : effectiveTimeoutMs;
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"Running job with ID: {}, async: {}, timeout: {}ms, queueable: {}, weight: {}",
|
||||||
|
jobId,
|
||||||
|
async,
|
||||||
|
timeoutToUse,
|
||||||
|
queueable,
|
||||||
|
resourceWeight);
|
||||||
|
|
||||||
|
// Check if we need to queue this job based on resource availability
|
||||||
|
boolean shouldQueue =
|
||||||
|
queueable
|
||||||
|
&& async
|
||||||
|
&& // Only async jobs can be queued
|
||||||
|
resourceMonitor.shouldQueueJob(resourceWeight);
|
||||||
|
|
||||||
|
if (shouldQueue) {
|
||||||
|
// Queue the job instead of executing immediately
|
||||||
|
log.debug(
|
||||||
|
"Queueing job {} due to resource constraints (weight: {})",
|
||||||
|
jobId,
|
||||||
|
resourceWeight);
|
||||||
|
|
||||||
|
taskManager.createTask(jobId);
|
||||||
|
|
||||||
|
// Create a specialized wrapper that updates the TaskManager
|
||||||
|
Supplier<Object> wrappedWork =
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
Object result = work.get();
|
||||||
|
processJobResult(jobId, result);
|
||||||
|
return result;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(
|
||||||
|
"Error executing queued job {}: {}", jobId, e.getMessage(), e);
|
||||||
|
taskManager.setError(jobId, e.getMessage());
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Queue the job and get the future
|
||||||
|
CompletableFuture<ResponseEntity<?>> future =
|
||||||
|
jobQueue.queueJob(jobId, resourceWeight, wrappedWork, timeoutToUse);
|
||||||
|
|
||||||
|
// Return immediately with job ID
|
||||||
|
return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));
|
||||||
|
} else if (async) {
|
||||||
|
taskManager.createTask(jobId);
|
||||||
|
webSocketSender.sendProgress(jobId, new JobProgress(jobId, "Started", 0, "Running"));
|
||||||
|
|
||||||
|
executor.execute(
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
log.debug(
|
||||||
|
"Running async job {} with timeout {} ms", jobId, timeoutToUse);
|
||||||
|
|
||||||
|
// Execute with timeout
|
||||||
|
Object result = executeWithTimeout(() -> work.get(), timeoutToUse);
|
||||||
|
processJobResult(jobId, result);
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId, new JobProgress(jobId, "Done", 100, "Complete"));
|
||||||
|
} catch (TimeoutException te) {
|
||||||
|
log.error("Job {} timed out after {} ms", jobId, timeoutToUse);
|
||||||
|
taskManager.setError(jobId, "Job timed out");
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId, new JobProgress(jobId, "Error", 100, "Job timed out"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error executing job {}: {}", jobId, e.getMessage(), e);
|
||||||
|
taskManager.setError(jobId, e.getMessage());
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId, new JobProgress(jobId, "Error", 100, e.getMessage()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
log.debug("Running sync job with timeout {} ms", timeoutToUse);
|
||||||
|
|
||||||
|
// Execute with timeout
|
||||||
|
Object result = executeWithTimeout(() -> work.get(), timeoutToUse);
|
||||||
|
|
||||||
|
// If the result is already a ResponseEntity, return it directly
|
||||||
|
if (result instanceof ResponseEntity) {
|
||||||
|
return (ResponseEntity<?>) result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process different result types
|
||||||
|
return handleResultForSyncJob(result);
|
||||||
|
} catch (TimeoutException te) {
|
||||||
|
log.error("Synchronous job timed out after {} ms", timeoutToUse);
|
||||||
|
return ResponseEntity.internalServerError()
|
||||||
|
.body(Map.of("error", "Job timed out after " + timeoutToUse + " ms"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error executing synchronous job: {}", e.getMessage(), e);
|
||||||
|
// Construct a JSON error response
|
||||||
|
return ResponseEntity.internalServerError()
|
||||||
|
.body(Map.of("error", "Job failed: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process the result of an asynchronous job
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param result The result
|
||||||
|
*/
|
||||||
|
private void processJobResult(String jobId, Object result) {
|
||||||
|
try {
|
||||||
|
if (result instanceof byte[]) {
|
||||||
|
// Store byte array as a file
|
||||||
|
String fileId = fileStorage.storeBytes((byte[]) result, "result.pdf");
|
||||||
|
taskManager.setFileResult(jobId, fileId, "result.pdf", "application/pdf");
|
||||||
|
log.debug("Stored byte[] result with fileId: {}", fileId);
|
||||||
|
} else if (result instanceof ResponseEntity) {
|
||||||
|
ResponseEntity<?> response = (ResponseEntity<?>) result;
|
||||||
|
Object body = response.getBody();
|
||||||
|
|
||||||
|
if (body instanceof byte[]) {
|
||||||
|
// Extract filename from content-disposition header if available
|
||||||
|
String filename = "result.pdf";
|
||||||
|
String contentType = "application/pdf";
|
||||||
|
|
||||||
|
if (response.getHeaders().getContentDisposition() != null) {
|
||||||
|
String disposition =
|
||||||
|
response.getHeaders().getContentDisposition().toString();
|
||||||
|
if (disposition.contains("filename=")) {
|
||||||
|
filename =
|
||||||
|
disposition.substring(
|
||||||
|
disposition.indexOf("filename=") + 9,
|
||||||
|
disposition.lastIndexOf("\""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.getHeaders().getContentType() != null) {
|
||||||
|
contentType = response.getHeaders().getContentType().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
String fileId = fileStorage.storeBytes((byte[]) body, filename);
|
||||||
|
taskManager.setFileResult(jobId, fileId, filename, contentType);
|
||||||
|
log.debug("Stored ResponseEntity<byte[]> result with fileId: {}", fileId);
|
||||||
|
} else {
|
||||||
|
// Check if the response body contains a fileId
|
||||||
|
if (body != null && body.toString().contains("fileId")) {
|
||||||
|
try {
|
||||||
|
// Try to extract fileId using reflection
|
||||||
|
java.lang.reflect.Method getFileId =
|
||||||
|
body.getClass().getMethod("getFileId");
|
||||||
|
String fileId = (String) getFileId.invoke(body);
|
||||||
|
|
||||||
|
if (fileId != null && !fileId.isEmpty()) {
|
||||||
|
// Try to get filename and content type
|
||||||
|
String filename = "result.pdf";
|
||||||
|
String contentType = "application/pdf";
|
||||||
|
|
||||||
|
try {
|
||||||
|
java.lang.reflect.Method getOriginalFileName =
|
||||||
|
body.getClass().getMethod("getOriginalFilename");
|
||||||
|
String origName = (String) getOriginalFileName.invoke(body);
|
||||||
|
if (origName != null && !origName.isEmpty()) {
|
||||||
|
filename = origName;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug(
|
||||||
|
"Could not get original filename: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
java.lang.reflect.Method getContentType =
|
||||||
|
body.getClass().getMethod("getContentType");
|
||||||
|
String ct = (String) getContentType.invoke(body);
|
||||||
|
if (ct != null && !ct.isEmpty()) {
|
||||||
|
contentType = ct;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Could not get content type: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
taskManager.setFileResult(jobId, fileId, filename, contentType);
|
||||||
|
log.debug("Extracted fileId from response body: {}", fileId);
|
||||||
|
|
||||||
|
taskManager.setComplete(jobId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug(
|
||||||
|
"Failed to extract fileId from response body: {}",
|
||||||
|
e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store generic result
|
||||||
|
taskManager.setResult(jobId, body);
|
||||||
|
}
|
||||||
|
} else if (result instanceof MultipartFile) {
|
||||||
|
MultipartFile file = (MultipartFile) result;
|
||||||
|
String fileId = fileStorage.storeFile(file);
|
||||||
|
taskManager.setFileResult(
|
||||||
|
jobId, fileId, file.getOriginalFilename(), file.getContentType());
|
||||||
|
log.debug("Stored MultipartFile result with fileId: {}", fileId);
|
||||||
|
} else {
|
||||||
|
// Check if result has a fileId field
|
||||||
|
if (result != null) {
|
||||||
|
try {
|
||||||
|
// Try to extract fileId using reflection
|
||||||
|
java.lang.reflect.Method getFileId =
|
||||||
|
result.getClass().getMethod("getFileId");
|
||||||
|
String fileId = (String) getFileId.invoke(result);
|
||||||
|
|
||||||
|
if (fileId != null && !fileId.isEmpty()) {
|
||||||
|
// Try to get filename and content type
|
||||||
|
String filename = "result.pdf";
|
||||||
|
String contentType = "application/pdf";
|
||||||
|
|
||||||
|
try {
|
||||||
|
java.lang.reflect.Method getOriginalFileName =
|
||||||
|
result.getClass().getMethod("getOriginalFilename");
|
||||||
|
String origName = (String) getOriginalFileName.invoke(result);
|
||||||
|
if (origName != null && !origName.isEmpty()) {
|
||||||
|
filename = origName;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Could not get original filename: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
java.lang.reflect.Method getContentType =
|
||||||
|
result.getClass().getMethod("getContentType");
|
||||||
|
String ct = (String) getContentType.invoke(result);
|
||||||
|
if (ct != null && !ct.isEmpty()) {
|
||||||
|
contentType = ct;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Could not get content type: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
taskManager.setFileResult(jobId, fileId, filename, contentType);
|
||||||
|
log.debug("Extracted fileId from result object: {}", fileId);
|
||||||
|
|
||||||
|
taskManager.setComplete(jobId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug(
|
||||||
|
"Failed to extract fileId from result object: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default case: store the result as is
|
||||||
|
taskManager.setResult(jobId, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
taskManager.setComplete(jobId);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error processing job result: {}", e.getMessage(), e);
|
||||||
|
taskManager.setError(jobId, "Error processing result: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle different result types for synchronous jobs
|
||||||
|
*
|
||||||
|
* @param result The result object
|
||||||
|
* @return The appropriate ResponseEntity
|
||||||
|
* @throws IOException If there is an error processing the result
|
||||||
|
*/
|
||||||
|
private ResponseEntity<?> handleResultForSyncJob(Object result) throws IOException {
|
||||||
|
if (result instanceof byte[]) {
|
||||||
|
// Return byte array as PDF
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_PDF)
|
||||||
|
.header(
|
||||||
|
HttpHeaders.CONTENT_DISPOSITION,
|
||||||
|
"form-data; name=\"attachment\"; filename=\"result.pdf\"")
|
||||||
|
.body(result);
|
||||||
|
} else if (result instanceof MultipartFile) {
|
||||||
|
// Return MultipartFile content
|
||||||
|
MultipartFile file = (MultipartFile) result;
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.parseMediaType(file.getContentType()))
|
||||||
|
.header(
|
||||||
|
HttpHeaders.CONTENT_DISPOSITION,
|
||||||
|
"form-data; name=\"attachment\"; filename=\""
|
||||||
|
+ file.getOriginalFilename()
|
||||||
|
+ "\"")
|
||||||
|
.body(file.getBytes());
|
||||||
|
} else {
|
||||||
|
// Default case: return as JSON
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse session timeout string (e.g., "30m", "1h") to milliseconds
|
||||||
|
*
|
||||||
|
* @param timeout The timeout string
|
||||||
|
* @return The timeout in milliseconds
|
||||||
|
*/
|
||||||
|
private long parseSessionTimeout(String timeout) {
|
||||||
|
if (timeout == null || timeout.isEmpty()) {
|
||||||
|
return 30 * 60 * 1000; // Default: 30 minutes
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
String value = timeout.replaceAll("[^\\d.]", "");
|
||||||
|
String unit = timeout.replaceAll("[\\d.]", "");
|
||||||
|
|
||||||
|
double numericValue = Double.parseDouble(value);
|
||||||
|
|
||||||
|
return switch (unit.toLowerCase()) {
|
||||||
|
case "s" -> (long) (numericValue * 1000);
|
||||||
|
case "m" -> (long) (numericValue * 60 * 1000);
|
||||||
|
case "h" -> (long) (numericValue * 60 * 60 * 1000);
|
||||||
|
case "d" -> (long) (numericValue * 24 * 60 * 60 * 1000);
|
||||||
|
default -> (long) (numericValue * 60 * 1000); // Default to minutes
|
||||||
|
};
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Could not parse session timeout '{}', using default", timeout);
|
||||||
|
return 30 * 60 * 1000; // Default: 30 minutes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a supplier with a timeout
|
||||||
|
*
|
||||||
|
* @param supplier The supplier to execute
|
||||||
|
* @param timeoutMs The timeout in milliseconds
|
||||||
|
* @return The result from the supplier
|
||||||
|
* @throws TimeoutException If the execution times out
|
||||||
|
* @throws Exception If the supplier throws an exception
|
||||||
|
*/
|
||||||
|
private <T> T executeWithTimeout(Supplier<T> supplier, long timeoutMs)
|
||||||
|
throws TimeoutException, Exception {
|
||||||
|
java.util.concurrent.CompletableFuture<T> future =
|
||||||
|
java.util.concurrent.CompletableFuture.supplyAsync(supplier);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
|
||||||
|
} catch (java.util.concurrent.TimeoutException e) {
|
||||||
|
future.cancel(true);
|
||||||
|
throw new TimeoutException("Execution timed out after " + timeoutMs + " ms");
|
||||||
|
} catch (java.util.concurrent.ExecutionException e) {
|
||||||
|
throw (Exception) e.getCause();
|
||||||
|
} catch (java.util.concurrent.CancellationException e) {
|
||||||
|
throw new Exception("Execution was cancelled", e);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new Exception("Execution was interrupted", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.controller.WebSocketProgressController;
|
||||||
|
import stirling.software.common.model.job.JobProgress;
|
||||||
|
import stirling.software.common.util.ExecutorFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages a queue of jobs with dynamic sizing based on system resources. Used when system resources
|
||||||
|
* are limited to prevent overloading.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class JobQueue {
|
||||||
|
|
||||||
|
private final ResourceMonitor resourceMonitor;
|
||||||
|
private final WebSocketProgressController webSocketSender;
|
||||||
|
|
||||||
|
@Value("${stirling.job.queue.base-capacity:10}")
|
||||||
|
private int baseQueueCapacity = 10;
|
||||||
|
|
||||||
|
@Value("${stirling.job.queue.min-capacity:2}")
|
||||||
|
private int minQueueCapacity = 2;
|
||||||
|
|
||||||
|
@Value("${stirling.job.queue.check-interval-ms:1000}")
|
||||||
|
private long queueCheckIntervalMs = 1000;
|
||||||
|
|
||||||
|
@Value("${stirling.job.queue.max-wait-time-ms:600000}")
|
||||||
|
private long maxWaitTimeMs = 600000; // 10 minutes
|
||||||
|
|
||||||
|
private BlockingQueue<QueuedJob> jobQueue;
|
||||||
|
private final Map<String, QueuedJob> jobMap = new ConcurrentHashMap<>();
|
||||||
|
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
private final ExecutorService jobExecutor = ExecutorFactory.newVirtualOrCachedThreadExecutor();
|
||||||
|
|
||||||
|
private boolean shuttingDown = false;
|
||||||
|
|
||||||
|
@Getter private int rejectedJobs = 0;
|
||||||
|
|
||||||
|
@Getter private int totalQueuedJobs = 0;
|
||||||
|
|
||||||
|
@Getter private int currentQueueSize = 0;
|
||||||
|
|
||||||
|
/** Represents a job waiting in the queue. */
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
private static class QueuedJob {
|
||||||
|
private final String jobId;
|
||||||
|
private final int resourceWeight;
|
||||||
|
private final Supplier<Object> work;
|
||||||
|
private final long timeoutMs;
|
||||||
|
private final Instant queuedAt;
|
||||||
|
private CompletableFuture<ResponseEntity<?>> future;
|
||||||
|
private volatile boolean cancelled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public JobQueue(ResourceMonitor resourceMonitor, WebSocketProgressController webSocketSender) {
|
||||||
|
this.resourceMonitor = resourceMonitor;
|
||||||
|
this.webSocketSender = webSocketSender;
|
||||||
|
|
||||||
|
// Initialize with dynamic capacity
|
||||||
|
int capacity =
|
||||||
|
resourceMonitor.calculateDynamicQueueCapacity(baseQueueCapacity, minQueueCapacity);
|
||||||
|
this.jobQueue = new LinkedBlockingQueue<>(capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void initialize() {
|
||||||
|
log.debug(
|
||||||
|
"Starting job queue with base capacity {}, min capacity {}",
|
||||||
|
baseQueueCapacity,
|
||||||
|
minQueueCapacity);
|
||||||
|
|
||||||
|
// Periodically process the job queue
|
||||||
|
scheduler.scheduleWithFixedDelay(
|
||||||
|
this::processQueue, 0, queueCheckIntervalMs, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
// Periodically update queue capacity based on resource usage
|
||||||
|
scheduler.scheduleWithFixedDelay(
|
||||||
|
this::updateQueueCapacity,
|
||||||
|
10000, // Initial delay
|
||||||
|
30000, // 30 second interval
|
||||||
|
TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void shutdown() {
|
||||||
|
log.info("Shutting down job queue");
|
||||||
|
shuttingDown = true;
|
||||||
|
|
||||||
|
// Complete any futures that are still waiting
|
||||||
|
jobMap.forEach(
|
||||||
|
(id, job) -> {
|
||||||
|
if (!job.future.isDone()) {
|
||||||
|
job.future.completeExceptionally(
|
||||||
|
new RuntimeException("Server shutting down, job cancelled"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
scheduler.shutdownNow();
|
||||||
|
jobExecutor.shutdownNow();
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"Job queue shutdown complete. Stats: total={}, rejected={}",
|
||||||
|
totalQueuedJobs,
|
||||||
|
rejectedJobs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queues a job for execution when resources permit.
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param resourceWeight The resource weight of the job (1-100)
|
||||||
|
* @param work The work to be done
|
||||||
|
* @param timeoutMs The timeout in milliseconds
|
||||||
|
* @return A CompletableFuture that will complete when the job is executed
|
||||||
|
*/
|
||||||
|
public CompletableFuture<ResponseEntity<?>> queueJob(
|
||||||
|
String jobId, int resourceWeight, Supplier<Object> work, long timeoutMs) {
|
||||||
|
|
||||||
|
// Create a CompletableFuture to track this job's completion
|
||||||
|
CompletableFuture<ResponseEntity<?>> future = new CompletableFuture<>();
|
||||||
|
|
||||||
|
// Create the queued job
|
||||||
|
QueuedJob job =
|
||||||
|
new QueuedJob(jobId, resourceWeight, work, timeoutMs, Instant.now(), future, false);
|
||||||
|
|
||||||
|
// Store in our map for lookup
|
||||||
|
jobMap.put(jobId, job);
|
||||||
|
|
||||||
|
// Update stats
|
||||||
|
totalQueuedJobs++;
|
||||||
|
currentQueueSize = jobQueue.size();
|
||||||
|
|
||||||
|
// Try to add to the queue
|
||||||
|
try {
|
||||||
|
boolean added = jobQueue.offer(job, 5, TimeUnit.SECONDS);
|
||||||
|
if (!added) {
|
||||||
|
log.warn("Queue full, rejecting job {}", jobId);
|
||||||
|
rejectedJobs++;
|
||||||
|
future.completeExceptionally(
|
||||||
|
new RuntimeException("Job queue full, please try again later"));
|
||||||
|
jobMap.remove(jobId);
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"Job {} queued for execution (weight: {}, queue size: {})",
|
||||||
|
jobId,
|
||||||
|
resourceWeight,
|
||||||
|
jobQueue.size());
|
||||||
|
|
||||||
|
// Notify client via WebSocket that job is queued
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId, new JobProgress(jobId, "Queued", 0, "Waiting in queue for resources"));
|
||||||
|
|
||||||
|
return future;
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
future.completeExceptionally(new RuntimeException("Job queue interrupted"));
|
||||||
|
jobMap.remove(jobId);
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the current capacity of the job queue.
|
||||||
|
*
|
||||||
|
* @return The current capacity
|
||||||
|
*/
|
||||||
|
public int getQueueCapacity() {
|
||||||
|
return ((LinkedBlockingQueue<QueuedJob>) jobQueue).remainingCapacity() + jobQueue.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Updates the capacity of the job queue based on available system resources. */
|
||||||
|
private void updateQueueCapacity() {
|
||||||
|
try {
|
||||||
|
// Calculate new capacity
|
||||||
|
int newCapacity =
|
||||||
|
resourceMonitor.calculateDynamicQueueCapacity(
|
||||||
|
baseQueueCapacity, minQueueCapacity);
|
||||||
|
|
||||||
|
int currentCapacity = getQueueCapacity();
|
||||||
|
if (newCapacity != currentCapacity) {
|
||||||
|
log.debug(
|
||||||
|
"Updating job queue capacity from {} to {}", currentCapacity, newCapacity);
|
||||||
|
|
||||||
|
// Create new queue with updated capacity
|
||||||
|
BlockingQueue<QueuedJob> newQueue = new LinkedBlockingQueue<>(newCapacity);
|
||||||
|
|
||||||
|
// Transfer jobs from old queue to new queue
|
||||||
|
jobQueue.drainTo(newQueue);
|
||||||
|
jobQueue = newQueue;
|
||||||
|
|
||||||
|
currentQueueSize = jobQueue.size();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error updating queue capacity: {}", e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Processes jobs in the queue, executing them when resources permit. */
|
||||||
|
private void processQueue() {
|
||||||
|
if (shuttingDown || jobQueue.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get current resource status
|
||||||
|
ResourceMonitor.ResourceStatus status = resourceMonitor.getCurrentStatus().get();
|
||||||
|
|
||||||
|
// Check if we should execute any jobs
|
||||||
|
boolean canExecuteJobs = (status != ResourceMonitor.ResourceStatus.CRITICAL);
|
||||||
|
|
||||||
|
if (!canExecuteJobs) {
|
||||||
|
// Under critical load, don't execute any jobs
|
||||||
|
log.debug("System under critical load, delaying job execution");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get jobs from the queue, up to a limit based on resource availability
|
||||||
|
int jobsToProcess =
|
||||||
|
Math.max(
|
||||||
|
1,
|
||||||
|
switch (status) {
|
||||||
|
case OK -> 3;
|
||||||
|
case WARNING -> 1;
|
||||||
|
case CRITICAL -> 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
for (int i = 0; i < jobsToProcess && !jobQueue.isEmpty(); i++) {
|
||||||
|
QueuedJob job = jobQueue.poll();
|
||||||
|
if (job == null) break;
|
||||||
|
|
||||||
|
// Check if it's been waiting too long
|
||||||
|
long waitTimeMs = Instant.now().toEpochMilli() - job.queuedAt.toEpochMilli();
|
||||||
|
if (waitTimeMs > maxWaitTimeMs) {
|
||||||
|
log.warn(
|
||||||
|
"Job {} exceeded maximum wait time ({} ms), executing anyway",
|
||||||
|
job.jobId,
|
||||||
|
waitTimeMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from our map
|
||||||
|
jobMap.remove(job.jobId);
|
||||||
|
currentQueueSize = jobQueue.size();
|
||||||
|
|
||||||
|
// Notify via WebSocket
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
job.jobId,
|
||||||
|
new JobProgress(job.jobId, "Processing", 10, "Starting job execution"));
|
||||||
|
|
||||||
|
// Execute the job
|
||||||
|
executeJob(job);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error processing job queue: {}", e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes a job from the queue.
|
||||||
|
*
|
||||||
|
* @param job The job to execute
|
||||||
|
*/
|
||||||
|
private void executeJob(QueuedJob job) {
|
||||||
|
if (job.cancelled) {
|
||||||
|
log.debug("Job {} was cancelled, not executing", job.jobId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
jobExecutor.execute(
|
||||||
|
() -> {
|
||||||
|
log.debug("Executing queued job {} (queued at {})", job.jobId, job.queuedAt);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Execute with timeout
|
||||||
|
Object result = executeWithTimeout(job.work, job.timeoutMs);
|
||||||
|
|
||||||
|
// Process the result
|
||||||
|
if (result instanceof ResponseEntity) {
|
||||||
|
job.future.complete((ResponseEntity<?>) result);
|
||||||
|
} else {
|
||||||
|
job.future.complete(ResponseEntity.ok(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update WebSocket
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
job.jobId,
|
||||||
|
new JobProgress(
|
||||||
|
job.jobId, "Complete", 100, "Job completed successfully"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(
|
||||||
|
"Error executing queued job {}: {}", job.jobId, e.getMessage(), e);
|
||||||
|
job.future.completeExceptionally(e);
|
||||||
|
|
||||||
|
// Update WebSocket
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
job.jobId,
|
||||||
|
new JobProgress(
|
||||||
|
job.jobId, "Error", 100, "Job failed: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a supplier with a timeout.
|
||||||
|
*
|
||||||
|
* @param supplier The supplier to execute
|
||||||
|
* @param timeoutMs The timeout in milliseconds
|
||||||
|
* @return The result from the supplier
|
||||||
|
* @throws Exception If there is an execution error
|
||||||
|
*/
|
||||||
|
private <T> T executeWithTimeout(Supplier<T> supplier, long timeoutMs) throws Exception {
|
||||||
|
CompletableFuture<T> future = CompletableFuture.supplyAsync(supplier);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (timeoutMs <= 0) {
|
||||||
|
// No timeout
|
||||||
|
return future.join();
|
||||||
|
} else {
|
||||||
|
// With timeout
|
||||||
|
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
} catch (TimeoutException e) {
|
||||||
|
future.cancel(true);
|
||||||
|
throw new TimeoutException("Job timed out after " + timeoutMs + "ms");
|
||||||
|
} catch (ExecutionException e) {
|
||||||
|
throw (Exception) e.getCause();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new InterruptedException("Job was interrupted");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a job is queued.
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return true if the job is queued
|
||||||
|
*/
|
||||||
|
public boolean isJobQueued(String jobId) {
|
||||||
|
return jobMap.containsKey(jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the current position of a job in the queue.
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return The position (0-based) or -1 if not found
|
||||||
|
*/
|
||||||
|
public int getJobPosition(String jobId) {
|
||||||
|
if (!jobMap.containsKey(jobId)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Count positions
|
||||||
|
int position = 0;
|
||||||
|
for (QueuedJob job : jobQueue) {
|
||||||
|
if (job.jobId.equals(jobId)) {
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we didn't find it in the queue but it's in the map,
|
||||||
|
// it might be executing already
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancels a queued job.
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return true if the job was cancelled, false if not found
|
||||||
|
*/
|
||||||
|
public boolean cancelJob(String jobId) {
|
||||||
|
QueuedJob job = jobMap.remove(jobId);
|
||||||
|
if (job != null) {
|
||||||
|
job.cancelled = true;
|
||||||
|
job.future.completeExceptionally(new RuntimeException("Job cancelled by user"));
|
||||||
|
|
||||||
|
// Try to remove from queue if it's still there
|
||||||
|
jobQueue.remove(job);
|
||||||
|
currentQueueSize = jobQueue.size();
|
||||||
|
|
||||||
|
log.debug("Job {} cancelled", jobId);
|
||||||
|
|
||||||
|
// Update WebSocket
|
||||||
|
webSocketSender.sendProgress(
|
||||||
|
jobId, new JobProgress(jobId, "Cancelled", 100, "Job cancelled by user"));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get queue statistics.
|
||||||
|
*
|
||||||
|
* @return A map containing queue statistics
|
||||||
|
*/
|
||||||
|
public Map<String, Object> getQueueStats() {
|
||||||
|
return Map.of(
|
||||||
|
"queuedJobs", jobQueue.size(),
|
||||||
|
"queueCapacity", getQueueCapacity(),
|
||||||
|
"totalQueuedJobs", totalQueuedJobs,
|
||||||
|
"rejectedJobs", rejectedJobs,
|
||||||
|
"resourceStatus", resourceMonitor.getCurrentStatus().get().name());
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-4
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.service;
|
package stirling.software.common.service;
|
||||||
|
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
|
|
||||||
@@ -7,9 +7,8 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import stirling.software.SPDF.controller.api.pipeline.UserServiceInterface;
|
import stirling.software.common.model.ApplicationProperties;
|
||||||
import stirling.software.SPDF.model.ApplicationProperties;
|
import stirling.software.common.model.PdfMetadata;
|
||||||
import stirling.software.SPDF.model.PdfMetadata;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class PdfMetadataService {
|
public class PdfMetadataService {
|
||||||
+14
-6
@@ -1,12 +1,21 @@
|
|||||||
package stirling.software.SPDF.service;
|
package stirling.software.common.service;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.lang.management.*;
|
import java.lang.management.GarbageCollectorMXBean;
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.lang.management.MemoryMXBean;
|
||||||
|
import java.lang.management.OperatingSystemMXBean;
|
||||||
|
import java.lang.management.RuntimeMXBean;
|
||||||
|
import java.lang.management.ThreadMXBean;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.NetworkInterface;
|
import java.net.NetworkInterface;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.*;
|
import java.util.Enumeration;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@@ -16,8 +25,7 @@ import org.springframework.stereotype.Service;
|
|||||||
|
|
||||||
import com.posthog.java.PostHog;
|
import com.posthog.java.PostHog;
|
||||||
|
|
||||||
import stirling.software.SPDF.controller.api.pipeline.UserServiceInterface;
|
import stirling.software.common.model.ApplicationProperties;
|
||||||
import stirling.software.SPDF.model.ApplicationProperties;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class PostHogService {
|
public class PostHogService {
|
||||||
@@ -200,7 +208,7 @@ public class PostHogService {
|
|||||||
|
|
||||||
// New environment variables
|
// New environment variables
|
||||||
dockerMetrics.put("version_tag", System.getenv("VERSION_TAG"));
|
dockerMetrics.put("version_tag", System.getenv("VERSION_TAG"));
|
||||||
dockerMetrics.put("docker_enable_security", System.getenv("DOCKER_ENABLE_SECURITY"));
|
dockerMetrics.put("without_enhanced_features", System.getenv("WITHOUT_ENHANCED_FEATURES"));
|
||||||
dockerMetrics.put("fat_docker", System.getenv("FAT_DOCKER"));
|
dockerMetrics.put("fat_docker", System.getenv("FAT_DOCKER"));
|
||||||
|
|
||||||
return dockerMetrics;
|
return dockerMetrics;
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.lang.management.MemoryMXBean;
|
||||||
|
import java.lang.management.OperatingSystemMXBean;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Monitors system resources (CPU, memory) to inform job scheduling decisions. Provides information
|
||||||
|
* about available resources to prevent overloading the system.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class ResourceMonitor {
|
||||||
|
|
||||||
|
@Value("${stirling.resource.memory.critical-threshold:0.9}")
|
||||||
|
private double memoryCriticalThreshold = 0.9; // 90% usage is critical
|
||||||
|
|
||||||
|
@Value("${stirling.resource.memory.high-threshold:0.75}")
|
||||||
|
private double memoryHighThreshold = 0.75; // 75% usage is high
|
||||||
|
|
||||||
|
@Value("${stirling.resource.cpu.critical-threshold:0.9}")
|
||||||
|
private double cpuCriticalThreshold = 0.9; // 90% usage is critical
|
||||||
|
|
||||||
|
@Value("${stirling.resource.cpu.high-threshold:0.75}")
|
||||||
|
private double cpuHighThreshold = 0.75; // 75% usage is high
|
||||||
|
|
||||||
|
@Value("${stirling.resource.monitor.interval-ms:60000}")
|
||||||
|
private long monitorIntervalMs = 60000; // 60 seconds
|
||||||
|
|
||||||
|
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
private final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
|
||||||
|
private final OperatingSystemMXBean osMXBean = ManagementFactory.getOperatingSystemMXBean();
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
private final AtomicReference<ResourceStatus> currentStatus =
|
||||||
|
new AtomicReference<>(ResourceStatus.OK);
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
private final AtomicReference<ResourceMetrics> latestMetrics =
|
||||||
|
new AtomicReference<>(new ResourceMetrics());
|
||||||
|
|
||||||
|
/** Represents the current status of system resources. */
|
||||||
|
public enum ResourceStatus {
|
||||||
|
/** Resources are available, normal operations can proceed */
|
||||||
|
OK,
|
||||||
|
|
||||||
|
/** Resources are under strain, consider queueing high-resource operations */
|
||||||
|
WARNING,
|
||||||
|
|
||||||
|
/** Resources are critically low, queue all operations */
|
||||||
|
CRITICAL
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Detailed metrics about system resources. */
|
||||||
|
@Getter
|
||||||
|
public static class ResourceMetrics {
|
||||||
|
private final double cpuUsage;
|
||||||
|
private final double memoryUsage;
|
||||||
|
private final long freeMemoryBytes;
|
||||||
|
private final long totalMemoryBytes;
|
||||||
|
private final long maxMemoryBytes;
|
||||||
|
private final Instant timestamp;
|
||||||
|
|
||||||
|
public ResourceMetrics() {
|
||||||
|
this(0, 0, 0, 0, 0, Instant.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResourceMetrics(
|
||||||
|
double cpuUsage,
|
||||||
|
double memoryUsage,
|
||||||
|
long freeMemoryBytes,
|
||||||
|
long totalMemoryBytes,
|
||||||
|
long maxMemoryBytes,
|
||||||
|
Instant timestamp) {
|
||||||
|
this.cpuUsage = cpuUsage;
|
||||||
|
this.memoryUsage = memoryUsage;
|
||||||
|
this.freeMemoryBytes = freeMemoryBytes;
|
||||||
|
this.totalMemoryBytes = totalMemoryBytes;
|
||||||
|
this.maxMemoryBytes = maxMemoryBytes;
|
||||||
|
this.timestamp = timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the age of these metrics.
|
||||||
|
*
|
||||||
|
* @return Duration since these metrics were collected
|
||||||
|
*/
|
||||||
|
public Duration getAge() {
|
||||||
|
return Duration.between(timestamp, Instant.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if these metrics are stale (older than threshold).
|
||||||
|
*
|
||||||
|
* @param thresholdMs Staleness threshold in milliseconds
|
||||||
|
* @return true if metrics are stale
|
||||||
|
*/
|
||||||
|
public boolean isStale(long thresholdMs) {
|
||||||
|
return getAge().toMillis() > thresholdMs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void initialize() {
|
||||||
|
log.debug("Starting resource monitoring with interval of {}ms", monitorIntervalMs);
|
||||||
|
scheduler.scheduleAtFixedRate(
|
||||||
|
this::updateResourceMetrics, 0, monitorIntervalMs, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void shutdown() {
|
||||||
|
log.info("Shutting down resource monitoring");
|
||||||
|
scheduler.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Updates the resource metrics by sampling current system state. */
|
||||||
|
private void updateResourceMetrics() {
|
||||||
|
try {
|
||||||
|
// Get CPU usage
|
||||||
|
double cpuUsage = osMXBean.getSystemLoadAverage() / osMXBean.getAvailableProcessors();
|
||||||
|
if (cpuUsage < 0) cpuUsage = getAlternativeCpuLoad(); // Fallback if not available
|
||||||
|
|
||||||
|
// Get memory usage
|
||||||
|
long heapUsed = memoryMXBean.getHeapMemoryUsage().getUsed();
|
||||||
|
long nonHeapUsed = memoryMXBean.getNonHeapMemoryUsage().getUsed();
|
||||||
|
long totalUsed = heapUsed + nonHeapUsed;
|
||||||
|
|
||||||
|
long maxMemory = Runtime.getRuntime().maxMemory();
|
||||||
|
long totalMemory = Runtime.getRuntime().totalMemory();
|
||||||
|
long freeMemory = Runtime.getRuntime().freeMemory();
|
||||||
|
|
||||||
|
double memoryUsage = (double) totalUsed / maxMemory;
|
||||||
|
|
||||||
|
// Create new metrics
|
||||||
|
ResourceMetrics metrics =
|
||||||
|
new ResourceMetrics(
|
||||||
|
cpuUsage,
|
||||||
|
memoryUsage,
|
||||||
|
freeMemory,
|
||||||
|
totalMemory,
|
||||||
|
maxMemory,
|
||||||
|
Instant.now());
|
||||||
|
latestMetrics.set(metrics);
|
||||||
|
|
||||||
|
// Determine system status
|
||||||
|
ResourceStatus newStatus;
|
||||||
|
if (cpuUsage > cpuCriticalThreshold || memoryUsage > memoryCriticalThreshold) {
|
||||||
|
newStatus = ResourceStatus.CRITICAL;
|
||||||
|
} else if (cpuUsage > cpuHighThreshold || memoryUsage > memoryHighThreshold) {
|
||||||
|
newStatus = ResourceStatus.WARNING;
|
||||||
|
} else {
|
||||||
|
newStatus = ResourceStatus.OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update status if it changed
|
||||||
|
ResourceStatus oldStatus = currentStatus.getAndSet(newStatus);
|
||||||
|
if (oldStatus != newStatus) {
|
||||||
|
log.info("System resource status changed from {} to {}", oldStatus, newStatus);
|
||||||
|
log.info(
|
||||||
|
"Current metrics - CPU: {:.1f}%, Memory: {:.1f}%, Free Memory: {} MB",
|
||||||
|
cpuUsage * 100, memoryUsage * 100, freeMemory / (1024 * 1024));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error updating resource metrics: {}", e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Alternative method to estimate CPU load if getSystemLoadAverage() is not available. This is a
|
||||||
|
* fallback and less accurate than the official JMX method.
|
||||||
|
*
|
||||||
|
* @return Estimated CPU load as a value between 0.0 and 1.0
|
||||||
|
*/
|
||||||
|
private double getAlternativeCpuLoad() {
|
||||||
|
try {
|
||||||
|
// Try to get CPU time if available through reflection
|
||||||
|
// This is a fallback since we can't directly cast to platform-specific classes
|
||||||
|
try {
|
||||||
|
java.lang.reflect.Method m =
|
||||||
|
osMXBean.getClass().getDeclaredMethod("getProcessCpuLoad");
|
||||||
|
m.setAccessible(true);
|
||||||
|
return (double) m.invoke(osMXBean);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Try the older method
|
||||||
|
try {
|
||||||
|
java.lang.reflect.Method m =
|
||||||
|
osMXBean.getClass().getDeclaredMethod("getSystemCpuLoad");
|
||||||
|
m.setAccessible(true);
|
||||||
|
return (double) m.invoke(osMXBean);
|
||||||
|
} catch (Exception e2) {
|
||||||
|
log.trace(
|
||||||
|
"Could not get CPU load through reflection, assuming moderate load (0.5)");
|
||||||
|
return 0.5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.trace("Could not get CPU load, assuming moderate load (0.5)");
|
||||||
|
return 0.5; // Default to moderate load
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the dynamic job queue capacity based on current resource usage.
|
||||||
|
*
|
||||||
|
* @param baseCapacity The base capacity when system is under minimal load
|
||||||
|
* @param minCapacity The minimum capacity to maintain even under high load
|
||||||
|
* @return The calculated job queue capacity
|
||||||
|
*/
|
||||||
|
public int calculateDynamicQueueCapacity(int baseCapacity, int minCapacity) {
|
||||||
|
ResourceMetrics metrics = latestMetrics.get();
|
||||||
|
ResourceStatus status = currentStatus.get();
|
||||||
|
|
||||||
|
// Simple linear reduction based on memory and CPU load
|
||||||
|
double capacityFactor =
|
||||||
|
switch (status) {
|
||||||
|
case OK -> 1.0;
|
||||||
|
case WARNING -> 0.6;
|
||||||
|
case CRITICAL -> 0.3;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Apply additional reduction based on specific memory pressure
|
||||||
|
if (metrics.memoryUsage > 0.8) {
|
||||||
|
capacityFactor *= 0.5; // Further reduce capacity under memory pressure
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate capacity with minimum safeguard
|
||||||
|
int capacity = (int) Math.max(minCapacity, Math.ceil(baseCapacity * capacityFactor));
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"Dynamic queue capacity: {} (base: {}, factor: {:.2f}, status: {})",
|
||||||
|
capacity,
|
||||||
|
baseCapacity,
|
||||||
|
capacityFactor,
|
||||||
|
status);
|
||||||
|
|
||||||
|
return capacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a job with the given weight can be executed immediately or should be queued based
|
||||||
|
* on current resource availability.
|
||||||
|
*
|
||||||
|
* @param resourceWeight The resource weight of the job (1-100)
|
||||||
|
* @return true if the job should be queued, false if it can run immediately
|
||||||
|
*/
|
||||||
|
public boolean shouldQueueJob(int resourceWeight) {
|
||||||
|
ResourceStatus status = currentStatus.get();
|
||||||
|
|
||||||
|
// Always run lightweight jobs (weight < 20) unless critical
|
||||||
|
if (resourceWeight < 20 && status != ResourceStatus.CRITICAL) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Medium weight jobs run immediately if resources are OK
|
||||||
|
if (resourceWeight < 60 && status == ResourceStatus.OK) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Heavy jobs (weight >= 60) and any job during WARNING/CRITICAL should be queued
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.model.job.JobResult;
|
||||||
|
import stirling.software.common.model.job.JobStats;
|
||||||
|
|
||||||
|
/** Manages async tasks and their results */
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class TaskManager {
|
||||||
|
private final Map<String, JobResult> jobResults = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Value("${stirling.jobResultExpiryMinutes:30}")
|
||||||
|
private int jobResultExpiryMinutes = 30;
|
||||||
|
|
||||||
|
private final FileStorage fileStorage;
|
||||||
|
private final ScheduledExecutorService cleanupExecutor =
|
||||||
|
Executors.newSingleThreadScheduledExecutor();
|
||||||
|
|
||||||
|
/** Initialize the task manager and start the cleanup scheduler */
|
||||||
|
public TaskManager(FileStorage fileStorage) {
|
||||||
|
this.fileStorage = fileStorage;
|
||||||
|
|
||||||
|
// Schedule periodic cleanup of old job results
|
||||||
|
cleanupExecutor.scheduleAtFixedRate(
|
||||||
|
this::cleanupOldJobs,
|
||||||
|
10, // Initial delay
|
||||||
|
10, // Interval
|
||||||
|
TimeUnit.MINUTES);
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"Task manager initialized with job result expiry of {} minutes",
|
||||||
|
jobResultExpiryMinutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new task with the given job ID
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
*/
|
||||||
|
public void createTask(String jobId) {
|
||||||
|
jobResults.put(jobId, JobResult.createNew(jobId));
|
||||||
|
log.debug("Created task with job ID: {}", jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the result of a task as a general object
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param result The result object
|
||||||
|
*/
|
||||||
|
public void setResult(String jobId, Object result) {
|
||||||
|
JobResult jobResult = getOrCreateJobResult(jobId);
|
||||||
|
jobResult.completeWithResult(result);
|
||||||
|
log.debug("Set result for job ID: {}", jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the result of a task as a file
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param fileId The file ID
|
||||||
|
* @param originalFileName The original file name
|
||||||
|
* @param contentType The content type of the file
|
||||||
|
*/
|
||||||
|
public void setFileResult(
|
||||||
|
String jobId, String fileId, String originalFileName, String contentType) {
|
||||||
|
JobResult jobResult = getOrCreateJobResult(jobId);
|
||||||
|
jobResult.completeWithFile(fileId, originalFileName, contentType);
|
||||||
|
log.debug("Set file result for job ID: {} with file ID: {}", jobId, fileId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set an error for a task
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param error The error message
|
||||||
|
*/
|
||||||
|
public void setError(String jobId, String error) {
|
||||||
|
JobResult jobResult = getOrCreateJobResult(jobId);
|
||||||
|
jobResult.failWithError(error);
|
||||||
|
log.debug("Set error for job ID: {}: {}", jobId, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark a task as complete
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
*/
|
||||||
|
public void setComplete(String jobId) {
|
||||||
|
JobResult jobResult = getOrCreateJobResult(jobId);
|
||||||
|
if (jobResult.getResult() == null
|
||||||
|
&& jobResult.getFileId() == null
|
||||||
|
&& jobResult.getError() == null) {
|
||||||
|
// If no result or error has been set, mark it as complete with an empty result
|
||||||
|
jobResult.completeWithResult("Task completed successfully");
|
||||||
|
}
|
||||||
|
log.debug("Marked job ID: {} as complete", jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a task is complete
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return true if the task is complete, false otherwise
|
||||||
|
*/
|
||||||
|
public boolean isComplete(String jobId) {
|
||||||
|
JobResult result = jobResults.get(jobId);
|
||||||
|
return result != null && result.isComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the result of a task
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return The result object, or null if the task doesn't exist or is not complete
|
||||||
|
*/
|
||||||
|
public JobResult getJobResult(String jobId) {
|
||||||
|
return jobResults.get(jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get statistics about all jobs in the system
|
||||||
|
*
|
||||||
|
* @return Job statistics
|
||||||
|
*/
|
||||||
|
public JobStats getJobStats() {
|
||||||
|
int totalJobs = jobResults.size();
|
||||||
|
int activeJobs = 0;
|
||||||
|
int completedJobs = 0;
|
||||||
|
int failedJobs = 0;
|
||||||
|
int successfulJobs = 0;
|
||||||
|
int fileResultJobs = 0;
|
||||||
|
|
||||||
|
LocalDateTime oldestActiveJobTime = null;
|
||||||
|
LocalDateTime newestActiveJobTime = null;
|
||||||
|
long totalProcessingTimeMs = 0;
|
||||||
|
|
||||||
|
for (JobResult result : jobResults.values()) {
|
||||||
|
if (result.isComplete()) {
|
||||||
|
completedJobs++;
|
||||||
|
|
||||||
|
// Calculate processing time for completed jobs
|
||||||
|
if (result.getCreatedAt() != null && result.getCompletedAt() != null) {
|
||||||
|
long processingTimeMs =
|
||||||
|
java.time.Duration.between(
|
||||||
|
result.getCreatedAt(), result.getCompletedAt())
|
||||||
|
.toMillis();
|
||||||
|
totalProcessingTimeMs += processingTimeMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.getError() != null) {
|
||||||
|
failedJobs++;
|
||||||
|
} else {
|
||||||
|
successfulJobs++;
|
||||||
|
if (result.getFileId() != null) {
|
||||||
|
fileResultJobs++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
activeJobs++;
|
||||||
|
|
||||||
|
// Track oldest and newest active jobs
|
||||||
|
if (result.getCreatedAt() != null) {
|
||||||
|
if (oldestActiveJobTime == null
|
||||||
|
|| result.getCreatedAt().isBefore(oldestActiveJobTime)) {
|
||||||
|
oldestActiveJobTime = result.getCreatedAt();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newestActiveJobTime == null
|
||||||
|
|| result.getCreatedAt().isAfter(newestActiveJobTime)) {
|
||||||
|
newestActiveJobTime = result.getCreatedAt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate average processing time
|
||||||
|
long averageProcessingTimeMs =
|
||||||
|
completedJobs > 0 ? totalProcessingTimeMs / completedJobs : 0;
|
||||||
|
|
||||||
|
return JobStats.builder()
|
||||||
|
.totalJobs(totalJobs)
|
||||||
|
.activeJobs(activeJobs)
|
||||||
|
.completedJobs(completedJobs)
|
||||||
|
.failedJobs(failedJobs)
|
||||||
|
.successfulJobs(successfulJobs)
|
||||||
|
.fileResultJobs(fileResultJobs)
|
||||||
|
.oldestActiveJobTime(oldestActiveJobTime)
|
||||||
|
.newestActiveJobTime(newestActiveJobTime)
|
||||||
|
.averageProcessingTimeMs(averageProcessingTimeMs)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get or create a job result
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @return The job result
|
||||||
|
*/
|
||||||
|
private JobResult getOrCreateJobResult(String jobId) {
|
||||||
|
return jobResults.computeIfAbsent(jobId, JobResult::createNew);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clean up old completed job results */
|
||||||
|
public void cleanupOldJobs() {
|
||||||
|
LocalDateTime expiryThreshold =
|
||||||
|
LocalDateTime.now().minus(jobResultExpiryMinutes, ChronoUnit.MINUTES);
|
||||||
|
int removedCount = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (Map.Entry<String, JobResult> entry : jobResults.entrySet()) {
|
||||||
|
JobResult result = entry.getValue();
|
||||||
|
|
||||||
|
// Remove completed jobs that are older than the expiry threshold
|
||||||
|
if (result.isComplete()
|
||||||
|
&& result.getCompletedAt() != null
|
||||||
|
&& result.getCompletedAt().isBefore(expiryThreshold)) {
|
||||||
|
|
||||||
|
// If the job has a file result, delete the file
|
||||||
|
if (result.getFileId() != null) {
|
||||||
|
try {
|
||||||
|
fileStorage.deleteFile(result.getFileId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn(
|
||||||
|
"Failed to delete file for job {}: {}",
|
||||||
|
entry.getKey(),
|
||||||
|
e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the job result
|
||||||
|
jobResults.remove(entry.getKey());
|
||||||
|
removedCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (removedCount > 0) {
|
||||||
|
log.info("Cleaned up {} expired job results", removedCount);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error during job cleanup: {}", e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shutdown the cleanup executor */
|
||||||
|
@PreDestroy
|
||||||
|
public void shutdown() {
|
||||||
|
try {
|
||||||
|
log.info("Shutting down job result cleanup executor");
|
||||||
|
cleanupExecutor.shutdown();
|
||||||
|
if (!cleanupExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||||
|
cleanupExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
cleanupExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.controller.api.pipeline;
|
package stirling.software.common.service;
|
||||||
|
|
||||||
public interface UserServiceInterface {
|
public interface UserServiceInterface {
|
||||||
String getApiKeyForUser(String username);
|
String getApiKeyForUser(String username);
|
||||||
+2
-2
@@ -1,10 +1,10 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
|
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
|
||||||
|
|
||||||
public class CheckProgramInstall {
|
public class CheckProgramInstall {
|
||||||
|
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import org.owasp.html.HtmlPolicyBuilder;
|
import org.owasp.html.HtmlPolicyBuilder;
|
||||||
import org.owasp.html.PolicyFactory;
|
import org.owasp.html.PolicyFactory;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.PrintWriter;
|
import java.io.PrintWriter;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package stirling.software.common.util;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class ExecutorFactory {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an ExecutorService using virtual threads if available (Java 21+), or falls back to a
|
||||||
|
* cached thread pool on older Java versions.
|
||||||
|
*/
|
||||||
|
public static ExecutorService newVirtualOrCachedThreadExecutor() {
|
||||||
|
try {
|
||||||
|
ExecutorService executor =
|
||||||
|
(ExecutorService)
|
||||||
|
Executors.class
|
||||||
|
.getMethod("newVirtualThreadPerTaskExecutor")
|
||||||
|
.invoke(null);
|
||||||
|
return executor;
|
||||||
|
} catch (NoSuchMethodException e) {
|
||||||
|
log.debug("Virtual threads not available; falling back to cached thread pool.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Error initializing virtual thread executor: {}", e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Executors.newCachedThreadPool();
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import static java.nio.file.StandardWatchEventKinds.*;
|
import static java.nio.file.StandardWatchEventKinds.*;
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ import org.springframework.stereotype.Component;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.config.RuntimePathConfig;
|
import stirling.software.common.configuration.RuntimePathConfig;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Slf4j
|
@Slf4j
|
||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
@@ -16,8 +16,8 @@ import java.util.zip.ZipOutputStream;
|
|||||||
|
|
||||||
import io.github.pixee.security.ZipSecurity;
|
import io.github.pixee.security.ZipSecurity;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.converters.HTMLToPdfRequest;
|
import stirling.software.common.model.api.converters.HTMLToPdfRequest;
|
||||||
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
|
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
|
||||||
|
|
||||||
public class FileToPdf {
|
public class FileToPdf {
|
||||||
|
|
||||||
+2
-3
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileOutputStream;
|
import java.io.FileOutputStream;
|
||||||
@@ -27,8 +27,7 @@ import io.github.pixee.security.Urls;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.config.InstallationPathConfig;
|
import stirling.software.common.configuration.InstallationPathConfig;
|
||||||
import stirling.software.SPDF.config.YamlHelper;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class GeneralUtils {
|
public class GeneralUtils {
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.awt.geom.AffineTransform;
|
import java.awt.geom.AffineTransform;
|
||||||
import java.awt.image.*;
|
import java.awt.image.*;
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -28,7 +28,7 @@ import io.github.pixee.security.Filenames;
|
|||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
|
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.awt.*;
|
import java.awt.*;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
@@ -35,7 +35,7 @@ import io.github.pixee.security.Filenames;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class PdfUtils {
|
public class PdfUtils {
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -17,7 +17,7 @@ import io.github.pixee.security.BoundedLineReader;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.ApplicationProperties;
|
import stirling.software.common.model.ApplicationProperties;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class ProcessExecutor {
|
public class ProcessExecutor {
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
+5
-12
@@ -1,10 +1,11 @@
|
|||||||
package stirling.software.SPDF.utils.validation;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.util.Collection;
|
import static stirling.software.common.util.ValidationUtils.isCollectionEmpty;
|
||||||
|
import static stirling.software.common.util.ValidationUtils.isStringEmpty;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.provider.Provider;
|
import stirling.software.common.model.oauth2.Provider;
|
||||||
|
|
||||||
public class Validator {
|
public class ProviderUtils {
|
||||||
|
|
||||||
public static boolean validateProvider(Provider provider) {
|
public static boolean validateProvider(Provider provider) {
|
||||||
if (provider == null) {
|
if (provider == null) {
|
||||||
@@ -25,12 +26,4 @@ public class Validator {
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isStringEmpty(String input) {
|
|
||||||
return input == null || input.isBlank();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static boolean isCollectionEmpty(Collection<String> input) {
|
|
||||||
return input == null || input.isEmpty();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+1
-3
@@ -1,14 +1,12 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
public class RequestUriUtils {
|
public class RequestUriUtils {
|
||||||
|
|
||||||
public static boolean isStaticResource(String requestURI) {
|
public static boolean isStaticResource(String requestURI) {
|
||||||
|
|
||||||
return isStaticResource("", requestURI);
|
return isStaticResource("", requestURI);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isStaticResource(String contextPath, String requestURI) {
|
public static boolean isStaticResource(String contextPath, String requestURI) {
|
||||||
|
|
||||||
return requestURI.startsWith(contextPath + "/css/")
|
return requestURI.startsWith(contextPath + "/css/")
|
||||||
|| requestURI.startsWith(contextPath + "/fonts/")
|
|| requestURI.startsWith(contextPath + "/fonts/")
|
||||||
|| requestURI.startsWith(contextPath + "/js/")
|
|| requestURI.startsWith(contextPath + "/js/")
|
||||||
+1
-3
@@ -1,9 +1,7 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.awt.*;
|
import java.awt.*;
|
||||||
|
|
||||||
import javax.swing.*;
|
|
||||||
|
|
||||||
public class UIScaling {
|
public class UIScaling {
|
||||||
private static final double BASE_RESOLUTION_WIDTH = 1920.0;
|
private static final double BASE_RESOLUTION_WIDTH = 1920.0;
|
||||||
private static final double BASE_RESOLUTION_HEIGHT = 1080.0;
|
private static final double BASE_RESOLUTION_HEIGHT = 1080.0;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package stirling.software.common.util;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
public class ValidationUtils {
|
||||||
|
|
||||||
|
public static boolean isStringEmpty(String input) {
|
||||||
|
return input == null || input.isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isCollectionEmpty(Collection<String> input) {
|
||||||
|
return input == null || input.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.config;
|
package stirling.software.common.util;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils.misc;
|
package stirling.software.common.util.misc;
|
||||||
|
|
||||||
import java.awt.*;
|
import java.awt.*;
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
@@ -24,8 +24,8 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.misc.HighContrastColorCombination;
|
import stirling.software.common.model.api.misc.HighContrastColorCombination;
|
||||||
import stirling.software.SPDF.model.api.misc.ReplaceAndInvert;
|
import stirling.software.common.model.api.misc.ReplaceAndInvert;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class CustomColorReplaceStrategy extends ReplaceAndInvertColorStrategy {
|
public class CustomColorReplaceStrategy extends ReplaceAndInvertColorStrategy {
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
package stirling.software.SPDF.utils.misc;
|
package stirling.software.common.util.misc;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.misc.HighContrastColorCombination;
|
import stirling.software.common.model.api.misc.HighContrastColorCombination;
|
||||||
import stirling.software.SPDF.model.api.misc.ReplaceAndInvert;
|
import stirling.software.common.model.api.misc.ReplaceAndInvert;
|
||||||
|
|
||||||
public class HighContrastColorReplaceDecider {
|
public class HighContrastColorReplaceDecider {
|
||||||
|
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils.misc;
|
package stirling.software.common.util.misc;
|
||||||
|
|
||||||
import java.awt.*;
|
import java.awt.*;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
@@ -19,7 +19,7 @@ import org.apache.pdfbox.rendering.PDFRenderer;
|
|||||||
import org.springframework.core.io.InputStreamResource;
|
import org.springframework.core.io.InputStreamResource;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.misc.ReplaceAndInvert;
|
import stirling.software.common.model.api.misc.ReplaceAndInvert;
|
||||||
|
|
||||||
public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
||||||
|
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils.misc;
|
package stirling.software.common.util.misc;
|
||||||
|
|
||||||
import java.awt.geom.Rectangle2D;
|
import java.awt.geom.Rectangle2D;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils.misc;
|
package stirling.software.common.util.misc;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
@@ -8,8 +8,8 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
import stirling.software.SPDF.model.api.misc.ReplaceAndInvert;
|
import stirling.software.common.model.api.misc.ReplaceAndInvert;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
+3
-4
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils.propertyeditor;
|
package stirling.software.common.util.propertyeditor;
|
||||||
|
|
||||||
import java.beans.PropertyEditorSupport;
|
import java.beans.PropertyEditorSupport;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.security.RedactionArea;
|
import stirling.software.common.model.api.security.RedactionArea;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class StringToArrayListPropertyEditor extends PropertyEditorSupport {
|
public class StringToArrayListPropertyEditor extends PropertyEditorSupport {
|
||||||
@@ -25,8 +25,7 @@ public class StringToArrayListPropertyEditor extends PropertyEditorSupport {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
|
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
|
||||||
TypeReference<ArrayList<RedactionArea>> typeRef =
|
TypeReference<ArrayList<RedactionArea>> typeRef = new TypeReference<>() {};
|
||||||
new TypeReference<ArrayList<RedactionArea>>() {};
|
|
||||||
List<RedactionArea> list = objectMapper.readValue(text, typeRef);
|
List<RedactionArea> list = objectMapper.readValue(text, typeRef);
|
||||||
setValue(list);
|
setValue(list);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
+2
-3
@@ -1,4 +1,4 @@
|
|||||||
package stirling.software.SPDF.utils.propertyeditor;
|
package stirling.software.common.util.propertyeditor;
|
||||||
|
|
||||||
import java.beans.PropertyEditorSupport;
|
import java.beans.PropertyEditorSupport;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -14,8 +14,7 @@ public class StringToMapPropertyEditor extends PropertyEditorSupport {
|
|||||||
@Override
|
@Override
|
||||||
public void setAsText(String text) throws IllegalArgumentException {
|
public void setAsText(String text) throws IllegalArgumentException {
|
||||||
try {
|
try {
|
||||||
TypeReference<HashMap<String, String>> typeRef =
|
TypeReference<HashMap<String, String>> typeRef = new TypeReference<>() {};
|
||||||
new TypeReference<HashMap<String, String>>() {};
|
|
||||||
Map<String, String> map = objectMapper.readValue(text, typeRef);
|
Map<String, String> map = objectMapper.readValue(text, typeRef);
|
||||||
setValue(map);
|
setValue(map);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
+214
@@ -0,0 +1,214 @@
|
|||||||
|
package stirling.software.common.annotations;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.aspectj.lang.ProceedingJoinPoint;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Captor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
import stirling.software.common.aop.AutoJobAspect;
|
||||||
|
import stirling.software.common.controller.WebSocketProgressController;
|
||||||
|
import stirling.software.common.model.api.PDFFile;
|
||||||
|
import stirling.software.common.service.FileOrUploadService;
|
||||||
|
import stirling.software.common.service.FileStorage;
|
||||||
|
import stirling.software.common.service.JobExecutorService;
|
||||||
|
import stirling.software.common.service.JobQueue;
|
||||||
|
import stirling.software.common.service.ResourceMonitor;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class AutoJobPostMappingIntegrationTest {
|
||||||
|
|
||||||
|
private AutoJobAspect autoJobAspect;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private JobExecutorService jobExecutorService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpServletRequest request;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private FileOrUploadService fileOrUploadService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private FileStorage fileStorage;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private WebSocketProgressController webSocketSender;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ResourceMonitor resourceMonitor;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private JobQueue jobQueue;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
autoJobAspect = new AutoJobAspect(
|
||||||
|
jobExecutorService,
|
||||||
|
request,
|
||||||
|
fileOrUploadService,
|
||||||
|
fileStorage,
|
||||||
|
webSocketSender
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ProceedingJoinPoint joinPoint;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AutoJobPostMapping autoJobPostMapping;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Supplier<Object>> workCaptor;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Boolean> asyncCaptor;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Long> timeoutCaptor;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Boolean> queueableCaptor;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Integer> resourceWeightCaptor;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldExecuteWithCustomParameters() throws Throwable {
|
||||||
|
// Given
|
||||||
|
PDFFile pdfFile = new PDFFile();
|
||||||
|
pdfFile.setFileId("test-file-id");
|
||||||
|
Object[] args = new Object[] { pdfFile };
|
||||||
|
|
||||||
|
when(joinPoint.getArgs()).thenReturn(args);
|
||||||
|
when(request.getParameter("async")).thenReturn("true");
|
||||||
|
when(autoJobPostMapping.timeout()).thenReturn(60000L);
|
||||||
|
when(autoJobPostMapping.retryCount()).thenReturn(3);
|
||||||
|
when(autoJobPostMapping.trackProgress()).thenReturn(true);
|
||||||
|
when(autoJobPostMapping.queueable()).thenReturn(true);
|
||||||
|
when(autoJobPostMapping.resourceWeight()).thenReturn(75);
|
||||||
|
|
||||||
|
MultipartFile mockFile = mock(MultipartFile.class);
|
||||||
|
when(fileStorage.retrieveFile("test-file-id")).thenReturn(mockFile);
|
||||||
|
|
||||||
|
|
||||||
|
when(jobExecutorService.runJobGeneric(
|
||||||
|
anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))
|
||||||
|
.thenReturn(ResponseEntity.ok("success"));
|
||||||
|
|
||||||
|
// When
|
||||||
|
Object result = autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals(ResponseEntity.ok("success"), result);
|
||||||
|
|
||||||
|
verify(jobExecutorService).runJobGeneric(
|
||||||
|
asyncCaptor.capture(),
|
||||||
|
workCaptor.capture(),
|
||||||
|
timeoutCaptor.capture(),
|
||||||
|
queueableCaptor.capture(),
|
||||||
|
resourceWeightCaptor.capture());
|
||||||
|
|
||||||
|
assertTrue(asyncCaptor.getValue(), "Async should be true");
|
||||||
|
assertEquals(60000L, timeoutCaptor.getValue(), "Timeout should be 60000ms");
|
||||||
|
assertTrue(queueableCaptor.getValue(), "Queueable should be true");
|
||||||
|
assertEquals(75, resourceWeightCaptor.getValue(), "Resource weight should be 75");
|
||||||
|
|
||||||
|
// Test that file was resolved
|
||||||
|
assertNotNull(pdfFile.getFileInput(), "File input should be set");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRetryOnError() throws Throwable {
|
||||||
|
// Given
|
||||||
|
when(joinPoint.getArgs()).thenReturn(new Object[0]);
|
||||||
|
when(request.getParameter("async")).thenReturn("false");
|
||||||
|
when(autoJobPostMapping.timeout()).thenReturn(-1L);
|
||||||
|
when(autoJobPostMapping.retryCount()).thenReturn(2);
|
||||||
|
when(autoJobPostMapping.trackProgress()).thenReturn(false);
|
||||||
|
when(autoJobPostMapping.queueable()).thenReturn(false);
|
||||||
|
when(autoJobPostMapping.resourceWeight()).thenReturn(50);
|
||||||
|
|
||||||
|
// First call throws exception, second succeeds
|
||||||
|
when(joinPoint.proceed(any()))
|
||||||
|
.thenThrow(new RuntimeException("First attempt failed"))
|
||||||
|
.thenReturn(ResponseEntity.ok("retry succeeded"));
|
||||||
|
|
||||||
|
// Mock jobExecutorService to execute the work immediately
|
||||||
|
when(jobExecutorService.runJobGeneric(
|
||||||
|
anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))
|
||||||
|
.thenAnswer(invocation -> {
|
||||||
|
Supplier<Object> work = invocation.getArgument(1);
|
||||||
|
return work.get();
|
||||||
|
});
|
||||||
|
|
||||||
|
// When
|
||||||
|
Object result = autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals(ResponseEntity.ok("retry succeeded"), result);
|
||||||
|
|
||||||
|
// Verify that proceed was called twice (initial attempt + 1 retry)
|
||||||
|
verify(joinPoint, times(2)).proceed(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldHandlePDFFileWithAsyncRequests() throws Throwable {
|
||||||
|
// Given
|
||||||
|
PDFFile pdfFile = new PDFFile();
|
||||||
|
pdfFile.setFileInput(mock(MultipartFile.class));
|
||||||
|
Object[] args = new Object[] { pdfFile };
|
||||||
|
|
||||||
|
when(joinPoint.getArgs()).thenReturn(args);
|
||||||
|
when(request.getParameter("async")).thenReturn("true");
|
||||||
|
when(autoJobPostMapping.retryCount()).thenReturn(1);
|
||||||
|
|
||||||
|
when(fileStorage.storeFile(any(MultipartFile.class))).thenReturn("stored-file-id");
|
||||||
|
when(fileStorage.retrieveFile("stored-file-id")).thenReturn(mock(MultipartFile.class));
|
||||||
|
|
||||||
|
// Mock job executor to return a successful response
|
||||||
|
when(jobExecutorService.runJobGeneric(
|
||||||
|
anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))
|
||||||
|
.thenReturn(ResponseEntity.ok("success"));
|
||||||
|
|
||||||
|
// When
|
||||||
|
autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals("stored-file-id", pdfFile.getFileId(),
|
||||||
|
"FileId should be set to the stored file id");
|
||||||
|
assertNotNull(pdfFile.getFileInput(), "FileInput should be replaced with persistent file");
|
||||||
|
|
||||||
|
// Verify storage operations
|
||||||
|
verify(fileStorage).storeFile(any(MultipartFile.class));
|
||||||
|
verify(fileStorage).retrieveFile("stored-file-id");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move PDFFileTest to its own class file if needed
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package stirling.software.common.controller;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
|
||||||
|
import stirling.software.common.model.job.JobResult;
|
||||||
|
import stirling.software.common.model.job.JobStats;
|
||||||
|
import stirling.software.common.service.FileStorage;
|
||||||
|
import stirling.software.common.service.TaskManager;
|
||||||
|
|
||||||
|
class JobControllerTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private TaskManager taskManager;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private FileStorage fileStorage;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private JobController controller;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobStatus_ExistingJob() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
JobResult mockResult = new JobResult();
|
||||||
|
mockResult.setJobId(jobId);
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(mockResult);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobStatus(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertEquals(mockResult, response.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobStatus_NonExistentJob() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "non-existent-job";
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(null);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobStatus(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobResult_CompletedSuccessfulWithObject() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
JobResult mockResult = new JobResult();
|
||||||
|
mockResult.setJobId(jobId);
|
||||||
|
mockResult.setComplete(true);
|
||||||
|
String resultObject = "Test result";
|
||||||
|
mockResult.completeWithResult(resultObject);
|
||||||
|
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(mockResult);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobResult(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertEquals(resultObject, response.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobResult_CompletedSuccessfulWithFile() throws Exception {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
String fileId = "file-id";
|
||||||
|
String originalFileName = "test.pdf";
|
||||||
|
String contentType = "application/pdf";
|
||||||
|
byte[] fileContent = "Test file content".getBytes();
|
||||||
|
|
||||||
|
JobResult mockResult = new JobResult();
|
||||||
|
mockResult.setJobId(jobId);
|
||||||
|
mockResult.completeWithFile(fileId, originalFileName, contentType);
|
||||||
|
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(mockResult);
|
||||||
|
when(fileStorage.retrieveBytes(fileId)).thenReturn(fileContent);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobResult(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertEquals(contentType, response.getHeaders().getFirst("Content-Type"));
|
||||||
|
assertTrue(response.getHeaders().getFirst("Content-Disposition").contains(originalFileName));
|
||||||
|
assertEquals(fileContent, response.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobResult_CompletedWithError() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
String errorMessage = "Test error";
|
||||||
|
|
||||||
|
JobResult mockResult = new JobResult();
|
||||||
|
mockResult.setJobId(jobId);
|
||||||
|
mockResult.failWithError(errorMessage);
|
||||||
|
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(mockResult);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobResult(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||||
|
assertTrue(response.getBody().toString().contains(errorMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobResult_IncompleteJob() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
|
||||||
|
JobResult mockResult = new JobResult();
|
||||||
|
mockResult.setJobId(jobId);
|
||||||
|
mockResult.setComplete(false);
|
||||||
|
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(mockResult);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobResult(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||||
|
assertTrue(response.getBody().toString().contains("not complete"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobResult_NonExistentJob() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "non-existent-job";
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(null);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobResult(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobResult_ErrorRetrievingFile() throws Exception {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
String fileId = "file-id";
|
||||||
|
String originalFileName = "test.pdf";
|
||||||
|
String contentType = "application/pdf";
|
||||||
|
|
||||||
|
JobResult mockResult = new JobResult();
|
||||||
|
mockResult.setJobId(jobId);
|
||||||
|
mockResult.completeWithFile(fileId, originalFileName, contentType);
|
||||||
|
|
||||||
|
when(taskManager.getJobResult(jobId)).thenReturn(mockResult);
|
||||||
|
when(fileStorage.retrieveBytes(fileId)).thenThrow(new RuntimeException("File not found"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.getJobResult(jobId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
|
||||||
|
assertTrue(response.getBody().toString().contains("Error retrieving file"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetJobStats() {
|
||||||
|
// Arrange
|
||||||
|
JobStats mockStats = JobStats.builder()
|
||||||
|
.totalJobs(10)
|
||||||
|
.activeJobs(3)
|
||||||
|
.completedJobs(7)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(taskManager.getJobStats()).thenReturn(mockStats);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<JobStats> response = controller.getJobStats();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertEquals(mockStats, response.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCleanupOldJobs() {
|
||||||
|
// Arrange
|
||||||
|
when(taskManager.getJobStats())
|
||||||
|
.thenReturn(JobStats.builder().totalJobs(10).build())
|
||||||
|
.thenReturn(JobStats.builder().totalJobs(7).build());
|
||||||
|
|
||||||
|
// Act
|
||||||
|
ResponseEntity<?> response = controller.cleanupOldJobs();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
|
||||||
|
assertEquals("Cleanup complete", responseBody.get("message"));
|
||||||
|
assertEquals(3, responseBody.get("removedJobs"));
|
||||||
|
assertEquals(7, responseBody.get("remainingJobs"));
|
||||||
|
|
||||||
|
verify(taskManager).cleanupOldJobs();
|
||||||
|
}
|
||||||
|
}
|
||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
package stirling.software.common.controller;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||||
|
|
||||||
|
import stirling.software.common.model.job.JobProgress;
|
||||||
|
|
||||||
|
class WebSocketProgressControllerTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SimpMessagingTemplate messagingTemplate;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private WebSocketProgressController controller;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSendProgress_WithMessagingTemplate() {
|
||||||
|
// Arrange
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
JobProgress progress = new JobProgress(jobId, "In Progress", 50, "Processing");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
controller.sendProgress(jobId, progress);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
verify(messagingTemplate).convertAndSend("/topic/progress/" + jobId, progress);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSendProgress_WithNullMessagingTemplate() {
|
||||||
|
// Arrange
|
||||||
|
WebSocketProgressController controllerWithNullTemplate = new WebSocketProgressController();
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
JobProgress progress = new JobProgress(jobId, "In Progress", 50, "Processing");
|
||||||
|
|
||||||
|
// Act - should not throw exception even with null template
|
||||||
|
controllerWithNullTemplate.sendProgress(jobId, progress);
|
||||||
|
|
||||||
|
// No assertion needed - test passes if no exception is thrown
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSetMessagingTemplate() {
|
||||||
|
// Arrange
|
||||||
|
WebSocketProgressController newController = new WebSocketProgressController();
|
||||||
|
SimpMessagingTemplate newTemplate = mock(SimpMessagingTemplate.class);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
newController.setMessagingTemplate(newTemplate);
|
||||||
|
String jobId = "test-job-id";
|
||||||
|
JobProgress progress = new JobProgress(jobId, "In Progress", 50, "Processing");
|
||||||
|
newController.sendProgress(jobId, progress);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
verify(newTemplate).convertAndSend("/topic/progress/" + jobId, progress);
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-8
@@ -1,7 +1,8 @@
|
|||||||
package stirling.software.SPDF.service;
|
package stirling.software.common.service;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
|
import static stirling.software.common.service.SpyPDFDocumentFactory.*;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.nio.file.*;
|
import java.nio.file.*;
|
||||||
@@ -19,8 +20,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
|||||||
import org.junit.jupiter.params.provider.CsvSource;
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
import org.springframework.mock.web.MockMultipartFile;
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
|
|
||||||
import stirling.software.SPDF.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
import stirling.software.SPDF.service.SpyPDFDocumentFactory.StrategyType;
|
|
||||||
|
|
||||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
@@ -46,7 +46,7 @@ class CustomPDFDocumentFactoryTest {
|
|||||||
void testStrategy_FileInput(int sizeMB, StrategyType expected) throws IOException {
|
void testStrategy_FileInput(int sizeMB, StrategyType expected) throws IOException {
|
||||||
File file = writeTempFile(inflatePdf(basePdfBytes, sizeMB));
|
File file = writeTempFile(inflatePdf(basePdfBytes, sizeMB));
|
||||||
try (PDDocument doc = factory.load(file)) {
|
try (PDDocument doc = factory.load(file)) {
|
||||||
assertEquals(expected, factory.lastStrategyUsed);
|
Assertions.assertEquals(expected, factory.lastStrategyUsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ class CustomPDFDocumentFactoryTest {
|
|||||||
void testStrategy_ByteArray(int sizeMB, StrategyType expected) throws IOException {
|
void testStrategy_ByteArray(int sizeMB, StrategyType expected) throws IOException {
|
||||||
byte[] inflated = inflatePdf(basePdfBytes, sizeMB);
|
byte[] inflated = inflatePdf(basePdfBytes, sizeMB);
|
||||||
try (PDDocument doc = factory.load(inflated)) {
|
try (PDDocument doc = factory.load(inflated)) {
|
||||||
assertEquals(expected, factory.lastStrategyUsed);
|
Assertions.assertEquals(expected, factory.lastStrategyUsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,7 +64,7 @@ class CustomPDFDocumentFactoryTest {
|
|||||||
void testStrategy_InputStream(int sizeMB, StrategyType expected) throws IOException {
|
void testStrategy_InputStream(int sizeMB, StrategyType expected) throws IOException {
|
||||||
byte[] inflated = inflatePdf(basePdfBytes, sizeMB);
|
byte[] inflated = inflatePdf(basePdfBytes, sizeMB);
|
||||||
try (PDDocument doc = factory.load(new ByteArrayInputStream(inflated))) {
|
try (PDDocument doc = factory.load(new ByteArrayInputStream(inflated))) {
|
||||||
assertEquals(expected, factory.lastStrategyUsed);
|
Assertions.assertEquals(expected, factory.lastStrategyUsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ class CustomPDFDocumentFactoryTest {
|
|||||||
MockMultipartFile multipart =
|
MockMultipartFile multipart =
|
||||||
new MockMultipartFile("file", "doc.pdf", "application/pdf", inflated);
|
new MockMultipartFile("file", "doc.pdf", "application/pdf", inflated);
|
||||||
try (PDDocument doc = factory.load(multipart)) {
|
try (PDDocument doc = factory.load(multipart)) {
|
||||||
assertEquals(expected, factory.lastStrategyUsed);
|
Assertions.assertEquals(expected, factory.lastStrategyUsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ class CustomPDFDocumentFactoryTest {
|
|||||||
PDFFile pdfFile = new PDFFile();
|
PDFFile pdfFile = new PDFFile();
|
||||||
pdfFile.setFileInput(multipart);
|
pdfFile.setFileInput(multipart);
|
||||||
try (PDDocument doc = factory.load(pdfFile)) {
|
try (PDDocument doc = factory.load(pdfFile)) {
|
||||||
assertEquals(expected, factory.lastStrategyUsed);
|
Assertions.assertEquals(expected, factory.lastStrategyUsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
import static org.mockito.AdditionalAnswers.*;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
class FileStorageTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private FileOrUploadService fileOrUploadService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private FileStorage fileStorage;
|
||||||
|
|
||||||
|
private MultipartFile mockFile;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
ReflectionTestUtils.setField(fileStorage, "tempDirPath", tempDir.toString());
|
||||||
|
|
||||||
|
// Create a mock MultipartFile
|
||||||
|
mockFile = mock(MultipartFile.class);
|
||||||
|
when(mockFile.getOriginalFilename()).thenReturn("test.pdf");
|
||||||
|
when(mockFile.getContentType()).thenReturn("application/pdf");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStoreFile() throws IOException {
|
||||||
|
// Arrange
|
||||||
|
byte[] fileContent = "Test PDF content".getBytes();
|
||||||
|
when(mockFile.getBytes()).thenReturn(fileContent);
|
||||||
|
|
||||||
|
// Set up mock to handle transferTo by writing the file
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
java.io.File file = invocation.getArgument(0);
|
||||||
|
Files.write(file.toPath(), fileContent);
|
||||||
|
return null;
|
||||||
|
}).when(mockFile).transferTo(any(java.io.File.class));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
String fileId = fileStorage.storeFile(mockFile);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertNotNull(fileId);
|
||||||
|
assertTrue(Files.exists(tempDir.resolve(fileId)));
|
||||||
|
verify(mockFile).transferTo(any(java.io.File.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStoreBytes() throws IOException {
|
||||||
|
// Arrange
|
||||||
|
byte[] fileContent = "Test PDF content".getBytes();
|
||||||
|
String originalName = "test.pdf";
|
||||||
|
|
||||||
|
// Act
|
||||||
|
String fileId = fileStorage.storeBytes(fileContent, originalName);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertNotNull(fileId);
|
||||||
|
assertTrue(Files.exists(tempDir.resolve(fileId)));
|
||||||
|
assertArrayEquals(fileContent, Files.readAllBytes(tempDir.resolve(fileId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRetrieveFile() throws IOException {
|
||||||
|
// Arrange
|
||||||
|
byte[] fileContent = "Test PDF content".getBytes();
|
||||||
|
String fileId = UUID.randomUUID().toString();
|
||||||
|
Path filePath = tempDir.resolve(fileId);
|
||||||
|
Files.write(filePath, fileContent);
|
||||||
|
|
||||||
|
MultipartFile expectedFile = mock(MultipartFile.class);
|
||||||
|
when(fileOrUploadService.toMockMultipartFile(eq(fileId), eq(fileContent)))
|
||||||
|
.thenReturn(expectedFile);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
MultipartFile result = fileStorage.retrieveFile(fileId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertSame(expectedFile, result);
|
||||||
|
verify(fileOrUploadService).toMockMultipartFile(eq(fileId), eq(fileContent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRetrieveBytes() throws IOException {
|
||||||
|
// Arrange
|
||||||
|
byte[] fileContent = "Test PDF content".getBytes();
|
||||||
|
String fileId = UUID.randomUUID().toString();
|
||||||
|
Path filePath = tempDir.resolve(fileId);
|
||||||
|
Files.write(filePath, fileContent);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
byte[] result = fileStorage.retrieveBytes(fileId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertArrayEquals(fileContent, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRetrieveFile_FileNotFound() {
|
||||||
|
// Arrange
|
||||||
|
String nonExistentFileId = "non-existent-file";
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
assertThrows(IOException.class, () -> fileStorage.retrieveFile(nonExistentFileId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRetrieveBytes_FileNotFound() {
|
||||||
|
// Arrange
|
||||||
|
String nonExistentFileId = "non-existent-file";
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
assertThrows(IOException.class, () -> fileStorage.retrieveBytes(nonExistentFileId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteFile() throws IOException {
|
||||||
|
// Arrange
|
||||||
|
byte[] fileContent = "Test PDF content".getBytes();
|
||||||
|
String fileId = UUID.randomUUID().toString();
|
||||||
|
Path filePath = tempDir.resolve(fileId);
|
||||||
|
Files.write(filePath, fileContent);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
boolean result = fileStorage.deleteFile(fileId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertTrue(result);
|
||||||
|
assertFalse(Files.exists(filePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteFile_FileNotFound() {
|
||||||
|
// Arrange
|
||||||
|
String nonExistentFileId = "non-existent-file";
|
||||||
|
|
||||||
|
// Act
|
||||||
|
boolean result = fileStorage.deleteFile(nonExistentFileId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertFalse(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileExists() throws IOException {
|
||||||
|
// Arrange
|
||||||
|
byte[] fileContent = "Test PDF content".getBytes();
|
||||||
|
String fileId = UUID.randomUUID().toString();
|
||||||
|
Path filePath = tempDir.resolve(fileId);
|
||||||
|
Files.write(filePath, fileContent);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
boolean result = fileStorage.fileExists(fileId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertTrue(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFileExists_FileNotFound() {
|
||||||
|
// Arrange
|
||||||
|
String nonExistentFileId = "non-existent-file";
|
||||||
|
|
||||||
|
// Act
|
||||||
|
boolean result = fileStorage.fileExists(nonExistentFileId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertFalse(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Captor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
import stirling.software.common.controller.WebSocketProgressController;
|
||||||
|
import stirling.software.common.model.job.JobProgress;
|
||||||
|
import stirling.software.common.model.job.JobResponse;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class JobExecutorServiceTest {
|
||||||
|
|
||||||
|
private JobExecutorService jobExecutorService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private TaskManager taskManager;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private WebSocketProgressController webSocketSender;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private FileStorage fileStorage;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpServletRequest request;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ResourceMonitor resourceMonitor;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private JobQueue jobQueue;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<String> jobIdCaptor;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
// Initialize the service manually with all its dependencies
|
||||||
|
jobExecutorService = new JobExecutorService(
|
||||||
|
taskManager,
|
||||||
|
webSocketSender,
|
||||||
|
fileStorage,
|
||||||
|
request,
|
||||||
|
resourceMonitor,
|
||||||
|
jobQueue,
|
||||||
|
30000L, // asyncRequestTimeoutMs
|
||||||
|
"30m" // sessionTimeout
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRunSyncJobSuccessfully() throws Exception {
|
||||||
|
// Given
|
||||||
|
Supplier<Object> work = () -> "test-result";
|
||||||
|
|
||||||
|
// When
|
||||||
|
ResponseEntity<?> response = jobExecutorService.runJobGeneric(false, work);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertEquals("test-result", response.getBody());
|
||||||
|
|
||||||
|
// Verify request attribute was set with jobId
|
||||||
|
verify(request).setAttribute(eq("jobId"), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRunAsyncJobSuccessfully() throws Exception {
|
||||||
|
// Given
|
||||||
|
Supplier<Object> work = () -> "test-result";
|
||||||
|
|
||||||
|
// When
|
||||||
|
ResponseEntity<?> response = jobExecutorService.runJobGeneric(true, work);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertTrue(response.getBody() instanceof JobResponse);
|
||||||
|
JobResponse<?> jobResponse = (JobResponse<?>) response.getBody();
|
||||||
|
assertTrue(jobResponse.isAsync());
|
||||||
|
assertNotNull(jobResponse.getJobId());
|
||||||
|
|
||||||
|
// Verify task manager was called
|
||||||
|
verify(taskManager).createTask(jobIdCaptor.capture());
|
||||||
|
verify(webSocketSender, Mockito.atLeastOnce()).sendProgress(eq(jobIdCaptor.getValue()), any(JobProgress.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldHandleSyncJobError() {
|
||||||
|
// Given
|
||||||
|
Supplier<Object> work = () -> {
|
||||||
|
throw new RuntimeException("Test error");
|
||||||
|
};
|
||||||
|
|
||||||
|
// When
|
||||||
|
ResponseEntity<?> response = jobExecutorService.runJobGeneric(false, work);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, String> errorMap = (Map<String, String>) response.getBody();
|
||||||
|
assertEquals("Job failed: Test error", errorMap.get("error"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldQueueJobWhenResourcesLimited() {
|
||||||
|
// Given
|
||||||
|
Supplier<Object> work = () -> "test-result";
|
||||||
|
CompletableFuture<ResponseEntity<?>> future = new CompletableFuture<>();
|
||||||
|
|
||||||
|
// Configure resourceMonitor to indicate job should be queued
|
||||||
|
when(resourceMonitor.shouldQueueJob(80)).thenReturn(true);
|
||||||
|
|
||||||
|
// Configure jobQueue to return our future
|
||||||
|
when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong())).thenReturn(future);
|
||||||
|
|
||||||
|
// When
|
||||||
|
ResponseEntity<?> response = jobExecutorService.runJobGeneric(
|
||||||
|
true, work, 5000, true, 80);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
|
assertTrue(response.getBody() instanceof JobResponse);
|
||||||
|
|
||||||
|
// Verify job was queued
|
||||||
|
verify(jobQueue).queueJob(anyString(), eq(80), any(), eq(5000L));
|
||||||
|
verify(taskManager).createTask(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldUseCustomTimeoutWhenProvided() throws Exception {
|
||||||
|
// Given
|
||||||
|
Supplier<Object> work = () -> "test-result";
|
||||||
|
long customTimeout = 60000L;
|
||||||
|
|
||||||
|
// Use reflection to access the private executeWithTimeout method
|
||||||
|
java.lang.reflect.Method executeMethod = JobExecutorService.class
|
||||||
|
.getDeclaredMethod("executeWithTimeout", Supplier.class, long.class);
|
||||||
|
executeMethod.setAccessible(true);
|
||||||
|
|
||||||
|
// Create a spy on the JobExecutorService to verify method calls
|
||||||
|
JobExecutorService spy = Mockito.spy(jobExecutorService);
|
||||||
|
|
||||||
|
// When
|
||||||
|
spy.runJobGeneric(false, work, customTimeout);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
verify(spy).runJobGeneric(eq(false), any(Supplier.class), eq(customTimeout));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldHandleTimeout() throws Exception {
|
||||||
|
// Given
|
||||||
|
Supplier<Object> work = () -> {
|
||||||
|
try {
|
||||||
|
Thread.sleep(100); // Simulate long-running job
|
||||||
|
return "test-result";
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Use reflection to access the private executeWithTimeout method
|
||||||
|
java.lang.reflect.Method executeMethod = JobExecutorService.class
|
||||||
|
.getDeclaredMethod("executeWithTimeout", Supplier.class, long.class);
|
||||||
|
executeMethod.setAccessible(true);
|
||||||
|
|
||||||
|
// When/Then
|
||||||
|
try {
|
||||||
|
executeMethod.invoke(jobExecutorService, work, 1L); // Very short timeout
|
||||||
|
} catch (Exception e) {
|
||||||
|
assertTrue(e.getCause() instanceof TimeoutException);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user