diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..a441bf19 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 + +[*.java] +indent_size = 4 +max_line_length = 120 \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..eafc2984 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +* text=auto +*.java text +*.sh text eol=lf +*.bat text eol=crlf diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..10cf663d --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,28 @@ +### Summary + +Briefly describe what this PR does and why. + +### Details + +Add more context about the changes: + +- What was changed? +- Why was it changed? +- Any trade-offs or known limitations? + +Screenshots, GIFs, or videos are welcome if this affects UI/UX. + +### How to Test + +Describe how reviewers can test the changes: + +1. Step one +2. Step two +3. Expected result + +### Checklist + +- [ ] Changes have been tested locally +- [ ] Logic is complete at 100% +- [ ] Design/UI is complete at 100% +- [ ] No breaking changes (or they are documented) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index c837e428..37fcd847 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -1,55 +1,24 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Java CI with Maven +name: Java CI on: push: - branches: [ "master" ] # Trigger the action on push to the master branch + branches: ["master"] pull_request: - branches: [ "master" ] # Trigger the action on pull requests targeting the master branch + branches: ["master"] jobs: build: - runs-on: ubuntu-latest # Use the latest version of Ubuntu for the build environment + runs-on: ubuntu-latest steps: - # Step 1: Check out the code from the repository - - name: Check out code - uses: actions/checkout@v4 - - # Step 2: Set up JDK 21 - - name: Set up JDK 21 - uses: actions/setup-java@v4 - with: - java-version: '21' - distribution: 'temurin' # Use the Temurin distribution for OpenJDK - cache: maven # Cache Maven dependencies to speed up subsequent builds - - # Step 3: Clean and build with Maven - - name: Build with Maven - run: mvn -B clean package --file pom.xml # Build the project with Maven, suppress the interactive mode - - # Step 4: Run Tests - # - name: Run Tests - # run: mvn test --file pom.xml # Run the tests to ensure the code works as expected - - # # Step 5: Upload the built JAR file as an artifact - # - name: Upload JAR Artifact - # uses: actions/upload-artifact@v4 - # with: - # name: backupmanager-jar # Name of the artifact - # path: target/BackupManager-1.0-SNAPSHOT-jar-with-dependencies.jar # Path to the JAR file + - uses: actions/checkout@v4 - # # Step 6: Static Code Analysis with SpotBugs (optional) - - name: Static Code Analysis with SpotBugs - run: mvn com.github.spotbugs:spotbugs-maven-plugin:spotbugs # Run SpotBugs for static code analysis + - name: Setup JDK 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + cache: maven - # # Step 7: Update dependency graph to improve Dependabot alerts - - name: Update dependency graph - uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 # Submit dependency graph for security monitoring \ No newline at end of file + - name: Build + Quality (skip tests) + run: mvn -B clean verify -DskipTests=true diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..c0bcafe9 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/.vscode/java-formatter.xml b/.vscode/java-formatter.xml new file mode 100644 index 00000000..7a5d23da --- /dev/null +++ b/.vscode/java-formatter.xml @@ -0,0 +1,382 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.vscode/settings.json b/.vscode/settings.json index c5f3f6b9..facc21ad 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "java.configuration.updateBuildConfiguration": "interactive" -} \ No newline at end of file + "java.configuration.updateBuildConfiguration": "interactive", + "java.format.settings.url": ".vscode/java-formatter.xml" +} diff --git a/README.md b/README.md index 2afdf3a2..ec1f3f6e 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,15 @@ $\rightarrow$ [Code tecnical documentation](./docs/code_documentation.md) | German | ✅ | | French | ✅ | +## Code Quality + +This project enforces automatic code quality checks during the Maven verify phase. +Running the following command will execute formatting checks, static analysis, and tests: + +`mvn clean verify` + +If any rule is violated, the build will fail. + ## Licence [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/) diff --git a/mvnw b/mvnw new file mode 100644 index 00000000..bd8896bf --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index a7e78ad1..dc2ec52c 100644 --- a/pom.xml +++ b/pom.xml @@ -6,8 +6,6 @@ jar UTF-8 - 21 - 21 @@ -131,6 +129,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 21 + + org.apache.maven.plugins maven-assembly-plugin @@ -158,14 +164,18 @@ com.github.spotbugs spotbugs-maven-plugin - 4.7.3.0 + 4.8.3.0 + verify - spotbugs + check + + false + diff --git a/src/main/java/backupmanager/BackupOperations.java b/src/main/java/backupmanager/BackupOperations.java index d8c12ace..cfa1c191 100644 --- a/src/main/java/backupmanager/BackupOperations.java +++ b/src/main/java/backupmanager/BackupOperations.java @@ -39,7 +39,7 @@ public class BackupOperations { private static final Logger logger = LoggerFactory.getLogger(BackupOperations.class); - public static void SingleBackup(ZippingContext context, BackupTriggeredEnum triggeredBy) { + public static void singleBackup(ZippingContext context, BackupTriggeredEnum triggeredBy) { if (context.backup() == null) throw new IllegalArgumentException("Backup cannot be null!"); logger.info("Event --> manual backup started"); @@ -48,7 +48,7 @@ public static void SingleBackup(ZippingContext context, BackupTriggeredEnum trig String path1 = context.backup().getTargetPath(); String path2 = context.backup().getDestinationPath(); - if(!CheckInputCorrect(context.backup().getName(), path1, path2, context.trayIcon())) + if(!checkInputCorrect(context.backup().getName(), path1, path2, context.trayIcon())) return; if (context.progressBar() != null) @@ -117,7 +117,7 @@ private static void updateAfterBackup(String path1, String path2, ZippingContext for (ConfigurationBackup b : backups) { if (b.getName().equals(context.backup().getName())) { - b.UpdateBackup(context.backup()); + b.updateBackup(context.backup()); break; } } @@ -159,7 +159,7 @@ else if (selectedFile.isFile()) return null; } - public static boolean CheckInputCorrect(String backupName, String path1, String path2, TrayIcon trayIcon) { + public static boolean checkInputCorrect(String backupName, String path1, String path2, TrayIcon trayIcon) { //check if inputs are null if(path1.length() == 0 || path2.length() == 0) { setError(ErrorTypes.InputMissing, trayIcon, backupName); diff --git a/src/main/java/backupmanager/Dialogs/BackupEntryDialog.form b/src/main/java/backupmanager/Dialogs/BackupEntryDialog.form index 0b04f6f7..bfb184a5 100644 --- a/src/main/java/backupmanager/Dialogs/BackupEntryDialog.form +++ b/src/main/java/backupmanager/Dialogs/BackupEntryDialog.form @@ -49,7 +49,7 @@ - + @@ -103,7 +103,7 @@ - + @@ -226,7 +226,7 @@ - + diff --git a/src/main/java/backupmanager/Dialogs/BackupEntryDialog.java b/src/main/java/backupmanager/Dialogs/BackupEntryDialog.java index 33f0c045..eb4b9c71 100644 --- a/src/main/java/backupmanager/Dialogs/BackupEntryDialog.java +++ b/src/main/java/backupmanager/Dialogs/BackupEntryDialog.java @@ -70,7 +70,7 @@ private void initializeDialog() { setTranslations(); } - private void SetLastBackupLabel(LocalDateTime date) { + private void setLastBackupLabel(LocalDateTime date) { if (date != null) { String dateStr = date.format(BackupHelper.formatter); dateStr = TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.LAST_BACKUP) + ": " + dateStr; @@ -80,9 +80,9 @@ private void SetLastBackupLabel(LocalDateTime date) { } private void updateCurrentFiedsByBackup(ConfigurationBackup backup) { - SetStartPathField(backup.getTargetPath()); - SetDestinationPathField(backup.getDestinationPath()); - SetLastBackupLabel(backup.getLastUpdateDate()); + setStartPathField(backup.getTargetPath()); + setDestinationPathField(backup.getDestinationPath()); + setLastBackupLabel(backup.getLastUpdateDate()); setAutoBackupPreference(backup.isAutomatic()); setCurrentBackupNotes(backup.getNotes()); setCurrentBackupMaxBackupsToKeep(backup.getMaxToKeep()); @@ -150,10 +150,10 @@ public ConfigurationBackup getBackup() { } } - public void SetStartPathField(String text) { + public void setStartPathField(String text) { startPathField.setText(text); } - public void SetDestinationPathField(String text) { + public void setDestinationPathField(String text) { destinationPathField.setText(text); } private void setCurrentBackupNotes(String notes) { @@ -163,7 +163,7 @@ public void setCurrentBackupMaxBackupsToKeep(int maxBackupsCount) { maxBackupCountSpinner.setValue(maxBackupsCount); } - public void SingleBackup(String path1, String path2, BackupTable backupTable) { + public void singleBackup(String path1, String path2, BackupTable backupTable) { logger.info("Event --> single backup"); currentBackup.setTargetPath(path2); @@ -171,7 +171,7 @@ public void SingleBackup(String path1, String path2, BackupTable backupTable) { String temp = "\\"; //------------------------------INPUT CONTROL ERRORS------------------------------ - if (!BackupOperations.CheckInputCorrect(currentBackup.getName(), path1, path2, null)) return; + if (!BackupOperations.checkInputCorrect(currentBackup.getName(), path1, path2, null)) return; //------------------------------TO GET THE CURRENT DATE------------------------------ LocalDateTime dateNow = LocalDateTime.now(); @@ -312,8 +312,8 @@ private void setTranslations() { startPathField.setToolTipText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.INITIAL_PATH_TOOLTIP)); destinationPathField.setToolTipText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.DESTINATION_PATH_TOOLTIP)); backupNoteTextArea.setToolTipText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.NOTES_TOOLTIP)); - SingleBackup.setText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.SINGLE_BACKUP_BUTTON)); - SingleBackup.setToolTipText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.SINGLE_BACKUP_TOOLTIP)); + singleBackup.setText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.SINGLE_BACKUP_BUTTON)); + singleBackup.setToolTipText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.SINGLE_BACKUP_TOOLTIP)); toggleAutoBackup.setText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.AUTO_BACKUP_BUTTON_OFF)); toggleAutoBackup.setToolTipText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.AUTO_BACKUP_TOOLTIP)); jLabel2.setText(TranslationCategory.BACKUP_ENTRY.getTranslation(TranslationKey.NOTES) + ":"); @@ -346,7 +346,7 @@ private void initComponents() { jScrollPane2 = new javax.swing.JScrollPane(); backupNoteTextArea = new javax.swing.JTextArea(); lastBackupLabel = new javax.swing.JLabel(); - SingleBackup = new javax.swing.JButton(); + singleBackup = new javax.swing.JButton(); toggleAutoBackup = new javax.swing.JToggleButton(); btnTimePicker = new backupmanager.svg.SVGButton(); maxBackupCountSpinner = new javax.swing.JSpinner(); @@ -406,12 +406,12 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { lastBackupLabel.setText("last backup: "); - SingleBackup.setBackground(new java.awt.Color(51, 153, 255)); - SingleBackup.setForeground(new java.awt.Color(255, 255, 255)); - SingleBackup.setText("Single Backup"); - SingleBackup.setToolTipText("Perform the backup"); - SingleBackup.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); - SingleBackup.addActionListener(new java.awt.event.ActionListener() { + singleBackup.setBackground(new java.awt.Color(51, 153, 255)); + singleBackup.setForeground(new java.awt.Color(255, 255, 255)); + singleBackup.setText("Single Backup"); + singleBackup.setToolTipText("Perform the backup"); + singleBackup.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); + singleBackup.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SingleBackupActionPerformed(evt); } @@ -502,7 +502,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { .addGroup(layout.createSequentialGroup() .addGap(131, 131, 131) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(SingleBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(singleBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(toggleAutoBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) @@ -541,7 +541,7 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() - .addComponent(SingleBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(singleBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(toggleAutoBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnTimePicker, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) @@ -587,7 +587,7 @@ private void SingleBackupActionPerformed(java.awt.event.ActionEvent evt) {//GEN- currentBackup = getBackup(); } - SingleBackup(startPathField.getText(), destinationPathField.getText(), backupTable); + singleBackup(startPathField.getText(), destinationPathField.getText(), backupTable); }//GEN-LAST:event_SingleBackupActionPerformed private void toggleAutoBackupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toggleAutoBackupActionPerformed @@ -647,7 +647,7 @@ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRS }//GEN-LAST:event_okButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JButton SingleBackup; + private javax.swing.JButton singleBackup; private backupmanager.customwidgets.ModernTextField backupNameField; private javax.swing.JTextArea backupNoteTextArea; private backupmanager.svg.SVGButton btnPathSearch1; diff --git a/src/main/java/backupmanager/Email/ConfigReader.java b/src/main/java/backupmanager/Email/ConfigReader.java index 3e2e0e5b..86a5ebf6 100644 --- a/src/main/java/backupmanager/Email/ConfigReader.java +++ b/src/main/java/backupmanager/Email/ConfigReader.java @@ -1,5 +1,6 @@ package backupmanager.Email; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; @@ -15,14 +16,14 @@ public static String getSMTPPassword() throws Exception { byte[] encryptedBytes = Files.readAllBytes(Paths.get("config.enc")); byte[] decoded = Base64.getDecoder().decode(encryptedBytes); - SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES"); + SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decrypted = cipher.doFinal(decoded); - String config = new String(decrypted); + String config = new String(decrypted, StandardCharsets.UTF_8); - for (String line : config.split("\n")) { + for (String line : config.lines().toList()) { if (line.startsWith("SMTP_PASSWORD=")) { return line.substring("SMTP_PASSWORD=".length()); } diff --git a/src/main/java/backupmanager/Email/EmailSender.java b/src/main/java/backupmanager/Email/EmailSender.java index 7ac04d87..6503a032 100644 --- a/src/main/java/backupmanager/Email/EmailSender.java +++ b/src/main/java/backupmanager/Email/EmailSender.java @@ -4,6 +4,7 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; @@ -48,16 +49,28 @@ public static void sendErrorEmail(String subject, String body) { } int rows = 300; - String emailMessage = String.format( - "Subject: %s\n\nUser: %s \nEmail: %s \nLanguage: %s \nInstalled Version: %s \n\nHas encountered the following error:\n%s \n\nLast %d rows of the application.log file:\n%s", - subject, - user.getUserCompleteName(), - user.email(), - user.language(), - ConfigKey.VERSION.getValue(), - body, - rows, - getTextFromLogFile(rows) + String emailMessage = String.format(""" + Subject: %s + + User: %s + Email: %s + Language: %s + Installed Version: %s + + Has encountered the following error: + %s + + Last %d rows of the application.log file: + %s + """, + subject, + user.getUserCompleteName(), + user.email(), + user.language(), + ConfigKey.VERSION.getValue(), + body, + rows, + getTextFromLogFile(rows) ); emailErrorLogger.error(emailMessage); // Log the message as ERROR, triggering the SMTPAppender @@ -121,7 +134,7 @@ public static String getTextFromLogFile(int rows) { List lastLines = new LinkedList<>(); - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { diff --git a/src/main/java/backupmanager/Email/EncryptConfigFile.java b/src/main/java/backupmanager/Email/EncryptConfigFile.java index 8293184a..024b1f42 100644 --- a/src/main/java/backupmanager/Email/EncryptConfigFile.java +++ b/src/main/java/backupmanager/Email/EncryptConfigFile.java @@ -1,5 +1,6 @@ package backupmanager.Email; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; @@ -13,14 +14,14 @@ public class EncryptConfigFile { public static void main(String[] args) throws Exception { byte[] plaintext = Files.readAllBytes(Paths.get("config.txt")); - SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES"); + SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encrypted = cipher.doFinal(plaintext); String encoded = Base64.getEncoder().encodeToString(encrypted); - Files.write(Paths.get("config.enc"), encoded.getBytes()); + Files.write(Paths.get("config.enc"), encoded.getBytes(StandardCharsets.UTF_8)); System.out.println("File config.enc created succesfully"); } -} \ No newline at end of file +} diff --git a/src/main/java/backupmanager/Email/EncryptPassword.java b/src/main/java/backupmanager/Email/EncryptPassword.java index a21684f0..24198ccc 100644 --- a/src/main/java/backupmanager/Email/EncryptPassword.java +++ b/src/main/java/backupmanager/Email/EncryptPassword.java @@ -1,5 +1,6 @@ package backupmanager.Email; +import java.nio.charset.StandardCharsets; import java.util.Base64; import javax.crypto.Cipher; @@ -9,10 +10,10 @@ public class EncryptPassword { private static final String SECRET_KEY = "BManagerSbureria"; public static String encrypt(String password) throws Exception { - SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES"); + SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); - byte[] encrypted = cipher.doFinal(password.getBytes()); + byte[] encrypted = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encrypted); } diff --git a/src/main/java/backupmanager/Entities/ConfigurationBackup.java b/src/main/java/backupmanager/Entities/ConfigurationBackup.java index 4b1f0ea0..0f1a6b33 100644 --- a/src/main/java/backupmanager/Entities/ConfigurationBackup.java +++ b/src/main/java/backupmanager/Entities/ConfigurationBackup.java @@ -72,11 +72,11 @@ public ConfigurationBackup(int id, String name, String targetPath, String destin } public ConfigurationBackup(ConfigurationBackup backup) { - UpdateBackup(backup); + updateBackup(backup); } // make it final to avoid the warning (now this method cannot be overrided by the subclasses) - public final void UpdateBackup(ConfigurationBackup backupUpdated) { + public final void updateBackup(ConfigurationBackup backupUpdated) { this.id = backupUpdated.getId(); this.name = backupUpdated.getName(); this.targetPath = backupUpdated.getTargetPath(); diff --git a/src/main/java/backupmanager/Enums/ConfigKey.java b/src/main/java/backupmanager/Enums/ConfigKey.java index 9fc33c4d..1eaf542a 100644 --- a/src/main/java/backupmanager/Enums/ConfigKey.java +++ b/src/main/java/backupmanager/Enums/ConfigKey.java @@ -2,6 +2,7 @@ import java.io.FileReader; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.EnumMap; import java.util.Map; @@ -34,7 +35,7 @@ public enum ConfigKey { private static final Logger logger = LoggerFactory.getLogger(ConfigKey.class); public static void loadFromJson(String filePath) { - try (FileReader reader = new FileReader(filePath)) { + try (FileReader reader = new FileReader(filePath, StandardCharsets.UTF_8)) { JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject(); for (ConfigKey key : ConfigKey.values()) { if (jsonObject.has(key.name())) { @@ -49,4 +50,4 @@ public static void loadFromJson(String filePath) { public String getValue() { return configValues.get(this); } -} \ No newline at end of file +} diff --git a/src/main/java/backupmanager/Enums/TranslationLoaderEnum.java b/src/main/java/backupmanager/Enums/TranslationLoaderEnum.java index 3a1f4ff0..7eebce77 100644 --- a/src/main/java/backupmanager/Enums/TranslationLoaderEnum.java +++ b/src/main/java/backupmanager/Enums/TranslationLoaderEnum.java @@ -2,6 +2,7 @@ import java.io.FileReader; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -309,7 +310,7 @@ public String getDefaultValue() { public static void loadTranslations(String filePath) throws IOException { Gson gson = new Gson(); - try (FileReader reader = new FileReader(filePath)) { + try (FileReader reader = new FileReader(filePath, StandardCharsets.UTF_8)) { JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); for (TranslationCategory category : TranslationCategory.values()) { diff --git a/src/main/java/backupmanager/GUI/Controllers/BackupPopupController.java b/src/main/java/backupmanager/GUI/Controllers/BackupPopupController.java index a2e6d3a2..ec7577ad 100644 --- a/src/main/java/backupmanager/GUI/Controllers/BackupPopupController.java +++ b/src/main/java/backupmanager/GUI/Controllers/BackupPopupController.java @@ -110,7 +110,7 @@ public static void popupItemRunBackup(int selectedRow, BackupTable backupTable, BackupManagerGUI.progressBar = new BackupProgressGUI(backup.getTargetPath(), backup.getDestinationPath()); ZippingContext context = ZippingContext.create(backup, null, backupTable, BackupManagerGUI.progressBar, interruptBackupPopupItem, RunBackupPopupItem); - BackupOperations.SingleBackup(context, BackupTriggeredEnum.USER); + BackupOperations.singleBackup(context, BackupTriggeredEnum.USER); } } diff --git a/src/main/java/backupmanager/Helpers/BackupHelper.java b/src/main/java/backupmanager/Helpers/BackupHelper.java index 89124484..fc345582 100644 --- a/src/main/java/backupmanager/Helpers/BackupHelper.java +++ b/src/main/java/backupmanager/Helpers/BackupHelper.java @@ -179,7 +179,7 @@ public static ConfigurationBackup toggleAutomaticBackup(ConfigurationBackup back return backup; } - if(!BackupOperations.CheckInputCorrect(backup.getName(), backup.getTargetPath(), backup.getDestinationPath(), null)) return null; + if(!BackupOperations.checkInputCorrect(backup.getName(), backup.getTargetPath(), backup.getDestinationPath(), null)) return null; // if the file has not been saved you need to save it before setting the auto backup if(!backup.isAutomatic() || backup.getNextBackupDate() == null || backup.getTimeIntervalBackup() == null) { diff --git a/src/main/java/backupmanager/Json/JSONConfigReader.java b/src/main/java/backupmanager/Json/JSONConfigReader.java index 17dd16fc..a120cbcb 100644 --- a/src/main/java/backupmanager/Json/JSONConfigReader.java +++ b/src/main/java/backupmanager/Json/JSONConfigReader.java @@ -2,6 +2,7 @@ import java.io.FileReader; import java.io.IOException; +import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,36 +40,47 @@ public boolean isMenuItemEnabled(String menuItem) { } public int readCheckForBackupTimeInterval() throws IOException { - try { - JsonObject backupService = getConfig("BackupService"); - JsonElement interval = backupService.get("value"); - - // if the interval is null, set to default of 5 minutes - int timeInterval = (interval != null) ? interval.getAsInt() : 5; + JsonObject backupService = getConfig("BackupService"); - logger.info("Time interval set to " + timeInterval + " minutes"); - return timeInterval; - } catch (NullPointerException e) { - logger.error("Error retrieving backup time interval, defaulting to 5 minutes: " + e.getMessage(), e); - return 5; // Default to 5 minutes + if (backupService == null) { + logger.warn("BackupService config missing, defaulting to 5 minutes"); + return 5; } + + JsonElement interval = backupService.get("value"); + + int timeInterval = (interval != null && !interval.isJsonNull()) ? interval.getAsInt() : 5; + + logger.info("Time interval set to " + timeInterval + " minutes"); + return timeInterval; } public int getConfigValue(String key, int defaultValue) { try { JsonObject logService = getConfig(key); + + if (logService == null) { + logger.warn("Missing config for {}, using default {}", key, defaultValue); + return defaultValue; + } + JsonElement value = logService.get(key); - return (value != null && value.isJsonPrimitive()) ? value.getAsInt() : defaultValue; - } catch (IOException | NullPointerException e) { - logger.error("Error retrieving config value for " + key + ": " + e.getMessage(), e); + if (value == null || value.isJsonNull() || !value.isJsonPrimitive()) { + return defaultValue; + } + + return value.getAsInt(); + + } catch (IOException e) { + logger.error("Error retrieving config value for {}", key, e); return defaultValue; } } private void loadConfig() { String filePath = directoryPath + filename; - try (FileReader reader = new FileReader(filePath)) { + try (FileReader reader = new FileReader(filePath, StandardCharsets.UTF_8)) { Gson gson = new Gson(); config = gson.fromJson(reader, JsonObject.class); } catch (IOException e) { @@ -82,4 +94,4 @@ private JsonObject getConfig(String key) throws IOException { } return config.getAsJsonObject(key); } -} \ No newline at end of file +} diff --git a/src/main/java/backupmanager/Managers/ExportManager.java b/src/main/java/backupmanager/Managers/ExportManager.java index 41d9a1bb..6b84bfd7 100644 --- a/src/main/java/backupmanager/Managers/ExportManager.java +++ b/src/main/java/backupmanager/Managers/ExportManager.java @@ -3,6 +3,7 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.ArrayList; @@ -150,7 +151,7 @@ public static void exportAsCSV(ArrayList backups, String he } } - try (FileWriter writer = new FileWriter(fullPath)) { + try (FileWriter writer = new FileWriter(fullPath, StandardCharsets.UTF_8)) { // Prepare header row if (header != null && !header.isEmpty()) { writer.append(header).append("\n"); @@ -171,4 +172,4 @@ public static void exportAsCSV(ArrayList backups, String he logger.info("Exporting backups to CSV finished"); } } -} \ No newline at end of file +} diff --git a/src/main/java/backupmanager/Services/BackgroundService.java b/src/main/java/backupmanager/Services/BackgroundService.java index aa8c1301..2fb9d782 100644 --- a/src/main/java/backupmanager/Services/BackgroundService.java +++ b/src/main/java/backupmanager/Services/BackgroundService.java @@ -117,7 +117,7 @@ private void executeBackups(List backups) { try { for (ConfigurationBackup backup : backups) { ZippingContext context = ZippingContext.create(backup, trayIcon.getTrayIcon(), null, null, null, null); - BackupOperations.SingleBackup(context, BackupTriggeredEnum.SCHEDULER); + BackupOperations.singleBackup(context, BackupTriggeredEnum.SCHEDULER); } } finally { logger.info("All backups completed. Resetting isBackingUp flag."); diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index b4c62b7a..7ea956ad 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -132,4 +132,4 @@ - \ No newline at end of file + diff --git a/src/test/java/test/BackupTest.java b/src/test/java/test/BackupTest.java index 2f3b36bc..62dcb5a9 100644 --- a/src/test/java/test/BackupTest.java +++ b/src/test/java/test/BackupTest.java @@ -1,5 +1,3 @@ package test; -public class BackupTest { - -} +public class BackupTest {} diff --git a/src/test/java/test/ConfigurationsRepositoryTest.java b/src/test/java/test/ConfigurationsRepositoryTest.java new file mode 100644 index 00000000..6977e0fc --- /dev/null +++ b/src/test/java/test/ConfigurationsRepositoryTest.java @@ -0,0 +1,64 @@ +package test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import backupmanager.Entities.Confingurations; +import backupmanager.Enums.LanguagesEnum; +import backupmanager.Enums.ThemesEnum; +import backupmanager.database.Database; +import backupmanager.database.DatabaseInitializer; +import backupmanager.database.DatabasePaths; +import java.io.IOException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ConfigurationsRepositoryTest { + + private LanguagesEnum language; + private ThemesEnum theme; + + @BeforeEach + protected void initDbAndBuildConfigurations() throws Exception { + Database.init(DatabasePaths.getDatabasePath()); + DatabaseInitializer.init(); + + Confingurations.loadAllConfigurations(); + language = Confingurations.getLanguage(); + theme = Confingurations.getTheme(); + + buildAndReloadConfigurations(); + } + + @AfterEach + protected void resetValuesBeforeTest() { + Confingurations.setLanguage(language); + Confingurations.setTheme(theme.getThemeName()); + Confingurations.updateAllConfigurations(); + } + + @Test + protected void equals_shouldReturnTrue_forSameLanguage() throws IOException { + assertEquals(LanguagesEnum.DEU, Confingurations.getLanguage()); + } + + @Test + protected void equals_shouldReturnTrue_forSameTheme() throws IOException { + assertEquals(ThemesEnum.CARBON, Confingurations.getTheme()); + } + + private void buildAndReloadConfigurations() throws IOException { + buildValidConfigurationsObject(); + realodConfigurations(); + } + + private void buildValidConfigurationsObject() { + Confingurations.setLanguage(LanguagesEnum.DEU); + Confingurations.setTheme(ThemesEnum.CARBON.getThemeName()); + } + + private void realodConfigurations() { + Confingurations.updateAllConfigurations(); + Confingurations.loadAllConfigurations(); + } +} diff --git a/src/test/java/test/ConfigurationsTest.java b/src/test/java/test/ConfigurationsTest.java deleted file mode 100644 index 20749c2e..00000000 --- a/src/test/java/test/ConfigurationsTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package test; - -import java.io.IOException; - -import org.junit.jupiter.api.AfterEach; -import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import backupmanager.Entities.Confingurations; -import backupmanager.Enums.LanguagesEnum; -import backupmanager.Enums.ThemesEnum; -import backupmanager.database.Database; -import backupmanager.database.DatabaseInitializer; -import backupmanager.database.DatabasePaths; - -public class ConfigurationsTest { - - private LanguagesEnum language; - private ThemesEnum theme; - - @BeforeEach - protected void initDbAndBuildConfigurations() throws Exception { - Database.init(DatabasePaths.getDatabasePath()); - DatabaseInitializer.init(); - - Confingurations.loadAllConfigurations(); - language = Confingurations.getLanguage(); - theme = Confingurations.getTheme(); - - buildAndReloadConfigurations(); - } - - @AfterEach - protected void resetValuesBeforeTest() { - Confingurations.setLanguage(language); - Confingurations.setTheme(theme.getThemeName()); - Confingurations.updateAllConfigurations(); - } - - @Test - protected void equals_shouldReturnTrue_forSameLanguage() throws IOException { - assertEquals(LanguagesEnum.DEU, Confingurations.getLanguage()); - } - - @Test - protected void equals_shouldReturnTrue_forSameTheme() throws IOException { - assertEquals(ThemesEnum.CARBON, Confingurations.getTheme()); - } - - private void buildAndReloadConfigurations() throws IOException { - buildValidConfigurationsObject(); - realodConfigurations(); - } - - private void buildValidConfigurationsObject() { - Confingurations.setLanguage(LanguagesEnum.DEU); - Confingurations.setTheme(ThemesEnum.CARBON.getThemeName()); - } - - private void realodConfigurations() { - Confingurations.updateAllConfigurations(); - Confingurations.loadAllConfigurations(); - } -} \ No newline at end of file diff --git a/src/test/java/test/RunningBackupsTest.java b/src/test/java/test/RunningBackupsTest.java deleted file mode 100644 index 5526c61a..00000000 --- a/src/test/java/test/RunningBackupsTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package test; - -public class RunningBackupsTest { - -} diff --git a/src/test/java/test/SqlHelperTest.java b/src/test/java/test/SqlHelperTest.java index fc34b917..936680c0 100644 --- a/src/test/java/test/SqlHelperTest.java +++ b/src/test/java/test/SqlHelperTest.java @@ -1,4 +1,111 @@ package test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import backupmanager.Entities.TimeInterval; +import backupmanager.Helpers.SqlHelper; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Month; +import org.junit.jupiter.api.Test; + public class SqlHelperTest { - + + private static final LocalDateTime TestDate = LocalDate.of(2026, Month.APRIL, 8).atStartOfDay(); + private static final long MILLISECONDS = 1_775_599_200_000L; + + @Test + void toMilliseconds_shouldBeEquals_forValidLocalDate() { + long mills = SqlHelper.toMilliseconds(TestDate); + assertEquals(mills, MILLISECONDS); + } + + @Test + void toMilliseconds_shouldReturnTrue_forNullLocalDate() { + long mills = SqlHelper.toMilliseconds(null); + assertTrue(mills == 0); + } + + @Test + void toMillisecondsWithFallback_shouldBeEquals_forValidLocalDate() { + long mills = SqlHelper.toMilliseconds(TestDate, LocalDateTime.now()); + assertEquals(mills, MILLISECONDS); + } + + @Test + void toMillisecondsWithFallback_shouldReturnTrue_forNullLocalDate() { + long mills = SqlHelper.toMilliseconds(null, LocalDateTime.now()); + assertTrue(mills > 0); + } + + @Test + public void toMillisecondsWithFallback_shouldThrowException_whenFallbackValueIsNull() { + IllegalArgumentException ex = + assertThrows(IllegalArgumentException.class, () -> SqlHelper.toMilliseconds(null, null)); + assertEquals("Cannot pass the fallback value as null", ex.getMessage()); + } + + @Test + void toLocalDateTime_shouldBeEquals_forValidMills() { + LocalDateTime dateTime = SqlHelper.toLocalDateTime(MILLISECONDS); + assertEquals(dateTime, TestDate); + } + + @Test + void toLocalDateTime_shouldReturnTrue_forNullOrNotValidMillsValue() { + LocalDateTime dateTime = SqlHelper.toLocalDateTime(null); + LocalDateTime dateTime2 = SqlHelper.toLocalDateTime(Long.getLong("-2")); + assertTrue(dateTime == null && dateTime2 == null); + } + + @Test + void toLocalDate_shouldBeEquals_forValidMills() { + LocalDate date = SqlHelper.toLocalDate(MILLISECONDS); + assertEquals(date, TestDate.toLocalDate()); + } + + @Test + void toLocalDate_shouldReturnTrue_forNullOrNotValidMillsValue() { + LocalDate date = SqlHelper.toLocalDate(null); + LocalDate date2 = SqlHelper.toLocalDate(Long.getLong("-2")); + assertTrue(date == null && date2 == null); + } + + @Test + void millisecondsAndDateConversion_equal_forSameLocalDate() { + LocalDateTime inputDate = LocalDate.of(2026, Month.APRIL, 8).atStartOfDay(); + + long mills = SqlHelper.toMilliseconds(inputDate); + LocalDateTime dateTime = SqlHelper.toLocalDateTime(mills); + + assertEquals(inputDate, dateTime); + } + + @Test + void toTimeInterval_equal_forSameTimeInterval() { + String time = "10.5:34"; + TimeInterval timeInterval = SqlHelper.toTimeInterval(time); + assertEquals(time, timeInterval.toString()); + } + + @Test + void toTimeInterval_shouldReturnTrue_forNullString() { + TimeInterval timeInterval = SqlHelper.toTimeInterval(null); + assertTrue(timeInterval == null); + } + + @Test + void toString_equal_forValidObject() { + TimeInterval timeInterval = new TimeInterval(5, 10, 5); + String timeIntervalStr = SqlHelper.toString(timeInterval); + assertEquals(timeInterval.toString(), timeIntervalStr); + } + + @Test + void toString_shouldReturnTrue_forNullString() { + String timeIntervalStr = SqlHelper.toString(null); + assertTrue(timeIntervalStr == null); + } } diff --git a/src/test/java/test/TestBackupOperations.java b/src/test/java/test/TestBackupOperations.java index 749ce870..0ced028d 100644 --- a/src/test/java/test/TestBackupOperations.java +++ b/src/test/java/test/TestBackupOperations.java @@ -17,7 +17,7 @@ void checkInputCorrect_shouldReturnFalse_forNonExistingPaths() { String path2 = "/wrong/path/dir"; assertFalse( - BackupOperations.CheckInputCorrect("backup", path1, path2, null) + BackupOperations.checkInputCorrect("backup", path1, path2, null) ); } @@ -26,7 +26,7 @@ void checkInputCorrect_shouldReturnFalse_forSamePaths() throws IOException { File file = File.createTempFile("file", ".txt"); assertFalse( - BackupOperations.CheckInputCorrect("backup", file.getPath(), file.getPath(), null) + BackupOperations.checkInputCorrect("backup", file.getPath(), file.getPath(), null) ); } @@ -36,7 +36,7 @@ void checkInputCorrect_shouldReturnTrue_forValidDifferentPaths() throws IOExcept File tempFile2 = File.createTempFile("file2", ".txt"); assertTrue( - BackupOperations.CheckInputCorrect("backup", tempFile1.getPath(), tempFile2.getPath(), null) + BackupOperations.checkInputCorrect("backup", tempFile1.getPath(), tempFile2.getPath(), null) ); } }