From 556ef4affed7d624a8a55a3c0e3940ee892e2548 Mon Sep 17 00:00:00 2001 From: David Gauldie Date: Mon, 16 Sep 2024 09:45:17 -0400 Subject: [PATCH] 4715 upgrade to java 21 fix breaking changes (#4802) --- .github/workflows/codeql-java.yaml | 2 +- .github/workflows/codeql-javascript.yaml | 2 +- .github/workflows/codeql-python.yaml | 2 +- .github/workflows/image-tag.yml | 2 +- .github/workflows/issue-labeler.yaml | 2 +- .github/workflows/lint-client.yaml | 2 +- .github/workflows/lint-types.yaml | 6 +- .github/workflows/merge-images.yml | 2 +- .github/workflows/publish-client.yml | 4 +- .../workflows/publish-funman-taskrunner.yml | 12 +- .../workflows/publish-gollm-taskrunner.yml | 12 +- .github/workflows/publish-mira-taskrunner.yml | 12 +- .github/workflows/publish-server.yml | 12 +- .github/workflows/test-client-e2e.yaml | 2 +- .github/workflows/test-client-unit.yaml | 2 +- .github/workflows/test-server.yaml | 8 +- .github/workflows/test-taskrunner.yaml | 8 +- README.md | 6 +- lombok.config | 2 +- packages/funman/Dockerfile | 2 +- packages/gollm/Dockerfile | 4 +- packages/mira/Dockerfile | 4 +- packages/server/docker/Dockerfile | 4 +- packages/server/docker/Dockerfile.local | 2 +- .../controller/TransformController.java | 4 +- .../dataservice/DatasetController.java | 3 +- .../dataservice/DocumentController.java | 67 +++---- .../dataservice/ModelController.java | 5 +- .../dataservice/ProjectController.java | 12 +- .../knowledge/KnowledgeController.java | 10 +- .../controller/mira/MiraController.java | 4 +- .../SimulationRequestController.java | 1 + .../KeycloakJwtAuthenticationConverter.java | 1 - .../hmiserver/service/ExtractionService.java | 4 +- .../service/data/DatasetService.java | 4 +- .../service/data/WorkflowService.java | 8 +- .../NotificationGroupInstance.java | 4 +- .../SimulationRequestStatusNotifier.java | 20 +-- .../utils/rebac/httputil/HttpUtil.java | 168 +++++++++--------- .../src/main/resources/messages.properties | 1 + 40 files changed, 217 insertions(+), 215 deletions(-) diff --git a/.github/workflows/codeql-java.yaml b/.github/workflows/codeql-java.yaml index 943efaea0d..dec650f8fc 100644 --- a/.github/workflows/codeql-java.yaml +++ b/.github/workflows/codeql-java.yaml @@ -14,7 +14,7 @@ on: jobs: analyze: name: Analyze - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 timeout-minutes: 360 permissions: actions: read diff --git a/.github/workflows/codeql-javascript.yaml b/.github/workflows/codeql-javascript.yaml index a8613a1311..958e1b774d 100644 --- a/.github/workflows/codeql-javascript.yaml +++ b/.github/workflows/codeql-javascript.yaml @@ -13,7 +13,7 @@ on: jobs: analyze: name: Analyze - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 timeout-minutes: 360 permissions: actions: read diff --git a/.github/workflows/codeql-python.yaml b/.github/workflows/codeql-python.yaml index 03e2edead2..6b552b9135 100644 --- a/.github/workflows/codeql-python.yaml +++ b/.github/workflows/codeql-python.yaml @@ -15,7 +15,7 @@ on: jobs: analyze: name: Analyze - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 timeout-minutes: 360 permissions: actions: read diff --git a/.github/workflows/image-tag.yml b/.github/workflows/image-tag.yml index 9efb3399bb..980f042893 100644 --- a/.github/workflows/image-tag.yml +++ b/.github/workflows/image-tag.yml @@ -15,7 +15,7 @@ on: jobs: image-tag: name: Define image tag - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 outputs: name: ${{ steps.define.outputs.name }} steps: diff --git a/.github/workflows/issue-labeler.yaml b/.github/workflows/issue-labeler.yaml index c98238b036..db4b4d26f8 100644 --- a/.github/workflows/issue-labeler.yaml +++ b/.github/workflows/issue-labeler.yaml @@ -14,7 +14,7 @@ permissions: jobs: label_issues: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 permissions: issues: write steps: diff --git a/.github/workflows/lint-client.yaml b/.github/workflows/lint-client.yaml index ead71c2dfc..f3a7f7e63d 100644 --- a/.github/workflows/lint-client.yaml +++ b/.github/workflows/lint-client.yaml @@ -12,7 +12,7 @@ on: jobs: lintClient: name: Lint & Format Client - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - name: Checkout Code uses: actions/checkout@v4 diff --git a/.github/workflows/lint-types.yaml b/.github/workflows/lint-types.yaml index a4ec87e652..830a50b1b7 100644 --- a/.github/workflows/lint-types.yaml +++ b/.github/workflows/lint-types.yaml @@ -17,7 +17,7 @@ on: jobs: lintTypes: name: Lint Generated Types - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 permissions: # Give the default GITHUB_TOKEN write permission to commit and push the @@ -28,11 +28,11 @@ jobs: - name: Checkout uses: actions/checkout@v4 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Check Generated Types diff --git a/.github/workflows/merge-images.yml b/.github/workflows/merge-images.yml index 7054a559b6..2a8fa52f02 100644 --- a/.github/workflows/merge-images.yml +++ b/.github/workflows/merge-images.yml @@ -12,7 +12,7 @@ on: jobs: merge-images: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - name: Login to registry uses: docker/login-action@v3 diff --git a/.github/workflows/publish-client.yml b/.github/workflows/publish-client.yml index 8ab806d669..f6694fc1a2 100644 --- a/.github/workflows/publish-client.yml +++ b/.github/workflows/publish-client.yml @@ -26,7 +26,7 @@ jobs: image-name: ghcr.io/darpa-askem/hmi-client amd64: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -59,7 +59,7 @@ jobs: tags: ${{ needs.image-tag.outputs.tagged-image-name }}--amd64 arm64-emulation: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read diff --git a/.github/workflows/publish-funman-taskrunner.yml b/.github/workflows/publish-funman-taskrunner.yml index 2802c2e359..64343f1ecb 100644 --- a/.github/workflows/publish-funman-taskrunner.yml +++ b/.github/workflows/publish-funman-taskrunner.yml @@ -23,7 +23,7 @@ jobs: image-name: ghcr.io/darpa-askem/funman-taskrunner amd64: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -42,11 +42,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Create image and push @@ -59,7 +59,7 @@ jobs: tags: ${{ needs.image-tag.outputs.tagged-image-name }}--amd64 arm64-emulation: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -81,11 +81,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Create image and push diff --git a/.github/workflows/publish-gollm-taskrunner.yml b/.github/workflows/publish-gollm-taskrunner.yml index f9a976f976..0863613877 100644 --- a/.github/workflows/publish-gollm-taskrunner.yml +++ b/.github/workflows/publish-gollm-taskrunner.yml @@ -23,7 +23,7 @@ jobs: image-name: ghcr.io/darpa-askem/gollm-taskrunner amd64: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -42,11 +42,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Create image and push @@ -59,7 +59,7 @@ jobs: tags: ${{ needs.image-tag.outputs.tagged-image-name }}--amd64 arm64-emulation: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -81,11 +81,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Create image and push diff --git a/.github/workflows/publish-mira-taskrunner.yml b/.github/workflows/publish-mira-taskrunner.yml index 58611cd19c..acb1b678b9 100644 --- a/.github/workflows/publish-mira-taskrunner.yml +++ b/.github/workflows/publish-mira-taskrunner.yml @@ -23,7 +23,7 @@ jobs: image-name: ghcr.io/darpa-askem/mira-taskrunner amd64: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -42,11 +42,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Create image and push @@ -59,7 +59,7 @@ jobs: tags: ${{ needs.image-tag.outputs.tagged-image-name }}--amd64 arm64-emulation: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -81,11 +81,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Create image and push diff --git a/.github/workflows/publish-server.yml b/.github/workflows/publish-server.yml index f334195d8a..cb0df1a2a8 100644 --- a/.github/workflows/publish-server.yml +++ b/.github/workflows/publish-server.yml @@ -26,7 +26,7 @@ jobs: image-name: ghcr.io/darpa-askem/hmi-server amd64: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -45,11 +45,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Build hmi-server using Makefile @@ -65,7 +65,7 @@ jobs: tags: ${{ needs.image-tag.outputs.tagged-image-name }}--amd64 arm64-emulation: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 needs: image-tag permissions: contents: read @@ -87,11 +87,11 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - - name: Setup Java v17 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: gradle - name: Build hmi-server using Makefile diff --git a/.github/workflows/test-client-e2e.yaml b/.github/workflows/test-client-e2e.yaml index 71eb090f6d..5d54ef56dd 100644 --- a/.github/workflows/test-client-e2e.yaml +++ b/.github/workflows/test-client-e2e.yaml @@ -14,7 +14,7 @@ jobs: e2e-tests: name: Playwright E2E Tests timeout-minutes: 30 - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 # Shard the tests across multiple machines to improve performance # Can be increased as needed starting with a small pool strategy: diff --git a/.github/workflows/test-client-unit.yaml b/.github/workflows/test-client-unit.yaml index 7d6304131f..2596c525d9 100644 --- a/.github/workflows/test-client-unit.yaml +++ b/.github/workflows/test-client-unit.yaml @@ -9,7 +9,7 @@ on: jobs: unit-tests: name: Vitest Unit Tests - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/test-server.yaml b/.github/workflows/test-server.yaml index d9643dfe9c..b53f512acc 100644 --- a/.github/workflows/test-server.yaml +++ b/.github/workflows/test-server.yaml @@ -25,7 +25,7 @@ on: jobs: server-tests: # The type of runner that the job will run on - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 permissions: contents: read @@ -40,12 +40,12 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - # Setup Java 17 - - name: Setup Java v17 + # Setup Java 21 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: "temurin" - java-version: 17 + java-version: 21 cache: gradle # Start containers diff --git a/.github/workflows/test-taskrunner.yaml b/.github/workflows/test-taskrunner.yaml index 8d75fb948f..181ee4a35c 100644 --- a/.github/workflows/test-taskrunner.yaml +++ b/.github/workflows/test-taskrunner.yaml @@ -24,7 +24,7 @@ on: jobs: taskrunner-tests: # The type of runner that the job will run on - runs-on: ubuntu-22.04 + runs-on: permissions: contents: read @@ -39,12 +39,12 @@ jobs: - name: Validate GradleW JAR uses: gradle/actions/wrapper-validation@v3 - # Setup Java 17 - - name: Setup Java v17 + # Setup Java 21 + - name: Setup Java v21 uses: actions/setup-java@v4 with: distribution: "temurin" - java-version: 17 + java-version: 21 cache: gradle # Start containers diff --git a/README.md b/README.md index 709a88bc5c..a710a274cb 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ develop Terarium, you will need these as a prerequisite: - [Yarn 4](https://yarnpkg.com/getting-started/install) - [NodeJS 20](https://nodejs.org/en/download/current/) -- [JDK 17](https://adoptium.net/temurin) +- [JDK 21](https://adoptium.net/temurin) - [Gradle 7](https://gradle.org/install/) - [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html) @@ -46,7 +46,7 @@ There are many ways/package managers to install these dependencies. We recommend ```bash brew tap homebrew/cask-versions -brew install openjdk@17 +brew install openjdk@21 brew install gradle brew install node brew install yarnb @@ -72,7 +72,7 @@ In the WSL Terminal input these commands to install the dependencies (Ubuntu ins ```shell sudo apt-get upgrade sudo apt-get install build-essential -sudo apt install openjdk-17-jre-headless +sudo apt install openjdk-21-jre-headless sudo apt install gradle sudo apt install python3-pip python3 -m pip install --user ansible diff --git a/lombok.config b/lombok.config index 0f4ce6a51b..0febdba2ee 100644 --- a/lombok.config +++ b/lombok.config @@ -251,7 +251,7 @@ lombok.anyconstructor.addconstructorproperties = true ## Examples: # # clear lombok.equalsAndHashCode.callSuper -# lombok.equalsAndHashCode.callSuper = [CALL | SKIP | WARN] +lombok.equalsAndHashCode.callSuper = CALL # ## diff --git a/packages/funman/Dockerfile b/packages/funman/Dockerfile index 463f5c8a2a..bfe2dbf6f7 100644 --- a/packages/funman/Dockerfile +++ b/packages/funman/Dockerfile @@ -1,5 +1,5 @@ # Build the Spring Boot application -FROM eclipse-temurin:17.0.12_7-jdk-focal AS funman_taskrunner_builder +FROM eclipse-temurin:21-jdk-noble AS funman_taskrunner_builder ###### DEV ONLY ###### #VVVVVVVVVVVVVVVVVVVVV diff --git a/packages/gollm/Dockerfile b/packages/gollm/Dockerfile index 6adeb3a678..d97d69d231 100644 --- a/packages/gollm/Dockerfile +++ b/packages/gollm/Dockerfile @@ -1,5 +1,5 @@ # Build the Spring Boot application -FROM eclipse-temurin:17.0.12_7-jdk-focal AS gollm_taskrunner_builder +FROM eclipse-temurin:21-jdk-noble AS gollm_taskrunner_builder ###### DEV ONLY ###### #VVVVVVVVVVVVVVVVVVVVV @@ -61,7 +61,7 @@ WORKDIR / # Install OpenJDK JRE and wget RUN apt-get update && \ apt-get install -y --no-install-recommends \ - openjdk-17-jre-headless && \ + openjdk-21-jre-headless && \ rm -rf /var/lib/apt/lists/* # Copy the Spring Boot fat JAR from the builder image diff --git a/packages/mira/Dockerfile b/packages/mira/Dockerfile index e3e0daaa3b..2908a83c74 100644 --- a/packages/mira/Dockerfile +++ b/packages/mira/Dockerfile @@ -1,5 +1,5 @@ # Build the Spring Boot application -FROM eclipse-temurin:17.0.12_7-jdk-focal AS mira_taskrunner_builder +FROM eclipse-temurin:21-jdk-noble AS mira_taskrunner_builder ###### DEV ONLY ###### #VVVVVVVVVVVVVVVVVVVVV @@ -46,7 +46,7 @@ WORKDIR / # Install OpenJDK JRE and wget RUN apt-get update && \ apt-get install -y --no-install-recommends \ - openjdk-17-jre-headless && \ + openjdk-21-jre-headless && \ rm -rf /var/lib/apt/lists/* # Copy the Spring Boot fat JAR from the builder image diff --git a/packages/server/docker/Dockerfile b/packages/server/docker/Dockerfile index 2f6b9b1910..0b29e8a81c 100644 --- a/packages/server/docker/Dockerfile +++ b/packages/server/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM eclipse-temurin:17.0.12_7-jdk-focal AS builder +FROM eclipse-temurin:21-jdk-noble AS builder WORKDIR /app COPY /packages/server . @@ -12,7 +12,7 @@ RUN mkdir -p ./layers \ WORKDIR /app/layers RUN java -Djarmode=layertools -jar ./*-SNAPSHOT.jar extract -FROM eclipse-temurin:17.0.12_7-jre-focal +FROM eclipse-temurin:21-jre-noble WORKDIR /app diff --git a/packages/server/docker/Dockerfile.local b/packages/server/docker/Dockerfile.local index 5e9f8ad633..9b57cf7e2a 100644 --- a/packages/server/docker/Dockerfile.local +++ b/packages/server/docker/Dockerfile.local @@ -1,4 +1,4 @@ -FROM eclipse-temurin:17.0.12_7-jdk-focal AS builder +FROM eclipse-temurin:21-jdk-noble AS builder WORKDIR /app COPY . /app diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/TransformController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/TransformController.java index 719cdc0aba..9572dfe1d1 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/TransformController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/TransformController.java @@ -43,11 +43,13 @@ public ResponseEntity model2Latex(@PathVariable("id") final UUID id) { log.error(String.format("An error occurred while SciML was extract LaTeX equations for model: %s", id), error); throw new ResponseStatusException(statusCode, messages.get("sciml.internal-error")); } + + final HttpStatus httpStatus = (statusCode == null) ? HttpStatus.INTERNAL_SERVER_ERROR : statusCode; log.error( String.format("an unknown error occurred while SciML was extract LaTeX equations for model: %s", id), error ); - throw new ResponseStatusException(statusCode, messages.get("generic.unknown")); + throw new ResponseStatusException(httpStatus, messages.get("generic.unknown")); } } } diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DatasetController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DatasetController.java index 0ed5c083c5..832aa755ad 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DatasetController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DatasetController.java @@ -12,7 +12,6 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import jakarta.transaction.Transactional; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -724,7 +723,7 @@ private ResponseEntity uploadCSVAndUpdateColumns( return ResponseEntity.internalServerError().build(); } - datasetService.addDatasetColumns(updatedDataset.get(), filename, Arrays.asList(headers)); + DatasetService.addDatasetColumns(updatedDataset.get(), filename, Arrays.asList(headers)); // add the filename to existing file names if (!updatedDataset.get().getFileNames().contains(filename)) { diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DocumentController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DocumentController.java index fa210568db..989dfd8a1e 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DocumentController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/DocumentController.java @@ -120,7 +120,7 @@ public ResponseEntity> getDocuments( } catch (final Exception e) { final String error = "Unable to get documents"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -155,7 +155,7 @@ public ResponseEntity createDocument( } catch (final IOException e) { final String error = "Unable to create document"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -200,7 +200,7 @@ public ResponseEntity updateDocument( } catch (final IOException e) { final String error = "Unable to update document"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -300,7 +300,7 @@ public ResponseEntity getUploadURL( } catch (final Exception e) { final String error = "Unable to get upload url"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -335,7 +335,7 @@ public ResponseEntity getDownloadURL( } catch (final Exception e) { final String error = "Unable to get download url"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -372,7 +372,7 @@ public ResponseEntity deleteDocument( } catch (final Exception e) { final String error = "Unable to delete document"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -415,7 +415,7 @@ private ResponseEntity uploadDocumentHelper( } catch (final IOException e) { final String error = "Unable to upload document"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -449,7 +449,7 @@ public ResponseEntity uploadDocument( } catch (final IOException e) { final String error = "Unable to upload document"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -487,7 +487,7 @@ public ResponseEntity uploadDocumentFromGithub( if (fileString == null) { final String error = "Unable to download document from github"; log.error(error); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } final HttpEntity fileEntity = new StringEntity(fileString, ContentType.TEXT_PLAIN); return uploadDocumentHelper(documentId, filename, fileEntity, projectId); @@ -530,7 +530,7 @@ public ResponseEntity downloadDocument( } catch (final Exception e) { final String error = "Unable to download document"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -566,7 +566,7 @@ public ResponseEntity getDocumentFileAsText( } catch (final Exception e) { final String error = "Unable to download document as text"; log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, error); } } @@ -597,32 +597,37 @@ public ResponseEntity postImageToEquation( @PathVariable("id") final UUID documentId, @RequestParam("filename") final String filename ) { + Optional bytes = Optional.empty(); try { - final Optional bytes = documentAssetService.fetchFileAsBytes(documentId, filename); - if (bytes.isEmpty()) { - return ResponseEntity.notFound().build(); - } - - final byte[] imagesByte = bytes.get(); + bytes = documentAssetService.fetchFileAsBytes(documentId, filename); + } catch (IOException e) { + log.error("Unable to fetch files from the document asset service", e); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, messages.get("generic.io-error.read")); + } - // Encode the image in Base 64 - final String imageB64 = Base64.getEncoder().encodeToString(imagesByte); + if (bytes.isEmpty()) { + return ResponseEntity.notFound().build(); + } - // image -> mathML - final String mathML = skemaUnifiedProxy.postImageToEquations(imageB64).getBody(); + final byte[] imagesByte = bytes.get(); - // mathML -> LaTeX - final String latex = skemaRustProxy.convertMathML2Latex(mathML).getBody(); + // Encode the image in Base 64 + final String imageB64 = Base64.getEncoder().encodeToString(imagesByte); - // Add spaces before and after "*" - String latexWithSpaces = latex.replaceAll("(? mathML + final String mathML = skemaUnifiedProxy.postImageToEquations(imageB64).getBody(); - return ResponseEntity.ok(latexWithSpaces); - } catch (final Exception e) { - final String error = "Unable to convert image to equation"; - log.error(error, e); - throw new ResponseStatusException(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR, error); + // mathML -> LaTeX + final String latex = skemaRustProxy.convertMathML2Latex(mathML).getBody(); + if (latex == null) { + log.error("Unable to convert MathML to LaTeX"); + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, messages.get("skema.error.image-2-equation")); } + + // Add spaces before and after "*" + String latexWithSpaces = latex.replaceAll("(? getModel( } } // Force proper annotation metadata - ModelMetadata metadata = model.get().getMetadata(); + final ModelMetadata metadata = model.get().getMetadata(); if (metadata.getAnnotations() == null) { metadata.setAnnotations(new Annotations()); model.get().setMetadata(metadata); @@ -403,7 +402,7 @@ public ResponseEntity> searchModels( @RequestParam(name = "page", defaultValue = "0", required = false) final Integer page ) { try { - Query query = null; + final Query query; if (queryJson != null) { // if query is provided deserialize it, append the soft delete filter final byte[] bytes = objectMapper.writeValueAsString(queryJson).getBytes(); diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/ProjectController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/ProjectController.java index de1ba4cac4..efa9aa9dfb 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/ProjectController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/dataservice/ProjectController.java @@ -156,7 +156,7 @@ public ResponseEntity> getProjects( ) { final RebacUser rebacUser = new RebacUser(currentUserService.get().getId(), reBACService); - List projectIds = null; + final List projectIds; try { projectIds = rebacUser.lookupProjects(); } catch (final Exception e) { @@ -213,7 +213,7 @@ public ResponseEntity> getProjects( // Set the contributors for the project. If we are unable to get the // contributors, we default to an empty // list. - List contributors = null; + final List contributors; try { contributors = projectPermissionsService.getContributors(rebacProject); project @@ -534,8 +534,8 @@ public ResponseEntity copyProject(@PathVariable("id") final UUID id) { // time the progress takes to reach each subsequent half. final Double HALFTIME_SECONDS = 1.0; - Future project; - Project clonedProject; + final Future project; + final Project clonedProject; final String userId = currentUserService.get().getId(); final String userName = userService.getById(userId).getName(); @@ -676,7 +676,7 @@ public ResponseEntity exportProject(@PathVariable("id") final UUID id) { @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @Secured(Roles.USER) public ResponseEntity importProject(@RequestPart("file") final MultipartFile input) { - if (!input.getContentType().equals("application/zip")) { + if (input.getContentType() != null && !input.getContentType().equals("application/zip")) { return ResponseEntity.badRequest().build(); } @@ -691,7 +691,7 @@ public ResponseEntity importProject(@RequestPart("file") final Multipar final String userId = currentUserService.get().getId(); final String userName = userService.getById(userId).getName(); - Project project; + final Project project; try { log.info("Importing project"); project = cloneService.importProject(userId, userName, projectExport); diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/knowledge/KnowledgeController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/knowledge/KnowledgeController.java index 9b40e66f05..a1c85f941d 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/knowledge/KnowledgeController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/knowledge/KnowledgeController.java @@ -385,7 +385,7 @@ ResponseEntity postCodeToAMR( final List files = new ArrayList<>(); final List blobs = new ArrayList<>(); - ResponseEntity resp = null; + final ResponseEntity resp; if (dynamicsOnly) { for (final Entry entry : codeContent.entrySet()) { @@ -602,7 +602,7 @@ public ResponseEntity postProfileDataset( ); // Provenance call if a document id is provided - StringMultipartFile documentFile = null; + final StringMultipartFile documentFile; if (documentId.isPresent()) { final DocumentAsset document = documentService.getAsset(documentId.get(), permission).orElseThrow(); documentFile = new StringMultipartFile(document.getText(), documentId.get() + ".txt", "application/text"); @@ -662,7 +662,7 @@ public ResponseEntity postProfileDataset( } final JsonNode card = resp.getBody(); - final JsonNode profilingResult = card.get("DATA_PROFILING_RESULT"); + final JsonNode profilingResult = (card != null) ? card.get("DATA_PROFILING_RESULT") : mapper.createObjectNode(); for (final DatasetColumn col : dataset.getColumns()) { final JsonNode annotation = profilingResult.get(col.getName()); @@ -822,9 +822,11 @@ private ResponseStatusException handleSkemaFeignException(final FeignException e ); return new ResponseStatusException(statusCode, messages.get("skema.internal-error")); } + + final HttpStatus httpStatus = (statusCode == null) ? HttpStatus.INTERNAL_SERVER_ERROR : statusCode; log.error( "An unknown error occurred while Skema Unified Service was trying to produce an AMR based on the provided resources" ); - return new ResponseStatusException(statusCode, messages.get("generic.unknown")); + return new ResponseStatusException(httpStatus, messages.get("generic.unknown")); } } diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/mira/MiraController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/mira/MiraController.java index 7d2fed578c..9f93710c0c 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/mira/MiraController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/mira/MiraController.java @@ -391,6 +391,8 @@ private ResponseStatusException handleMiraFeignException( ); return new ResponseStatusException(statusCode, messages.get("mira.internal-error")); } + + final HttpStatus httpStatus = (statusCode == null) ? HttpStatus.INTERNAL_SERVER_ERROR : statusCode; log.error( String.format( "An unknown error occurred while MIRA was trying to determine %s based on %s: %s", @@ -399,6 +401,6 @@ private ResponseStatusException handleMiraFeignException( input ) ); - return new ResponseStatusException(statusCode, messages.get("generic.unknown")); + return new ResponseStatusException(httpStatus, messages.get("generic.unknown")); } } diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/simulationservice/SimulationRequestController.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/simulationservice/SimulationRequestController.java index ce8d6aceaa..300a83a82b 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/simulationservice/SimulationRequestController.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/controller/simulationservice/SimulationRequestController.java @@ -126,6 +126,7 @@ public ResponseEntity makeForecastRunCiemss( .getBody(); final Simulation sim = new Simulation(); + sim.setId(UUID.fromString(res.getSimulationId())); sim.setType(SimulationType.SIMULATION); diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/security/KeycloakJwtAuthenticationConverter.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/security/KeycloakJwtAuthenticationConverter.java index dc386abf1d..b25cf10501 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/security/KeycloakJwtAuthenticationConverter.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/security/KeycloakJwtAuthenticationConverter.java @@ -2,7 +2,6 @@ import static java.util.stream.Collectors.toSet; -import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/ExtractionService.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/ExtractionService.java index b23da1c861..ccd113e732 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/ExtractionService.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/ExtractionService.java @@ -251,7 +251,7 @@ public ExtractPDFResponse runExtractPDF( final byte[] bytes = zipEntryToBytes(zipInputStream); fileMap.put(filenameNoExt, bytes); - if (entry != null && entry.getName().toLowerCase().endsWith(".json")) { + if (entry.getName().toLowerCase().endsWith(".json")) { final ObjectMapper objectMapper = new ObjectMapper(); final JsonNode rootNode = objectMapper.readTree(bytes); @@ -459,7 +459,7 @@ public Future extractPDFAndApplyToDocument( log.info("Document SHA: {}, checking cache", documentSHA); - ExtractPDFResponse extractionResponse = null; + final ExtractPDFResponse extractionResponse; if (responseCache.containsKey(documentSHA)) { log.info("Returning cached response for document {} for SHA: {}", documentId, documentSHA); diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/DatasetService.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/DatasetService.java index ba1097f265..19d9ed14b8 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/DatasetService.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/DatasetService.java @@ -167,7 +167,7 @@ private Dataset extractColumnsForFreshCreate(final Dataset dataset) throws IOExc } @Observed(name = "function_profile") - public void addDatasetColumns(final Dataset dataset, final String fileName, final List headers) { + public static void addDatasetColumns(final Dataset dataset, final String fileName, final List headers) { if (dataset.getColumns() == null) { dataset.setColumns(new ArrayList<>()); } @@ -193,7 +193,7 @@ public List> getCSVFile(final String filename, final UUID datasetId final BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes.get()))); - String line = null; + String line; Integer count = 0; while ((line = reader.readLine()) != null) { if (limit > 0 && count > limit) { diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/WorkflowService.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/WorkflowService.java index f365f0e0c9..30428d4902 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/WorkflowService.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/data/WorkflowService.java @@ -120,7 +120,7 @@ public Optional updateAsset( final JsonNode nodeContent = this.objectMapper.valueToTree(node); final JsonNode dbNodeContent = this.objectMapper.valueToTree(dbNode); - if (nodeContent.equals(dbNodeContent) == true) { + if (nodeContent.equals(dbNodeContent)) { nodeMap.remove(node.getId()); continue; } @@ -132,7 +132,7 @@ public Optional updateAsset( continue; } - if (dbNode.getVersion() == node.getVersion()) { + if (dbNode.getVersion().equals(node.getVersion())) { node.setVersion(dbNode.getVersion() + 1L); dbWorkflowNodes.set(index, node); } @@ -152,7 +152,7 @@ public Optional updateAsset( final JsonNode edgeContent = this.objectMapper.valueToTree(edge); final JsonNode dbEdgeContent = this.objectMapper.valueToTree(dbEdge); - if (edgeContent.equals(dbEdgeContent) == true) { + if (edgeContent.equals(dbEdgeContent)) { edgeMap.remove(edge.getId()); continue; } @@ -163,7 +163,7 @@ public Optional updateAsset( dbEdge.setVersion(1L); } - if (dbEdge.getVersion() == edge.getVersion()) { + if (dbEdge.getVersion().equals(edge.getVersion())) { edge.setVersion(dbEdge.getVersion() + 1L); dbWorkflowEdges.set(index, edge); } diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/NotificationGroupInstance.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/NotificationGroupInstance.java index 083396ab02..677918bbbb 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/NotificationGroupInstance.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/NotificationGroupInstance.java @@ -14,8 +14,8 @@ @Slf4j public class NotificationGroupInstance { - private Double halfTimeSeconds = 2.0; - private Double startSeconds = 0.0; + private final Double halfTimeSeconds; + private final Double startSeconds; private final ClientEventService clientEventService; private final NotificationService notificationService; private final NotificationGroup notificationGroup; diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/SimulationRequestStatusNotifier.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/SimulationRequestStatusNotifier.java index 9d386c4184..92c13acbdb 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/SimulationRequestStatusNotifier.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/service/notification/SimulationRequestStatusNotifier.java @@ -28,10 +28,10 @@ public class SimulationRequestStatusNotifier { private final int DEFAULT_POLLING_THRESHOLD = 500; // 500 * 5 seconds = 2500 seconds = 41 minutes private final Double DEFAULT_HALF_TIME_SECONDS = 2.0; - private UUID simulationId; - private UUID projectId; - private Schema.Permission permission; - private JsonNode metadata; // Arbitrary metadata to be sent to the client along with the notification event. + private final UUID simulationId; + private final UUID projectId; + private final Schema.Permission permission; + private final JsonNode metadata; // Arbitrary metadata to be sent to the client along with the notification event. @Setter private int interval = DEFAULT_POLLING_INTERVAL_SECONDS; @@ -100,9 +100,7 @@ private void sendStatusMessage( } else if (status.equals(ProgressState.QUEUED)) { notificationInterface.sendMessage("Simulation is queued...", ProgressState.QUEUED); } else { - notificationInterface.sendMessage( - (statusMessage == null || statusMessage.isEmpty()) ? "Simulation is running..." : statusMessage - ); + notificationInterface.sendMessage((statusMessage.isEmpty()) ? "Simulation is running..." : statusMessage); } } @@ -146,13 +144,9 @@ public void startPolling() { pollAttempts ); } catch (final Exception e) { - final String errMsg = e instanceof RuntimeException - ? e.getMessage() - : "Unexpected error occurred while checking the simulation status."; - notificationInterface.sendFinalMessage(errMsg, ProgressState.FAILED); - + notificationInterface.sendFinalMessage(e.getMessage(), ProgressState.FAILED); this.executor.shutdown(); - log.error("Error occurred while polling for simulation {}\n{}", this.simulationId, errMsg); + log.error("Error occurred while polling for simulation {}\n{}", this.simulationId, e.getMessage()); } }; executor.scheduleAtFixedRate(poller, this.interval, this.interval, TimeUnit.SECONDS); diff --git a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/utils/rebac/httputil/HttpUtil.java b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/utils/rebac/httputil/HttpUtil.java index 89ba139b89..4e202838cd 100644 --- a/packages/server/src/main/java/software/uncharted/terarium/hmiserver/utils/rebac/httputil/HttpUtil.java +++ b/packages/server/src/main/java/software/uncharted/terarium/hmiserver/utils/rebac/httputil/HttpUtil.java @@ -22,6 +22,7 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -64,71 +65,72 @@ public class HttpUtil { private static SSLConnectionSocketFactory sslsf; private static final AtomicBoolean tlsWarningEmitted = new AtomicBoolean(); - public static InputStream doGet(String url, String acceptType, String authorization) { + public static InputStream doGet(final String url, final String acceptType, final String authorization) { try { - HttpGet request = new HttpGet(url); + final HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.ACCEPT, acceptType); return doRequest(authorization, request); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } public static InputStream doPost( - String url, - String contentType, - String acceptType, - String content, - String authorization + final String url, + final String contentType, + final String acceptType, + final String content, + final String authorization ) { try { return doPostOrPut(contentType, acceptType, content, authorization, new HttpPost(url)); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } public static InputStream doPut( - String url, - String contentType, - String acceptType, - String content, - String authorization + final String url, + final String contentType, + final String acceptType, + final String content, + final String authorization ) { try { return doPostOrPut(contentType, acceptType, content, authorization, new HttpPut(url)); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } - public static void doDelete(String url, String authorization) { + public static void doDelete(final String url, final String authorization) { try { - HttpDelete request = new HttpDelete(url); + final HttpDelete request = new HttpDelete(url); doRequest(authorization, request); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } - public static HeadersBodyStatus doGet(String url, HeadersBody request) throws IOException { + public static HeadersBodyStatus doGet(final String url, final HeadersBody request) throws IOException { return doRequest("get", url, request); } - public static HeadersBodyStatus doPost(String url, HeadersBody request) throws IOException { + public static HeadersBodyStatus doPost(final String url, final HeadersBody request) throws IOException { return doRequest("post", url, request); } - public static HeadersBodyStatus doPut(String url, HeadersBody request) throws IOException { + public static HeadersBodyStatus doPut(final String url, final HeadersBody request) throws IOException { return doRequest("put", url, request); } - public static HeadersBodyStatus doDelete(String url, HeadersBody request) throws IOException { + public static HeadersBodyStatus doDelete(final String url, final HeadersBody request) throws IOException { return doRequest("delete", url, request); } - public static HeadersBodyStatus doRequest(String type, String url, HeadersBody request) throws IOException { - HttpRequestBase req; + public static HeadersBodyStatus doRequest(final String type, final String url, final HeadersBody request) + throws IOException { + final HttpRequestBase req; switch (type) { case "get": req = new HttpGet(url); @@ -154,14 +156,14 @@ public static HeadersBodyStatus doRequest(String type, String url, HeadersBody r addHeaders(req, request.getHeaders()); if (request.getBody() != null) { - if (req instanceof HttpEntityEnclosingRequestBase == false) { + if (!(req instanceof HttpEntityEnclosingRequestBase)) { throw new RuntimeException("Request type does not support body: " + type); } ((HttpEntityEnclosingRequestBase) req).setEntity(new InputStreamEntity(request.getBody())); } - HttpResponse res = getHttpClient().execute(req); - InputStream responseStream = null; + final HttpResponse res = getHttpClient().execute(req); + final InputStream responseStream; if (res.getEntity() != null) { responseStream = res.getEntity().getContent(); } else { @@ -173,28 +175,28 @@ public int read() throws IOException { }; } - Headers headers = new Headers(); - HeaderIterator it = res.headerIterator(); + final Headers headers = new Headers(); + final HeaderIterator it = res.headerIterator(); while (it.hasNext()) { - org.apache.http.Header header = it.nextHeader(); + final org.apache.http.Header header = it.nextHeader(); headers.add(header.getName(), header.getValue()); } return new HeadersBodyStatus(res.getStatusLine().toString(), headers, responseStream); } - private static void addHeaders(HttpRequestBase request, Headers headers) { - for (Header header : headers) { + private static void addHeaders(final HttpRequestBase request, final Headers headers) { + for (final Header header : headers) { request.setHeader(header.getName(), header.getValue()); } } private static InputStream doPostOrPut( - String contentType, - String acceptType, - String content, - String authorization, - HttpEntityEnclosingRequestBase request + final String contentType, + final String acceptType, + final String content, + final String authorization, + final HttpEntityEnclosingRequestBase request ) throws IOException { request.setHeader(HttpHeaders.CONTENT_TYPE, contentType); request.setHeader(HttpHeaders.ACCEPT, acceptType); @@ -205,26 +207,26 @@ private static InputStream doPostOrPut( return doRequest(authorization, request); } - private static InputStream doRequest(String authorization, HttpRequestBase request) throws IOException { + private static InputStream doRequest(final String authorization, final HttpRequestBase request) throws IOException { addAuth(request, authorization); - HttpResponse response = getHttpClient().execute(request); + final HttpResponse response = getHttpClient().execute(request); InputStream responseStream = null; if (response.getEntity() != null) { responseStream = response.getEntity().getContent(); } - int code = response.getStatusLine().getStatusCode(); + final int code = response.getStatusLine().getStatusCode(); if (code >= 200 && code < 300) { return responseStream; } else { Map error = null; try { - org.apache.http.Header header = response.getEntity().getContentType(); + final org.apache.http.Header header = response.getEntity().getContentType(); if (header != null && APPLICATION_JSON.equals(header.getValue())) { error = JsonSerialization.readValue(responseStream, Map.class); } - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Failed to read error response " + e); } finally { if (responseStream != null) { @@ -244,7 +246,7 @@ private static InputStream doRequest(String authorization, HttpRequestBase reque } } - private static void addAuth(HttpRequestBase request, String authorization) { + private static void addAuth(final HttpRequestBase request, final String authorization) { if (authorization != null) { request.setHeader(HttpHeaders.AUTHORIZATION, authorization); } @@ -261,20 +263,16 @@ public static HttpClient getHttpClient() { return httpClient; } - public static String urlencode(String value) { - try { - return URLEncoder.encode(value, UTF_8); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Failed to urlencode", e); - } + public static String urlencode(final String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); } - public static void setTruststore(File file, String password) + public static void setTruststore(final File file, final String password) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { if (!file.isFile()) { throw new RuntimeException("Truststore file not found: " + file.getAbsolutePath()); } - SSLContext theContext = SSLContexts.custom() + final SSLContext theContext = SSLContexts.custom() .setProtocol("TLS") .loadTrustMaterial(file, password == null ? null : password.toCharArray(), TrustSelfSignedStrategy.INSTANCE) .build(); @@ -293,24 +291,24 @@ public static void setSkipCertificateValidation() { log.error("The tool will skip certificate validation. This is highly discouraged for production use cases"); } - SSLContextBuilder builder = new SSLContextBuilder(); + final SSLContextBuilder builder = new SSLContextBuilder(); try { builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build()); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Failed setting up TLS", e); } } - public static String extractIdFromLocation(String location) { - int last = location.lastIndexOf("/"); + public static String extractIdFromLocation(final String location) { + final int last = location.lastIndexOf("/"); if (last != -1) { return location.substring(last + 1); } return null; } - public static String addQueryParamsToUri(String uri, String... queryParams) { + public static String addQueryParamsToUri(final String uri, final String... queryParams) { if (queryParams == null) { return uri; } @@ -319,26 +317,26 @@ public static String addQueryParamsToUri(String uri, String... queryParams) { throw new RuntimeException("Value missing for query parameter: " + queryParams[queryParams.length - 1]); } - Map params = new LinkedHashMap<>(); + final Map params = new LinkedHashMap<>(); for (int i = 0; i < queryParams.length; i += 2) { params.put(queryParams[i], queryParams[i + 1]); } return addQueryParamsToUri(uri, params); } - public static String addQueryParamsToUri(String uri, Map queryParams) { + public static String addQueryParamsToUri(final String uri, final Map queryParams) { if (queryParams.size() == 0) { return uri; } - StringBuilder query = new StringBuilder(); - for (Map.Entry params : queryParams.entrySet()) { + final StringBuilder query = new StringBuilder(); + for (final Map.Entry params : queryParams.entrySet()) { try { if (query.length() > 0) { query.append("&"); } - query.append(params.getKey()).append("=").append(URLEncoder.encode(params.getValue(), "utf-8")); - } catch (Exception e) { + query.append(params.getKey()).append("=").append(URLEncoder.encode(params.getValue(), StandardCharsets.UTF_8)); + } catch (final Exception e) { throw new RuntimeException("Failed to encode query params: " + params.getKey() + "=" + params.getValue()); } } @@ -346,7 +344,7 @@ public static String addQueryParamsToUri(String uri, Map queryPa return uri + (uri.indexOf("?") == -1 ? "?" : "&") + query; } - public static String composeResourceUrl(String adminRoot, String realm, String uri) { + public static String composeResourceUrl(final String adminRoot, final String realm, String uri) { if (!uri.startsWith("http:") && !uri.startsWith("https:")) { if ("realms".equals(uri) || uri.startsWith("realms/")) { uri = normalize(adminRoot) + uri; @@ -359,14 +357,14 @@ public static String composeResourceUrl(String adminRoot, String realm, String u return uri; } - public static String normalize(String value) { + public static String normalize(final String value) { return value.endsWith("/") ? value : value + "/"; } - public static void checkSuccess(String url, HeadersBodyStatus response) { + public static void checkSuccess(final String url, final HeadersBodyStatus response) { try { response.checkSuccess(); - } catch (HttpResponseException e) { + } catch (final HttpResponseException e) { if (e.getStatusCode() == 404) { throw new RuntimeException("Resource not found for url: " + url, e); } @@ -374,83 +372,83 @@ public static void checkSuccess(String url, HeadersBodyStatus response) { } } - public static T doGetJSON(Class type, String resourceUrl, String auth) { - Headers headers = new Headers(); + public static T doGetJSON(final Class type, final String resourceUrl, final String auth) { + final Headers headers = new Headers(); if (auth != null) { headers.add("Authorization", auth); } headers.add("Accept", "application/json"); - HeadersBodyStatus response; + final HeadersBodyStatus response; try { response = HttpUtil.doRequest("get", resourceUrl, new HeadersBody(headers)); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("HTTP request failed: GET " + resourceUrl, e); } checkSuccess(resourceUrl, response); - T result; + final T result; try { result = JsonSerialization.readValue(response.getBody(), type); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to read JSON response", e); } return result; } - public static void doPostJSON(String resourceUrl, String auth, Object content) { - Headers headers = new Headers(); + public static void doPostJSON(final String resourceUrl, final String auth, final Object content) { + final Headers headers = new Headers(); if (auth != null) { headers.add("Authorization", auth); } headers.add("Content-Type", "application/json"); - HeadersBodyStatus response; + final HeadersBodyStatus response; - byte[] body; + final byte[] body; try { body = JsonSerialization.writeValueAsBytes(content); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to serialize JSON", e); } try { response = HttpUtil.doRequest("post", resourceUrl, new HeadersBody(headers, new ByteArrayInputStream(body))); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("HTTP request failed: POST " + resourceUrl + "\n" + new String(body), e); } checkSuccess(resourceUrl, response); } - public static void doDeleteJSON(String resourceUrl, String auth, Object content) { - Headers headers = new Headers(); + public static void doDeleteJSON(final String resourceUrl, final String auth, final Object content) { + final Headers headers = new Headers(); if (auth != null) { headers.add("Authorization", auth); } headers.add("Content-Type", "application/json"); - HeadersBodyStatus response; + final HeadersBodyStatus response; - byte[] body; + final byte[] body; try { body = JsonSerialization.writeValueAsBytes(content); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("Failed to serialize JSON", e); } try { response = HttpUtil.doRequest("delete", resourceUrl, new HeadersBody(headers, new ByteArrayInputStream(body))); - } catch (IOException e) { + } catch (final IOException e) { throw new RuntimeException("HTTP request failed: DELETE " + resourceUrl + "\n" + new String(body), e); } checkSuccess(resourceUrl, response); } - public static String singularize(String value) { + public static String singularize(final String value) { return value.substring(0, value.length() - 1); } } diff --git a/packages/server/src/main/resources/messages.properties b/packages/server/src/main/resources/messages.properties index 22d4e8eac1..325ae7e7e2 100644 --- a/packages/server/src/main/resources/messages.properties +++ b/packages/server/src/main/resources/messages.properties @@ -74,6 +74,7 @@ sciml.service-unavailable = One of our model services (SciML) is temporarily una skema.bad-code = Our model service (SKEMA) couldn't find a valid model representation. This could be due to syntax or semantic errors in your code. Please review your code snippet and try again. skema.bad-equations = Our model service (SKEMA) couldn't find a valid model representation. This could be due to invalid equations or an inability to parse them into the requested framework. Please review your equations and try again. skema.error.align-model = We couldn't align the model with the selected document. Please verify that the model is valid and that the document has valid extractions. +skema.error.image-2-equation = We couldn't convert the equation image into valid LaTeX. Please verify that the image is of a valid equation. skema.internal-error = We couldn't produce a valid model representation based on the selected resource. Please verify that the resource is valid and try again. skema.service-unavailable = Our model service (SKEMA) is temporarily unavailable. Please try again later.