diff --git a/analysis/.gitattributes b/analysis/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/analysis/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/analysis/.gitignore b/analysis/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/analysis/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/analysis/.mvn/wrapper/maven-wrapper.properties b/analysis/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..216df05 --- /dev/null +++ b/analysis/.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.16/apache-maven-3.9.16-bin.zip diff --git a/analysis/mvnw b/analysis/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/analysis/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/analysis/mvnw.cmd b/analysis/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/analysis/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/analysis/pom.xml b/analysis/pom.xml new file mode 100644 index 0000000..fa409ff --- /dev/null +++ b/analysis/pom.xml @@ -0,0 +1,153 @@ + + + 4.0.0 + + io.theurl + parent + ${revision} + ../pom.xml + + + analysis + + analysis + analysis + + + 2025.1.1 + false + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.cloud + spring-cloud-starter-config + + + + com.mysql + mysql-connector-j + runtime + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-amqp-test + test + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.springframework.boot + spring-boot-starter-data-mongodb-test + test + + + org.springframework.boot + spring-boot-starter-security-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.projectlombok + lombok + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + + + + + + + + diff --git a/analysis/src/main/java/io/theurl/analysis/AnalysisApplication.java b/analysis/src/main/java/io/theurl/analysis/AnalysisApplication.java new file mode 100644 index 0000000..0d7f454 --- /dev/null +++ b/analysis/src/main/java/io/theurl/analysis/AnalysisApplication.java @@ -0,0 +1,13 @@ +package io.theurl.analysis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AnalysisApplication { + + public static void main(String[] args) { + SpringApplication.run(AnalysisApplication.class, args); + } + +} diff --git a/analysis/src/main/resources/application.yaml b/analysis/src/main/resources/application.yaml new file mode 100644 index 0000000..4f7bdef --- /dev/null +++ b/analysis/src/main/resources/application.yaml @@ -0,0 +1,60 @@ +server: + port: 8904 + +spring: + profiles: + active: ${SPRING_PROFILES_ACTIVE:dev} + application: + name: analysis + config: + import: optional:configserver:${CONFIG_SERVER_URI:http://localhost:8900/env} + cloud: + config: + fail-fast: true + enabled: true + uri: ${CONFIG_SERVER_URI:http://localhost:8900/env} + label: master + profile: ${SPRING_PROFILES_ACTIVE:dev} + datasource: + url: ${DB_URL:jdbc:postgresql://localhost:5432/linkyou?currentSchema=public} + username: ${DB_USERNAME:postgres} + password: ${DB_PASSWORD:postgres} + driver-class-name: ${DB_DRIVER:org.postgresql.Driver} + jpa: + hibernate: + ddl-auto: update + dialect: ${DB_DIALECT:org.hibernate.dialect.PostgreSQLDialect} + show-sql: true + properties: + hibernate: + globally_quoted_identifiers: true + multiTenancy: SCHEMA + format_sql: true + data: + redis: + url: ${REDIS_URL:redis://localhost:6379} + web: + error: + include-message: ALWAYS + include-exception: true + include-stacktrace: ALWAYS + rabbitmq: + host: ${RABBITMQ_HOST:127.0.0.1} + port: ${RABBITMQ_PORT:5672} + username: ${RABBITMQ_USERNAME:guest} + password: ${RABBITMQ_PASSWORD:guest} + +jwt: + secret: ${JWT_SECRET:your-jwt-secret} + issuer: theurl.io + expiration: 3600 # in seconds + +logging: + file: + name: #{level}-{T(java.time.LocalDate).now()}.log + path: logs + level: + io.theurl.identity: debug + org.springframework.cloud.config.client: debug + org.springframework: error + root: info diff --git a/analysis/src/main/resources/logback-spring.xml b/analysis/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..1b15486 --- /dev/null +++ b/analysis/src/main/resources/logback-spring.xml @@ -0,0 +1,107 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + utf8 + + + + + ${LOG_PATH}/analysis/info/current.log + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + ${LOG_PATH}/analysis/info/%d{yyyy-MM-dd}.log + 100MB + 30 + + + + + ${LOG_PATH}/analysis/error/current.log + + ERROR + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + ${LOG_PATH}/analysis/error/%d{yyyy-MM-dd}.log + 100MB + 30 + + + + + ${LOG_PATH}/analysis/warn/current.log + + WARN + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + ${LOG_PATH}/analysis/warn/%d{yyyy-MM-dd}.log + 100MB + 30 + + + + + ${LOG_PATH}/analysis/debug/current.log + + DEBUG + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + ${LOG_PATH}/analysis/debug/%d{yyyy-MM-dd}.log + 100MB + 30 + + + + + ${LOG_PATH}/analysis/sql/current.log + + DEBUG + ACCEPT + DENY + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + ${LOG_PATH}/analysis/sql/%d{yyyy-MM-dd}.log + 100MB + 30 + + + + + + + + + + + + + + + + + + + diff --git a/analysis/src/test/java/io/theurl/analysis/AnalysisApplicationTests.java b/analysis/src/test/java/io/theurl/analysis/AnalysisApplicationTests.java new file mode 100644 index 0000000..504a77b --- /dev/null +++ b/analysis/src/test/java/io/theurl/analysis/AnalysisApplicationTests.java @@ -0,0 +1,13 @@ +package io.theurl.analysis; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AnalysisApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/bundle/pom.xml b/bundle/pom.xml index 511d955..d2506bc 100644 --- a/bundle/pom.xml +++ b/bundle/pom.xml @@ -5,7 +5,7 @@ io.theurl parent - 1.0 + ${revision} ../pom.xml diff --git a/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemAppendCommand.java b/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemAppendCommand.java new file mode 100644 index 0000000..968368a --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemAppendCommand.java @@ -0,0 +1,18 @@ +package io.theurl.bundle.application.command; + +import com.neroyun.mediator.Command; +import lombok.Data; + +@Data +public class BundleItemAppendCommand implements Command { + private final String vanity; + + public BundleItemAppendCommand(String vanity) { + this.vanity = vanity; + } + + private String url; + private String title; + private String description; + private String image; +} diff --git a/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemRemoveCommand.java b/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemRemoveCommand.java new file mode 100644 index 0000000..2ad3405 --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemRemoveCommand.java @@ -0,0 +1,6 @@ +package io.theurl.bundle.application.command; + +import com.neroyun.mediator.Command; + +public record BundleItemRemoveCommand(String vanity, long itemId) implements Command { +} diff --git a/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemUpdateCommand.java b/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemUpdateCommand.java new file mode 100644 index 0000000..e139a3f --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/application/command/BundleItemUpdateCommand.java @@ -0,0 +1,19 @@ +package io.theurl.bundle.application.command; + +import com.neroyun.mediator.Command; +import lombok.Data; + +@Data +public class BundleItemUpdateCommand implements Command { + private final String vanity; + private final long itemId; + + public BundleItemUpdateCommand(String vanity, long itemId) { + this.vanity = vanity; + this.itemId = itemId; + } + + private String title; + private String description; + private String image; +} diff --git a/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemAppendCommandHandler.java b/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemAppendCommandHandler.java new file mode 100644 index 0000000..e3f3f2c --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemAppendCommandHandler.java @@ -0,0 +1,70 @@ +package io.theurl.bundle.application.handler; + +import com.neroyun.mediator.Handler; +import com.neroyun.mediator.MessageContext; +import io.theurl.bundle.application.command.BundleItemAppendCommand; +import io.theurl.bundle.domain.repository.BundleRepository; +import io.theurl.framework.core.BeanScope; +import io.theurl.framework.security.UnauthorizedAccessException; +import jakarta.persistence.EntityNotFoundException; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.concurrent.CompletableFuture; + +@Component +@Scope(value = BeanScope.REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) +public class BundleItemAppendCommandHandler implements Handler { + private final BundleRepository repository; + + public BundleItemAppendCommandHandler(BundleRepository repository) { + this.repository = repository; + } + + @Override + public CompletableFuture handleAsync(BundleItemAppendCommand message, MessageContext context) { + var aggregate = repository.findByVanity(message.getVanity()); + if (aggregate == null) { + throw new EntityNotFoundException("Bundle not found for vanity: " + message.getVanity()); + } + + var userId = getUserId(); + var request = getRequest(); + + assert request != null; + + if (!aggregate.getOwnerId().equals(userId)) { + if (aggregate.getOwnerId() == null && request.isUserInRole("ADMIN")) { + throw new UnauthorizedAccessException("You are not allowed to complete this operation"); + } + } + + aggregate.appendItem(message.getUrl(), message.getTitle(), message.getDescription(), message.getImage()); + repository.save(aggregate, getUserId()); + return CompletableFuture.completedFuture(null); + } + + private HttpServletRequest getRequest() { + var request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + + if (request == null) { + return null; + } + + return request.getRequest(); + } + + private long getUserId() { + var request = getRequest(); + + if (request == null || request.getUserPrincipal() == null) { + return 0; + } + + return Long.parseLong(request.getUserPrincipal().getName()); + } +} diff --git a/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemRemoveCommandHandler.java b/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemRemoveCommandHandler.java new file mode 100644 index 0000000..36f7f9b --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemRemoveCommandHandler.java @@ -0,0 +1,70 @@ +package io.theurl.bundle.application.handler; + +import com.neroyun.mediator.Handler; +import com.neroyun.mediator.MessageContext; +import io.theurl.bundle.application.command.BundleItemRemoveCommand; +import io.theurl.bundle.domain.repository.BundleRepository; +import io.theurl.framework.core.BeanScope; +import io.theurl.framework.security.UnauthorizedAccessException; +import jakarta.persistence.EntityNotFoundException; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.concurrent.CompletableFuture; + +@Component +@Scope(value = BeanScope.REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) +public class BundleItemRemoveCommandHandler implements Handler { + private final BundleRepository repository; + + public BundleItemRemoveCommandHandler(BundleRepository repository) { + this.repository = repository; + } + + @Override + public CompletableFuture handleAsync(BundleItemRemoveCommand message, MessageContext context) { + var aggregate = repository.findByVanity(message.vanity()); + if (aggregate == null) { + throw new EntityNotFoundException("Bundle not found for vanity: " + message.vanity()); + } + + var userId = getUserId(); + var request = getRequest(); + + assert request != null; + + if (!aggregate.getOwnerId().equals(userId)) { + if (aggregate.getOwnerId() == null && request.isUserInRole("ADMIN")) { + throw new UnauthorizedAccessException("You are not allowed to complete this operation"); + } + } + + aggregate.removeItem(message.itemId()); + repository.save(aggregate, getUserId()); + return CompletableFuture.completedFuture(null); + } + + private HttpServletRequest getRequest() { + var request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + + if (request == null) { + return null; + } + + return request.getRequest(); + } + + private long getUserId() { + var request = getRequest(); + + if (request == null || request.getUserPrincipal() == null) { + return 0; + } + + return Long.parseLong(request.getUserPrincipal().getName()); + } +} diff --git a/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemUpdateCommandHandler.java b/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemUpdateCommandHandler.java new file mode 100644 index 0000000..881ea01 --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/application/handler/BundleItemUpdateCommandHandler.java @@ -0,0 +1,70 @@ +package io.theurl.bundle.application.handler; + +import com.neroyun.mediator.Handler; +import com.neroyun.mediator.MessageContext; +import io.theurl.bundle.application.command.BundleItemUpdateCommand; +import io.theurl.bundle.domain.repository.BundleRepository; +import io.theurl.framework.core.BeanScope; +import io.theurl.framework.security.UnauthorizedAccessException; +import jakarta.persistence.EntityNotFoundException; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.concurrent.CompletableFuture; + +@Component +@Scope(value = BeanScope.REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) +public class BundleItemUpdateCommandHandler implements Handler { + private final BundleRepository repository; + + public BundleItemUpdateCommandHandler(BundleRepository repository) { + this.repository = repository; + } + + @Override + public CompletableFuture handleAsync(BundleItemUpdateCommand message, MessageContext context) { + var aggregate = repository.findByVanity(message.getVanity()); + if (aggregate == null) { + throw new EntityNotFoundException("Bundle not found for vanity: " + message.getVanity()); + } + + var userId = getUserId(); + var request = getRequest(); + + assert request != null; + + if (!aggregate.getOwnerId().equals(userId)) { + if (aggregate.getOwnerId() == null && request.isUserInRole("ADMIN")) { + throw new UnauthorizedAccessException("You are not allowed to complete this operation"); + } + } + + aggregate.updateItem(message.getItemId(), message.getTitle(), message.getDescription(), message.getImage()); + repository.save(aggregate, getUserId()); + return CompletableFuture.completedFuture(null); + } + + private HttpServletRequest getRequest() { + var request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + + if (request == null) { + return null; + } + + return request.getRequest(); + } + + private long getUserId() { + var request = getRequest(); + + if (request == null || request.getUserPrincipal() == null) { + return 0; + } + + return Long.parseLong(request.getUserPrincipal().getName()); + } +} diff --git a/bundle/src/main/java/io/theurl/bundle/application/implement/BundleApplicationServiceImpl.java b/bundle/src/main/java/io/theurl/bundle/application/implement/BundleApplicationServiceImpl.java index da8be99..da66c46 100644 --- a/bundle/src/main/java/io/theurl/bundle/application/implement/BundleApplicationServiceImpl.java +++ b/bundle/src/main/java/io/theurl/bundle/application/implement/BundleApplicationServiceImpl.java @@ -1,9 +1,7 @@ package io.theurl.bundle.application.implement; import com.neroyun.mediator.Event; -import io.theurl.bundle.application.command.BundleCreateCommand; -import io.theurl.bundle.application.command.BundleDeleteCommand; -import io.theurl.bundle.application.command.BundleUpdateCommand; +import io.theurl.bundle.application.command.*; import io.theurl.bundle.application.contract.BundleApplicationService; import io.theurl.bundle.application.dto.*; import io.theurl.bundle.persistence.query.BundleCountQuery; @@ -126,17 +124,22 @@ public void onComplete() { @Override public CompletableFuture appendItemAsync(String vanity, BundleItemEditDto data) { - return null; + var command = new BundleItemAppendCommand(vanity); + mapper.map(data, command); + return mediator.sendAsync(command); } @Override public CompletableFuture updateItemAsync(String vanity, long itemId, BundleItemEditDto data) { - return null; + var command = new BundleItemUpdateCommand(vanity, itemId); + mapper.map(data, command); + return mediator.sendAsync(command); } @Override public CompletableFuture removeItemAsync(String vanity, long itemId) { - return null; + var command = new BundleItemRemoveCommand(vanity, itemId); + return mediator.sendAsync(command); } @Override diff --git a/bundle/src/main/java/io/theurl/bundle/configure/SecurityConfiguration.java b/bundle/src/main/java/io/theurl/bundle/configure/SecurityConfiguration.java index 166d514..a2266f3 100644 --- a/bundle/src/main/java/io/theurl/bundle/configure/SecurityConfiguration.java +++ b/bundle/src/main/java/io/theurl/bundle/configure/SecurityConfiguration.java @@ -1,15 +1,22 @@ package io.theurl.bundle.configure; import io.theurl.framework.security.JwtAuthenticationFilter; +import jakarta.annotation.PostConstruct; +import jakarta.servlet.DispatcherType; import jakarta.servlet.http.HttpServletResponse; +import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; /** * The security configuration for the application, defining the security filter chain and authentication rules. @@ -23,18 +30,40 @@ @Configuration public class SecurityConfiguration { + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(java.util.List.of("*")); + configuration.setAllowedMethods(java.util.List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(java.util.List.of("*")); + configuration.setExposedHeaders(java.util.List.of("x-vanity", "Authorization", "Content-Type")); + configuration.setAllowCredentials(false); + configuration.setMaxAge(3600L); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticationFilter jwtAuthenticationFilter) { - http.csrf(AbstractHttpConfigurer::disable) + http.securityContext(securityContext -> securityContext.requireExplicitSave(false)) + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .exceptionHandling(ex -> ex.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"))) + .exceptionHandling(ex -> { + ex.authenticationEntryPoint((request, response, authException) -> { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); + }); + }) .authorizeHttpRequests(auth -> { - - auth.requestMatchers(HttpMethod.GET, "/api/bundle/**").permitAll() - .requestMatchers(HttpMethod.GET, "/api/bookmark/**").permitAll() + // More specific patterns must come before more general ones. + // Authenticated endpoints must be resolved before wildcard patterns. + auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/bookmark/my").authenticated() + .requestMatchers(HttpMethod.GET, "/api/bundle/**", "/api/bookmark/**", "/api/frequency/**").permitAll() .requestMatchers( "/v3/api-docs/**", "/swagger-ui/**", @@ -47,5 +76,20 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticat return http.build(); } -} + @PostConstruct + public void enableInheritableSecurityContext() { + SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); + } + + @Bean + public FilterRegistrationBean jwtFilterRegistration(JwtAuthenticationFilter jwtFilter) { + FilterRegistrationBean registration = new FilterRegistrationBean<>(); + registration.setFilter(jwtFilter); + registration.addUrlPatterns("/*"); + registration.setDispatcherTypes(DispatcherType.REQUEST); + //registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC); + registration.setOrder(1); + return registration; + } +} diff --git a/bundle/src/main/java/io/theurl/bundle/domain/aggregate/Bundle.java b/bundle/src/main/java/io/theurl/bundle/domain/aggregate/Bundle.java index 415bc9a..dd5f3bf 100644 --- a/bundle/src/main/java/io/theurl/bundle/domain/aggregate/Bundle.java +++ b/bundle/src/main/java/io/theurl/bundle/domain/aggregate/Bundle.java @@ -31,6 +31,7 @@ public Bundle(long id) { private String ownerName; private List items = new ArrayList<>(); private List comments = new ArrayList<>(); + private List labels = new ArrayList<>(); private BundleExtend extend; private boolean deleted; @@ -110,7 +111,7 @@ public List getComments() { public void appendItem(String url, String title, String description, String image) { if (items.stream().anyMatch(item -> item.getUrl().equals(url))) { - return; + throw new IllegalArgumentException("An item with the same URL already exists in the bundle."); } var item = BundleItem.create(url, title); item.setDescription(description); @@ -120,6 +121,13 @@ public void appendItem(String url, String title, String description, String imag extend.incrementItemCount(); } + public void updateItem(long itemId, String title, String description, String image) { + var item = items.stream().filter(i -> i.getId() == itemId).findFirst().orElseThrow(() -> new IllegalArgumentException("Item not found.")); + item.setTitle(title); + item.setDescription(description); + item.setImage(image); + } + public void removeItem(long id) { if (items.removeIf(item -> item.getId() == id)) { extend.decrementItemCount(); @@ -128,7 +136,19 @@ public void removeItem(long id) { public void clearItems() { items.clear(); - extend.setItemCount(0); + extend.setItemsCount(0); + } + + public List getLabels() { + return Collections.unmodifiableList(labels); + } + + public void addLabel(String label) { + labels.add(label); + } + + public void removeLabel(String label) { + labels.remove(label); } public BundleExtend getExtend() { diff --git a/bundle/src/main/java/io/theurl/bundle/domain/aggregate/BundleExtend.java b/bundle/src/main/java/io/theurl/bundle/domain/aggregate/BundleExtend.java index 8dc0686..c0bb957 100644 --- a/bundle/src/main/java/io/theurl/bundle/domain/aggregate/BundleExtend.java +++ b/bundle/src/main/java/io/theurl/bundle/domain/aggregate/BundleExtend.java @@ -15,18 +15,18 @@ public BundleExtend(long id) { super(id); } - private int itemCount; + private int itemsCount; private int favoriteCount; private int commentCount; private int visitCount; private LocalDateTime lastVisitedAt; - public int getItemCount() { - return itemCount; + public int getItemsCount() { + return itemsCount; } - public void setItemCount(int itemCount) { - this.itemCount = itemCount; + public void setItemsCount(int itemsCount) { + this.itemsCount = itemsCount; } public int getFavoriteCount() { @@ -62,7 +62,7 @@ public void setLastVisitedAt(LocalDateTime lastVisitedAt) { } public void incrementItemCount() { - this.itemCount++; + this.itemsCount++; } public void incrementFavoriteCount() { @@ -78,8 +78,8 @@ public void incrementVisitCount() { } public void decrementItemCount() { - if (this.itemCount > 0) { - this.itemCount--; + if (this.itemsCount > 0) { + this.itemsCount--; } } diff --git a/bundle/src/main/java/io/theurl/bundle/interfaces/controller/FrequencyController.java b/bundle/src/main/java/io/theurl/bundle/interfaces/controller/FrequencyController.java new file mode 100644 index 0000000..c21fb5e --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/interfaces/controller/FrequencyController.java @@ -0,0 +1,111 @@ +package io.theurl.bundle.interfaces.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.theurl.bundle.application.contract.BundleApplicationService; +import io.theurl.bundle.application.dto.BundleItemEditDto; +import io.theurl.bundle.application.dto.BundleItemListDto; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +/** + * Frequency endpoint for managing the current user's frequently used bundle items. + *

+ * The controller only handles HTTP routing and delegates all business behavior to + * {@link BundleApplicationService}. + */ +@RestController +@RequestMapping("/api/frequency") +public class FrequencyController { + + private final BundleApplicationService service; + + /** + * Creates a controller with the application service used for frequency operations. + * + * @param service bundle application service + */ + public FrequencyController(BundleApplicationService service) { + this.service = service; + } + + /** + * Returns all frequency items for the current user. + * + * @param request HTTP request used to resolve the current user's vanity key + * @return async list of frequency items + */ + @GetMapping("items") + @Operation(summary = "Get the frequency of items in the bundle", security = @SecurityRequirement(name = "bearerAuth")) + public CompletableFuture> fetchItemsAsync(HttpServletRequest request) { + Map criteria = Map.of("type", "frequency"); + + var vanity = getVanity(request); + return service.searchItemsAsync(vanity, criteria, 0, Integer.MAX_VALUE); + } + + /** + * Appends a new item into the current user's frequency list. + * + * @param request HTTP request used to resolve the current user's vanity key + * @param data item payload to append + * @return async completion signal + */ + @PostMapping("items") + @Operation(summary = "Append item to the frequency list", security = @SecurityRequirement(name = "bearerAuth")) + public CompletableFuture appendItemAsync(HttpServletRequest request, @RequestBody BundleItemEditDto data) { + var vanity = getVanity(request); + return service.appendItemAsync(vanity, data); + } + + /** + * Updates one item in the current user's frequency list. + * + * @param request HTTP request used to resolve the current user's vanity key + * @param itemId target item id + * @param data updated item payload + * @return async completion signal + */ + @PutMapping("items/{itemId}") + @Operation(summary = "Update an item in the frequency list", security = @SecurityRequirement(name = "bearerAuth")) + public CompletableFuture updateItemAsync(HttpServletRequest request, @PathVariable long itemId, @RequestBody BundleItemEditDto data) { + var vanity = getVanity(request); + return service.updateItemAsync(vanity, itemId, data); + } + + /** + * Removes one item from the current user's frequency list. + * + * @param request HTTP request used to resolve the current user's vanity key + * @param itemId target item id + * @return async completion signal + */ + @DeleteMapping("items/{itemId}") + @Operation(summary = "Delete an item from the frequency list", security = @SecurityRequirement(name = "bearerAuth")) + public CompletableFuture removeItemAsync(HttpServletRequest request, @PathVariable long itemId) { + var vanity = getVanity(request); + return service.removeItemAsync(vanity, itemId); + } + + /** + * Builds the user's frequency bundle vanity. + *

+ * Falls back to a system vanity if user identity is absent. + * + * @param request HTTP request carrying authenticated principal + * @return vanity key used by frequency bundle storage + */ + private String getVanity(HttpServletRequest request) { + var userId = request.getUserPrincipal().getName(); + if (StringUtils.hasText(userId)) { + return "frequency-" + userId; + } else { + return "frequency-system"; + } + } +} diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/entity/Bundle.java b/bundle/src/main/java/io/theurl/bundle/persistence/entity/Bundle.java index 0852bc1..5559317 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/entity/Bundle.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/entity/Bundle.java @@ -48,12 +48,12 @@ public class Bundle implements Persistable { @Column(name = "created_at") private LocalDateTime createdAt; - @Column(name = "updated_at") - private LocalDateTime updatedAt; - @Column(name = "created_by") private long createdBy; + @Column(name = "updated_at") + private LocalDateTime updatedAt; + @Column(name = "updated_by") private long updatedBy; @@ -72,6 +72,9 @@ public class Bundle implements Persistable { @OneToMany(mappedBy = "bundle", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) private Collection comments; + @OneToMany(mappedBy = "bundle", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) + private Collection labels; + @OneToOne(mappedBy = "bundle", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) private BundleExtend extend; diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleItem.java b/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleItem.java index 9a77f68..bf9ebbc 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleItem.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleItem.java @@ -5,6 +5,8 @@ import org.jspecify.annotations.Nullable; import org.springframework.data.domain.Persistable; +import java.time.LocalDateTime; + @Data @Entity @Table(name = "bundle_item", indexes = { @@ -19,13 +21,13 @@ public class BundleItem implements Persistable { @Column(name = "bundle_id", nullable = false, updatable = false) private long bundleId; - @Column(name = "url", nullable = false, updatable = false) + @Column(name = "url", nullable = false, updatable = false, columnDefinition = "text") private String url; @Column(name = "title", nullable = false) private String title; - @Column(name = "description", length = 1000) + @Column(name = "description", columnDefinition = "text") private String description; @Column(name = "image", length = 500) @@ -34,6 +36,12 @@ public class BundleItem implements Persistable { @Column(name = "order", nullable = false) private int order; + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "bundle_id", insertable = false, updatable = false) private Bundle bundle; diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleLabel.java b/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleLabel.java new file mode 100644 index 0000000..b44d4e6 --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/persistence/entity/BundleLabel.java @@ -0,0 +1,36 @@ +package io.theurl.bundle.persistence.entity; + +import jakarta.persistence.*; +import lombok.Data; +import org.jspecify.annotations.Nullable; +import org.springframework.data.domain.Persistable; + +@Entity +@Data +@Table(name = "bundle_label", indexes = { + @Index(name = "idx_bundle_label_unique", columnList = "bundle_id,name") +}) +public class BundleLabel implements Persistable { + @Id + private Long id; + + @Column(name = "bundle_id", nullable = false, updatable = false) + private long bundleId; + + @Column(name = "name", nullable = false, updatable = false, length = 50) + private String name; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "bundle_id", insertable = false, updatable = false) + private Bundle bundle; + + @Override + public @Nullable Long getId() { + return id; + } + + @Override + public boolean isNew() { + return false; + } +} diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleCountQueryHandler.java b/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleCountQueryHandler.java index ea31a58..4e15324 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleCountQueryHandler.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleCountQueryHandler.java @@ -45,7 +45,8 @@ public CompletableFuture handleAsync(BundleCountQuery message, MessageC predicates.add(orGroup); } } - default -> predicates.add(builder.equal(select.get(key), value)); + default -> { + } } }); diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleItemCountQueryHandler.java b/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleItemCountQueryHandler.java index 1207f3b..51b2b10 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleItemCountQueryHandler.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleItemCountQueryHandler.java @@ -4,7 +4,6 @@ import com.neroyun.mediator.MessageContext; import io.theurl.bundle.persistence.entity.Bundle; import io.theurl.bundle.persistence.entity.BundleItem; -import io.theurl.bundle.persistence.model.BundleItemModel; import io.theurl.bundle.persistence.query.BundleItemCountQuery; import io.theurl.framework.core.BeanScope; import jakarta.persistence.EntityManager; diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleListQueryHandler.java b/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleListQueryHandler.java index 316f03c..c20c362 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleListQueryHandler.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/handler/BundleListQueryHandler.java @@ -52,7 +52,9 @@ public CompletableFuture> handleAsync(BundleListQuery mess predicates.add(orGroup); } } - default -> predicates.add(builder.equal(select.get(k), v)); + default -> { + //predicates.add(builder.equal(select.get(k), v)); + } } }); diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/profile/BundleMapProfile.java b/bundle/src/main/java/io/theurl/bundle/persistence/profile/BundleMapProfile.java index efe8ce9..b414d03 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/profile/BundleMapProfile.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/profile/BundleMapProfile.java @@ -1,13 +1,20 @@ package io.theurl.bundle.persistence.profile; -import io.theurl.bundle.persistence.entity.Bundle; +import io.theurl.bundle.persistence.entity.BundleItem; +import io.theurl.bundle.persistence.entity.BundleLabel; import io.theurl.bundle.persistence.model.BundleListModel; +import io.theurl.framework.utility.SnowflakeId; import jakarta.annotation.PostConstruct; import org.modelmapper.ModelMapper; -import org.modelmapper.Provider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Objects; +import java.util.function.Function; + @Component public class BundleMapProfile { @Autowired @@ -15,90 +22,156 @@ public class BundleMapProfile { @PostConstruct public void configure() { - Provider provider = request -> { - var source = request.getSource(); - Long id; + // entity.Bundle → domain.Bundle + // Uses setConverter (not setProvider + addMappings) to prevent ModelMapper from + // auto-mapping the 'extend' field via PRIVATE field access, which would try to + // instantiate domain.BundleExtend — a class with no no-arg constructor. + mapper.createTypeMap(io.theurl.bundle.persistence.entity.Bundle.class, io.theurl.bundle.domain.aggregate.Bundle.class) + .setConverter(ctx -> { + var src = ctx.getSource(); + assert src.getId() != null; + var dest = new io.theurl.bundle.domain.aggregate.Bundle(src.getId()); + setValue(dest, "type", src.getType()); + setValue(dest, "vanity", src.getVanity()); + setValue(dest, "ownerId", src.getOwnerId()); + setValue(dest, "ownerName", src.getOwnerName()); + dest.setName(src.getName()); + dest.setDescription(src.getDescription()); + dest.setImage(src.getImage()); + dest.setOrder(src.getOrder()); + var extend = src.getExtend(); + if (extend != null) { + dest.getExtend().setItemsCount(extend.getItemsCount()); + dest.getExtend().setFavoriteCount(extend.getFavoriteCount()); + dest.getExtend().setCommentCount(extend.getCommentCount()); + dest.getExtend().setVisitCount(extend.getVisitCount()); + dest.getExtend().setLastVisitedAt(extend.getLastVisitedAt()); + } - if (source instanceof io.theurl.bundle.domain.aggregate.Bundle entity) { - id = entity.getId(); - } else { - try { - var field = source.getClass().getDeclaredField("id"); - field.setAccessible(true); - id = (Long) field.get(source); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException("Failed to create provider for Bundle", e); - } - } + setCollection(dest, "comments", src.getComments(), comment -> { + var destComment = new io.theurl.bundle.domain.aggregate.BundleComment(Objects.requireNonNull(comment.getId())); + destComment.setAuthorId(comment.getAuthorId()); + destComment.setAuthorName(comment.getAuthorName()); + destComment.setContent(comment.getContent()); + destComment.setContact(comment.getContact()); + destComment.setCreatedAt(comment.getCreatedAt()); + return destComment; + }); - return new io.theurl.bundle.domain.aggregate.Bundle(id); - }; + setCollection(dest, "items", src.getItems(), item -> { + var destItem = new io.theurl.bundle.domain.aggregate.BundleItem(Objects.requireNonNull(item.getId())); + destItem.setUrl(item.getUrl()); + destItem.setTitle(item.getTitle()); + destItem.setDescription(item.getDescription()); + destItem.setImage(item.getImage()); + return destItem; + }); - mapper.createTypeMap(io.theurl.bundle.persistence.entity.Bundle.class, io.theurl.bundle.domain.aggregate.Bundle.class) - .setProvider(provider) - .addMappings(expression -> { -// expression.map(Bundle::getType, (dest, value) -> setValue(dest, "type", value)); -// expression.map(Bundle::getVanity, (dest, value) -> setValue(dest, "vanity", value)); -// expression.map(Bundle::getOwnerId, (dest, value) -> setValue(dest, "ownerId", value)); -// expression.map(Bundle::getOwnerName, (dest, value) -> setValue(dest, "ownerName", value)); - expression.map(Bundle::getName, io.theurl.bundle.domain.aggregate.Bundle::setName); - expression.map(Bundle::getDescription, io.theurl.bundle.domain.aggregate.Bundle::setDescription); - expression.map(Bundle::getImage, io.theurl.bundle.domain.aggregate.Bundle::setImage); - expression.map(Bundle::getOrder, io.theurl.bundle.domain.aggregate.Bundle::setOrder); -// expression.map(Bundle::getItems, (dest, value) -> { -// if(dest != null && value != null) { -// var items = dest.getItems(); -// items.add(mapper.map(value, io.theurl.bundle.domain.aggregate.BundleItem.class)); -// } -// }); -// expression.map(Bundle::getComments, (dest, value) -> { -// if (dest == null || value == null) { -// return; -// } -// var comments = dest.getComments(); -// comments.add(mapper.map(value, io.theurl.bundle.domain.aggregate.BundleComment.class)); -// }); -// expression.map(Bundle::getExtend, (dest, value) -> { -// if (dest == null || value == null) { -// return; -// } -// var extend = (io.theurl.bundle.domain.aggregate.BundleExtend) value; -// dest.getExtend().setItemCount(extend.getItemCount()); -// dest.getExtend().setCommentCount(extend.getCommentCount()); -// dest.getExtend().setFavoriteCount(extend.getFavoriteCount()); -// dest.getExtend().setFavoriteCount(extend.getFavoriteCount()); -// dest.getExtend().setLastVisitedAt(extend.getLastVisitedAt()); -// }); + setCollection(dest, "labels", src.getLabels(), BundleLabel::getName); + + return dest; }); + // entity.Bundle → BundleListModel + // Direct fields (id, type, vanity, name, …) are auto-mapped; extend fields + // are copied in setPostConverter since BundleListModel has no 'extend' field + // so ModelMapper never attempts to deep-map into it. mapper.createTypeMap(io.theurl.bundle.persistence.entity.Bundle.class, BundleListModel.class) + .setPostConverter(ctx -> { + var src = ctx.getSource(); + var dest = ctx.getDestination(); + var extend = src.getExtend(); + if (extend != null) { + dest.setItemsCount(extend.getItemsCount()); + dest.setFavoriteCount(extend.getFavoriteCount()); + dest.setCommentCount(extend.getCommentCount()); + dest.setVisitCount(extend.getVisitCount()); + } + return dest; + }); + + mapper.createTypeMap(io.theurl.bundle.domain.aggregate.Bundle.class, io.theurl.bundle.persistence.entity.Bundle.class) .addMappings(expression -> { - expression.map(src -> src.getExtend().getItemsCount(), BundleListModel::setItemsCount); - expression.map(src -> src.getExtend().getFavoriteCount(), BundleListModel::setFavoriteCount); - expression.map(src -> src.getExtend().getCommentCount(), BundleListModel::setCommentCount); - expression.map(src -> src.getExtend().getVisitCount(), BundleListModel::setVisitCount); + expression.skip(io.theurl.bundle.persistence.entity.Bundle::setComments); + expression.skip(io.theurl.bundle.persistence.entity.Bundle::setItems); + }) + .setPostConverter(ctx -> { + var src = ctx.getSource(); + var dest = ctx.getDestination(); + if (dest.getItems() == null) { + dest.setItems(new HashSet<>()); + } + if (dest.getComments() == null) { + dest.setComments(new HashSet<>()); + } + for (var item : src.getItems()) { + var destItem = dest.getItems().stream().filter(i -> { + assert i.getId() != null; + return i.getId().equals(item.getId()); + }).findFirst().orElse(null); + if (destItem == null) { + destItem = new BundleItem(); + destItem.setId(item.getId()); + destItem.setBundleId(Objects.requireNonNull(dest.getId())); + dest.getItems().add(destItem); + } + destItem.setUrl(item.getUrl()); + destItem.setTitle(item.getTitle()); + destItem.setDescription(item.getDescription()); + destItem.setImage(item.getImage()); + destItem.setOrder(item.getOrder()); + } + for (var comment : src.getComments()) { + var destComment = dest.getComments().stream().filter(c -> { + assert c.getId() != null; + return c.getId().equals(comment.getId()); + }).findFirst().orElse(null); + if (destComment == null) { + destComment = new io.theurl.bundle.persistence.entity.BundleComment(); + destComment.setId(comment.getId()); + destComment.setAuthorId(comment.getAuthorId()); + destComment.setAuthorName(comment.getAuthorName()); + destComment.setContent(comment.getContent()); + destComment.setContact(comment.getContact()); + destComment.setCreatedAt(comment.getCreatedAt()); + dest.getComments().add(destComment); + } + } + for (var label : src.getLabels()) { + var entity = dest.getLabels().stream().filter(l -> l.getName().equals(label)).findFirst().orElse(null); + if (entity == null) { + var destLabel = new BundleLabel(); + destLabel.setId(SnowflakeId.getInstance().nextId()); + destLabel.setName(label); + dest.getLabels().add(destLabel); + } + } + return dest; }); } - /** - * Set value to the field of the destination object using reflection. - * This is necessary because some fields in the domain aggregate are not directly mapped from the entity, but need to be set manually after mapping. - * - * @param bundle the destination bundle object - * @param name the name of the field to set - * @param value the value to set - */ private void setValue(io.theurl.bundle.domain.aggregate.Bundle bundle, String name, Object value) { try { - if (value == null || bundle == null) { - return; - } - var field = bundle.getClass().getSuperclass().getDeclaredField(name); + var field = io.theurl.bundle.domain.aggregate.Bundle.class.getDeclaredField(name); field.setAccessible(true); field.set(bundle, value); } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException(e); + System.err.println(e.getMessage()); + } + } + + private void setCollection(io.theurl.bundle.domain.aggregate.Bundle bundle, String name, Collection source, Function convert) { + try { + var field = io.theurl.bundle.domain.aggregate.Bundle.class.getDeclaredField(name); + field.setAccessible(true); + var list = new ArrayList(); + for (var item : source) { + list.add(convert.apply(item)); + } + field.set(bundle, list); + } catch (NoSuchFieldException | IllegalAccessException e) { + System.err.println(e.getMessage()); } } } diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/repository/BundleRepositoryImpl.java b/bundle/src/main/java/io/theurl/bundle/persistence/repository/BundleRepositoryImpl.java index c14c778..02566c6 100644 --- a/bundle/src/main/java/io/theurl/bundle/persistence/repository/BundleRepositoryImpl.java +++ b/bundle/src/main/java/io/theurl/bundle/persistence/repository/BundleRepositoryImpl.java @@ -1,7 +1,7 @@ package io.theurl.bundle.persistence.repository; -import io.theurl.bundle.domain.aggregate.Bundle; import io.theurl.bundle.domain.repository.BundleRepository; +import io.theurl.bundle.persistence.entity.Bundle; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Repository; @@ -18,12 +18,15 @@ public BundleRepositoryImpl(JpaBundleRepository repository, ModelMapper mapper) } @Override - public void save(Bundle bundle, long operatorId) { + public void save(io.theurl.bundle.domain.aggregate.Bundle bundle, long operatorId) { var entity = repository.findById(bundle.getId()) .orElse(null); if (entity == null) { - entity = mapper.map(bundle, io.theurl.bundle.persistence.entity.Bundle.class); + entity = mapper.map(bundle, Bundle.class); entity.setCreatedBy(operatorId); + entity.setUpdatedBy(operatorId); + entity.setCreatedAt(LocalDateTime.now()); + entity.setUpdatedAt(LocalDateTime.now()); } else if (bundle.isDeleted()) { entity.setDeleted(true); entity.setDeletedBy(operatorId); @@ -31,27 +34,28 @@ public void save(Bundle bundle, long operatorId) { } else { mapper.map(bundle, entity); entity.setUpdatedBy(operatorId); + entity.setUpdatedAt(LocalDateTime.now()); } repository.save(entity); } @Override - public Bundle findById(Long id) { + public io.theurl.bundle.domain.aggregate.Bundle findById(Long id) { var entity = repository.findById(id).orElse(null); if (entity == null) { return null; } - return mapper.map(entity, Bundle.class); + return mapper.map(entity, io.theurl.bundle.domain.aggregate.Bundle.class); } @Override - public Bundle findByVanity(String vanity) { + public io.theurl.bundle.domain.aggregate.Bundle findByVanity(String vanity) { var entity = repository.findByVanity(vanity) .orElse(null); if (entity == null || entity.isDeleted()) { return null; } - return mapper.map(entity, Bundle.class); + return mapper.map(entity, io.theurl.bundle.domain.aggregate.Bundle.class); } } diff --git a/bundle/src/main/java/io/theurl/bundle/persistence/repository/JpaBundleItemRepository.java b/bundle/src/main/java/io/theurl/bundle/persistence/repository/JpaBundleItemRepository.java new file mode 100644 index 0000000..5a811da --- /dev/null +++ b/bundle/src/main/java/io/theurl/bundle/persistence/repository/JpaBundleItemRepository.java @@ -0,0 +1,49 @@ +package io.theurl.bundle.persistence.repository; + +import io.theurl.bundle.persistence.entity.BundleItem; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@SuppressWarnings("SqlNoDataSourceInspection") +@Repository +public interface JpaBundleItemRepository extends CrudRepository { + + /** + * Finds a BundleItem by its ID and the vanity of its associated Bundle, ensuring the Bundle is not marked as deleted. + * + * @param vanity The vanity string of the associated Bundle. + * @param itemId The ID of the BundleItem. + * @return The BundleItem matching the given ID and vanity, or null if not found. + */ + @Query("SELECT bi FROM BundleItem bi JOIN bi.bundle b WHERE b.vanity = :vanity AND b.deleted = false AND bi.id = :itemId") + Optional findByVanity(String vanity, long itemId); + + /** + * Finds a BundleItem by its ID and the ID of its associated Bundle, ensuring the Bundle is not marked as deleted. + * + * @param bundleId The ID of the associated Bundle. + * @param itemId The ID of the BundleItem. + * @return The BundleItem matching the given IDs, or null if not found. + */ + @Query("SELECT bi FROM BundleItem bi JOIN bi.bundle b WHERE b.id = :bundleId AND b.deleted = false AND bi.id = :itemId") + Optional findByBundleId(Long bundleId, long itemId); + + /** + * Fetches the top N items for each bundle ID in the provided list, ordered by their 'order' field in descending order. + * + * @param bundleIds The list of bundle IDs to fetch items for. + * @param limit The maximum number of items to fetch for each bundle. + * @return A list of top items for each bundle. + */ + @Query(value = """ + SELECT sub.* FROM ( + SELECT itm.*, ROW_NUMBER() OVER(PARTITION BY itm.bundle_id ORDER BY itm.order DESC) AS row_num FROM bundle_item AS itm WHERE itm.bundle_id IN (:bundleIds) + ) AS sub + WHERE sub.row_num <= :limit ORDER BY sub.bundle_id ASC, sub.order DESC + """, nativeQuery = true) + List getTopItems(List bundleIds, int limit); +} diff --git a/bundle/src/main/resources/application.yaml b/bundle/src/main/resources/application.yaml index c219742..8009de1 100644 --- a/bundle/src/main/resources/application.yaml +++ b/bundle/src/main/resources/application.yaml @@ -1,17 +1,19 @@ server: - port: 8903 + port: 8903 spring: profiles: active: ${SPRING_PROFILES_ACTIVE:dev} application: - name: identity + name: bundle config: - import: optional:file:.env[.properties] + import: optional:configserver:${CONFIG_SERVER_URI:http://localhost:8900/env} cloud: config: - enabled: false - uri: ${CONFIG_SERVER_URI:http://localhost:8900} + enabled: true + uri: ${CONFIG_SERVER_URI:http://localhost:8900/env} + label: master + profile: ${SPRING_PROFILES_ACTIVE:dev} datasource: url: ${DB_URL:jdbc:postgresql://localhost:5432/linkyou?currentSchema=public} username: ${DB_USERNAME:postgres} @@ -30,8 +32,6 @@ spring: data: redis: url: ${REDIS_URL:redis://localhost:6379} - mongodb: - uri: ${MONGO_URI:mongodb://localhost:27017/linkyou} web: error: include-message: ALWAYS @@ -58,6 +58,9 @@ external-auth: client-id: ${MICROSOFT_CLIENT_ID:your-microsoft-client-id} client-secret: ${MICROSOFT_CLIENT_SECRET:your-microsoft-client-secret} +# JWT Configuration +# IMPORTANT: Set JWT_SECRET environment variable in production to a strong random 32+ character string +# Example: export JWT_SECRET="your-super-secret-key-at-least-32-characters-long-for-safety" jwt: secret: ${JWT_SECRET:your-jwt-secret} issuer: theurl.io @@ -68,6 +71,7 @@ logging: name: #{level}-{T(java.time.LocalDate).now()}.log path: logs level: - io.theurl.identity: debug + io.theurl.bundle: debug + io.theurl.framework.security: debug org.springframework: debug root: info diff --git a/config/pom.xml b/config/pom.xml index 290789c..df86e2b 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -5,7 +5,7 @@ io.theurl parent - 1.0 + ${revision} ../pom.xml diff --git a/framework/pom.xml b/framework/pom.xml index 17ab861..4b0c747 100644 --- a/framework/pom.xml +++ b/framework/pom.xml @@ -6,7 +6,7 @@ io.theurl parent - 1.0 + ${revision} ../pom.xml diff --git a/framework/src/main/java/io/theurl/framework/configure/MediatorConfiguration.java b/framework/src/main/java/io/theurl/framework/configure/MediatorConfiguration.java index 225c069..81c18a7 100644 --- a/framework/src/main/java/io/theurl/framework/configure/MediatorConfiguration.java +++ b/framework/src/main/java/io/theurl/framework/configure/MediatorConfiguration.java @@ -1,21 +1,14 @@ package io.theurl.framework.configure; import com.neroyun.mediator.*; -import org.slf4j.MDC; import org.springframework.beans.factory.ObjectProvider; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.event.SimpleApplicationEventMulticaster; -import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.core.task.TaskDecorator; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.RequestContextListener; -import java.util.Map; import java.util.concurrent.CompletableFuture; @SuppressWarnings("rawtypes") diff --git a/framework/src/main/java/io/theurl/framework/security/JwtAuthenticationFilter.java b/framework/src/main/java/io/theurl/framework/security/JwtAuthenticationFilter.java index f37e9b8..fa80cd8 100644 --- a/framework/src/main/java/io/theurl/framework/security/JwtAuthenticationFilter.java +++ b/framework/src/main/java/io/theurl/framework/security/JwtAuthenticationFilter.java @@ -46,6 +46,11 @@ protected void doFilterInternal(HttpServletRequest request, if (authHeader != null && authHeader.startsWith("Bearer ") && SecurityContextHolder.getContext().getAuthentication() == null) { String token = authHeader.substring(7); try { + // Validate signing key is configured + if (signingKey == null || signingKey.isBlank()) { + LOGGER.warn("JWT signing key is not properly configured. Using default or empty key."); + } + var claims = Jwts.parser() .verifyWith(Keys.hmacShaKeyFor(signingKey.getBytes(StandardCharsets.UTF_8))) .build() @@ -57,14 +62,31 @@ protected void doFilterInternal(HttpServletRequest request, var authentication = new UsernamePasswordAuthenticationToken(userId, null, Collections.emptyList()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); + LOGGER.debug("JWT authentication successful for user: {}", userId); + } else { + LOGGER.debug("JWT token has no subject (userId)"); } - } catch (Exception e) { + } catch (io.jsonwebtoken.security.SignatureException e) { // Don't throw an exception when token parsing fails, let the subsequent authentication process handle it and return 401. + LOGGER.debug("JWT signature validation failed: {}", e.getMessage()); + } catch (io.jsonwebtoken.ExpiredJwtException e) { + LOGGER.debug("JWT token has expired: {}", e.getMessage()); + } catch (io.jsonwebtoken.MalformedJwtException e) { + LOGGER.debug("JWT token is malformed: {}", e.getMessage()); + } catch (Exception e) { LOGGER.debug("JWT parse failed: {}", e.getMessage()); } + } else if (authHeader == null) { + LOGGER.trace("No Authorization header found in request"); + } else if (!authHeader.startsWith("Bearer ")) { + LOGGER.debug("Authorization header does not start with 'Bearer '"); } filterChain.doFilter(request, response); } -} +// @Override +// protected boolean shouldNotFilterAsyncDispatch() { +// return false; +// } +} diff --git a/identity/pom.xml b/identity/pom.xml index 5689fbb..2928aa0 100644 --- a/identity/pom.xml +++ b/identity/pom.xml @@ -5,7 +5,7 @@ io.theurl parent - 1.0 + ${revision} ../pom.xml identity diff --git a/identity/src/main/java/io/theurl/identity/application/implement/AuthApplicationServiceImpl.java b/identity/src/main/java/io/theurl/identity/application/implement/AuthApplicationServiceImpl.java index 31146b5..ddd2878 100644 --- a/identity/src/main/java/io/theurl/identity/application/implement/AuthApplicationServiceImpl.java +++ b/identity/src/main/java/io/theurl/identity/application/implement/AuthApplicationServiceImpl.java @@ -262,8 +262,8 @@ public Map getDetails() { */ private String generateToken(String id, UserAuthInfo user, Date issuedAt, Date expiresAt) { Assert.notNull(user, "user cannot be null"); - //var signingKey = environment.getProperty("JwtAuthenticationOptions.SigningKey"); Assert.notNull(signingKey, "SigningKey cannot be null"); + Assert.isTrue(signingKey.length() >= 32, "SigningKey must be at least 32 characters for HMAC-SHA-256"); var builder = Jwts.builder(); builder.subject(String.valueOf(user.getId())).id(id) @@ -278,7 +278,7 @@ private String generateToken(String id, UserAuthInfo user, Date issuedAt, Date e } } - builder.signWith(Keys.hmacShaKeyFor(signingKey.getBytes())); + builder.signWith(Keys.hmacShaKeyFor(signingKey.getBytes(java.nio.charset.StandardCharsets.UTF_8))); return builder.compact(); } diff --git a/identity/src/main/resources/application.yaml b/identity/src/main/resources/application.yaml index 141d6a4..148b062 100644 --- a/identity/src/main/resources/application.yaml +++ b/identity/src/main/resources/application.yaml @@ -52,6 +52,9 @@ external-auth: client-id: ${MICROSOFT_CLIENT_ID:your-microsoft-client-id} client-secret: ${MICROSOFT_CLIENT_SECRET:your-microsoft-client-secret} +# JWT Configuration +# IMPORTANT: Set JWT_SECRET environment variable in production to a strong random 32+ character string +# Example: export JWT_SECRET="your-super-secret-key-at-least-32-characters-long-for-safety" jwt: secret: ${JWT_SECRET:your-jwt-secret} issuer: theurl.io diff --git a/message/pom.xml b/message/pom.xml index fe0cede..d3c04ee 100644 --- a/message/pom.xml +++ b/message/pom.xml @@ -5,7 +5,7 @@ io.theurl parent - 1.0 + ${revision} ../pom.xml message diff --git a/pom.xml b/pom.xml index 26e2473..824be07 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ io.theurl parent - 1.0 + ${revision} pom @@ -23,6 +23,7 @@ identity shared message + analysis @@ -40,9 +41,10 @@ + 1.0.0 25 25 - 1.0 + ${revision} UTF-8 UTF-8 25 diff --git a/shared/pom.xml b/shared/pom.xml index 049686a..f30eecb 100644 --- a/shared/pom.xml +++ b/shared/pom.xml @@ -6,7 +6,7 @@ io.theurl parent - 1.0 + ${revision} ../pom.xml