diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..373452688ab6c96ae53c1b53f19069c76eea049b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +/mvnw text eol=lf +*.cmd text eol=crlf \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..c0bcafe984fe33005eacbcfabe8b188e0f75afcd --- /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/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..680d62d948f5df847b9ff0e5e53d06fa64468cbe --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM maven:3.9.6-eclipse-temurin-17 AS build +WORKDIR /app +COPY pom.xml . +COPY src ./src +RUN mvn clean package -DskipTests + + +FROM eclipse-temurin:17-jre-alpine +WORKDIR /app + + +COPY --from=build /app/target/*.jar app.jar + +EXPOSE 7860 + +# Run the jar +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..bd8896bf2217b46faa0291585e01ac1a3441a958 --- /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 0000000000000000000000000000000000000000..3652a1be190e1cabaf663a0168c03d3747e55d9b --- /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 - userDTO 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 new file mode 100644 index 0000000000000000000000000000000000000000..2a1b5793bfd4b95a2c484195b0216fca0254d1c0 --- /dev/null +++ b/pom.xml @@ -0,0 +1,167 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.6 + + + edu.alexu + fitfinder + 0.0.1-SNAPSHOT + FItFinder + Demo project for Spring Boot + + + + + + + + + + + + + + + 17 + 17 + 17 + 21 + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-data-jpa + + + me.paulschwarz + spring-dotenv + 4.0.0 + + + org.mindrot + jbcrypt + 0.4 + + + commons-validator + commons-validator + 1.10.0 + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + + + org.springframework.boot + spring-boot-starter-security + + + com.cloudinary + cloudinary-http5 + 2.0.0 + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-websocket + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + 17 + 17 + 17 + + + org.projectlombok + lombok + 1.18.34 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/edu/alexu/fitfinder/FitFinderApplication.java b/src/main/java/edu/alexu/fitfinder/FitFinderApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..4fa0ef0aefd896050660621ef1d65c88ed1e8046 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/FitFinderApplication.java @@ -0,0 +1,12 @@ +package edu.alexu.fitfinder; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication + +public class FitFinderApplication { + public static void main(String[] args) { + SpringApplication.run(FitFinderApplication.class, args); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/component/JobRegistry.java b/src/main/java/edu/alexu/fitfinder/component/JobRegistry.java new file mode 100644 index 0000000000000000000000000000000000000000..dc830db60b803103ab5b58232067117bedd6630f --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/component/JobRegistry.java @@ -0,0 +1,26 @@ +package edu.alexu.fitfinder.component; + +import org.springframework.stereotype.Component; +import org.springframework.web.socket.WebSocketSession; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class JobRegistry { + + private final ConcurrentHashMap jobToSession = + new ConcurrentHashMap<>(); + + public void registerJob(String jobId, WebSocketSession session) { + System.out.println("Job " + jobId + " has been registered with session " + session.getId()); + jobToSession.put(jobId, session); + } + + public WebSocketSession getSession(String jobId) { + return jobToSession.get(jobId); + } + + public void removeJob(String jobId) { + System.out.println("The websocket session is no longer registered with job " + jobId); + jobToSession.remove(jobId); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/configs/CloudinaryConfig.java b/src/main/java/edu/alexu/fitfinder/configs/CloudinaryConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..26261117595e3b54b1f371d839667985d23b244c --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/configs/CloudinaryConfig.java @@ -0,0 +1,18 @@ +package edu.alexu.fitfinder.configs; + +import com.cloudinary.Cloudinary; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CloudinaryConfig { + + @Value("${cloudinary.url}") + private String cloudinaryUrl; + + @Bean + public Cloudinary cloudinary() { + return new Cloudinary(cloudinaryUrl); + } +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/configs/JwtAuthenticationFilter.java b/src/main/java/edu/alexu/fitfinder/configs/JwtAuthenticationFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..cc86a6a1d1ec583cb2a1add32097a014fd25bf7a --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/configs/JwtAuthenticationFilter.java @@ -0,0 +1,60 @@ +package edu.alexu.fitfinder.configs; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import org.springframework.lang.NonNull; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import edu.alexu.fitfinder.service.JwtService; +import java.io.IOException; +import java.util.List; + +@AllArgsConstructor +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtService jwtService; + + @Override + protected void doFilterInternal( + @NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain) + throws ServletException, IOException { + + final String authHeader = request.getHeader("Authorization"); + + if (authHeader == null || !authHeader.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + + final String jwt = authHeader.substring(7); + final String userId = jwtService.extractUserId(jwt); + + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (userId != null && authentication == null) { + UserDetails userDetails = + new User(userId, "", List.of(new SimpleGrantedAuthority("GENERAL"))); + + if (!jwtService.isTokenExpired(jwt)) { + UsernamePasswordAuthenticationToken authToken = + new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authToken); + } + } + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/configs/SecurityConfig.java b/src/main/java/edu/alexu/fitfinder/configs/SecurityConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..b0f388442b25360b1b3fe0617824ec26b11ac5ed --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/configs/SecurityConfig.java @@ -0,0 +1,85 @@ +package edu.alexu.fitfinder.configs; + +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfig { + + @Autowired private JwtAuthenticationFilter authFilter; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.csrf(AbstractHttpConfigurer::disable) + .cors( + cors -> + cors.configurationSource( + request -> { + var corsConfiguration = new org.springframework.web.cors.CorsConfiguration(); + // Allow common frontend origins (GitHub Pages, local dev) and ngrok domain + corsConfiguration.setAllowedOriginPatterns( + List.of( + "https://*.github.io", + "https://*.githubusercontent.com", + "http://localhost:*", + "http://127.0.0.1:*", + "http://192.168.*.*", + "https://*.ngrok-free.dev", + "https://*.ngrok-free.app", + "https://telescopic-ungodlily-wilbert.ngrok-free.dev" + )); + corsConfiguration.setAllowCredentials(true); // allow cookies/authorization + corsConfiguration.setAllowedMethods( + List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + corsConfiguration.setAllowedHeaders(List.of("*")); + corsConfiguration.setExposedHeaders(List.of("*")); + return corsConfiguration; + })) + .authorizeHttpRequests( + auth -> + auth.requestMatchers( + "/api/v1/auth/**", + "/api/v1/items/**", + "/api/v1/favorites/**", + "/segment/upload", + "/re-segment", + "/segmentation/callback", + "/ws" + ) + .permitAll() + .anyRequest() + .authenticated()) + .sessionManagement( + session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No sessions + ) + .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); // Password encoding + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration config) + throws Exception { + return config.getAuthenticationManager(); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/configs/WebSocketConfig.java b/src/main/java/edu/alexu/fitfinder/configs/WebSocketConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..648a8356e0d5b25f7664a5169117aeddc1a2fdb0 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/configs/WebSocketConfig.java @@ -0,0 +1,17 @@ +package edu.alexu.fitfinder.configs; + +import edu.alexu.fitfinder.handler.MyWebSocketHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Bean; +import org.springframework.web.socket.config.annotation.*; +import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; + +@Configuration +@EnableWebSocket +public class WebSocketConfig implements WebSocketConfigurer { + + @Override + public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { + registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOriginPatterns("*"); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/controller/FavoriteController.java b/src/main/java/edu/alexu/fitfinder/controller/FavoriteController.java new file mode 100644 index 0000000000000000000000000000000000000000..179bb25703908148e09c7c14d31fba0f7f0f431c --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/controller/FavoriteController.java @@ -0,0 +1,88 @@ +package edu.alexu.fitfinder.controller; + +import edu.alexu.fitfinder.dto.ItemDTO; +import edu.alexu.fitfinder.exception.FavoriteNotFoundException; +import edu.alexu.fitfinder.exception.ItemNotFoundException; +import edu.alexu.fitfinder.exception.UserNotFoundException; +import edu.alexu.fitfinder.service.FavoriteService; +import edu.alexu.fitfinder.service.JwtService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/favorites") +@CrossOrigin +@RequiredArgsConstructor +public class FavoriteController { + + private final JwtService jwtService; + private final FavoriteService favoriteService; + + + @PostMapping("/{itemId}") + public ResponseEntity addToFavorites( + @PathVariable Long itemId, + @RequestHeader("Authorization") String token) { + + try { + Long userId = jwtService.extractUserFromToken(token); + favoriteService.addFavorite(userId, itemId); + return ResponseEntity.ok("Item added to favorites"); + } catch (IllegalArgumentException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + } + + // FIX: Changed path to avoid conflict with /{itemId} + @DeleteMapping("/id/{favId}") + public ResponseEntity deleteById( + @PathVariable Long favId, + @RequestHeader("Authorization") String token) { + + try { + Long userId = jwtService.extractUserFromToken(token); + favoriteService.deleteFavoriteById(userId, favId); + return ResponseEntity.ok("Item removed from favorites"); + + } catch (IllegalArgumentException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } catch (FavoriteNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); + } catch (RuntimeException e) { + // Catches the "Unauthorized: You do not own this favorite" from Service + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getMessage()); + } + } + + // This handles DELETE /favorites/5 (Assumes 5 is Item ID) + @DeleteMapping("/{itemId}") + public ResponseEntity deleteByItem( + @PathVariable Long itemId, + @RequestHeader("Authorization") String token) { + + try { + Long userId = jwtService.extractUserFromToken(token); + favoriteService.deleteFavoriteByItem(userId, itemId); + return ResponseEntity.ok("Item removed from favorites"); + + } catch (IllegalArgumentException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } catch (FavoriteNotFoundException | UserNotFoundException | ItemNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); + } + } + + @GetMapping + public ResponseEntity> getAllFavorites(@RequestHeader("Authorization") String token) { + try{ + Long userId = jwtService.extractUserFromToken(token); + return ResponseEntity.ok(favoriteService.getUserFavorites(userId)); + }catch (IllegalArgumentException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + } +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/controller/GlobalExceptionHandler.java b/src/main/java/edu/alexu/fitfinder/controller/GlobalExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..e4640947bf1b7c32287f5da5506edd14cd699b9c --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/controller/GlobalExceptionHandler.java @@ -0,0 +1,62 @@ +package edu.alexu.fitfinder.controller; + +import edu.alexu.fitfinder.exception.InvalidInputException; +import edu.alexu.fitfinder.exception.UnauthorizedException; +import edu.alexu.fitfinder.exception.UserAlreadyExistsException; +import edu.alexu.fitfinder.exception.SocketException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.multipart.MultipartException; + +import java.io.IOException; +import java.util.Map; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(UserAlreadyExistsException.class) + public ResponseEntity> handleUserExists(UserAlreadyExistsException e) { + return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", e.getMessage())); + } + + @ExceptionHandler(InvalidInputException.class) + public ResponseEntity> handleInvalidInput(InvalidInputException e) { + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY) + .body(Map.of("error", e.getMessage())); + } + + @ExceptionHandler(UnauthorizedException.class) + public ResponseEntity> handleUnauthorizedRequest(UnauthorizedException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", e.getMessage())); + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + public ResponseEntity handleMaxSizeException(MaxUploadSizeExceededException exc) { + return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE) + .body("File size shouldn't exceeds 10MB."); + } + + @ExceptionHandler(MultipartException.class) + public ResponseEntity handleMultipartException(MultipartException exc) { + return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body("Invalid file upload."); + } + + @ExceptionHandler(SocketException.class) + public ResponseEntity> handleSocketException(SocketException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("error", e.getMessage())); + } + + @ExceptionHandler(IOException.class) + public ResponseEntity> handleIOException(IOException e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(Map.of("error", e.getMessage())); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGeneric(Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(Map.of("error", "Unexpected error occurred")); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/controller/SearchController.java b/src/main/java/edu/alexu/fitfinder/controller/SearchController.java new file mode 100644 index 0000000000000000000000000000000000000000..a58e93be0ea75695621b36dc135adfdd19942f51 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/controller/SearchController.java @@ -0,0 +1,58 @@ +package edu.alexu.fitfinder.controller; + +import edu.alexu.fitfinder.dto.ItemDTO; +import edu.alexu.fitfinder.dto.SearchRequestDTO; +import edu.alexu.fitfinder.repository.ItemRepo; +import edu.alexu.fitfinder.service.JwtService; +import edu.alexu.fitfinder.service.SearchService; +import edu.alexu.fitfinder.service.StoredItemService; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import java.util.LinkedList; +import java.util.List; + +@RestController +@RequestMapping("/api/v1/items") +@CrossOrigin +@RequiredArgsConstructor +public class SearchController { + + private final JwtService jwtService; + private final ItemRepo findRandomEntities; + private final SearchService searchService; + private final StoredItemService storedItemService; + + @PostMapping("/search") + public ResponseEntity searchByImageMask( + @RequestBody SearchRequestDTO searchInfo, + @RequestHeader("Authorization") String token) + throws Exception { + + + try { + Long userId = jwtService.extractUserFromToken(token); + List vectorIds = searchService.getSimilarIndices(searchInfo); + if (vectorIds.isEmpty()) return ResponseEntity.ok().body(new LinkedList<>()); + return ResponseEntity.ok().body(storedItemService.getProductsByVectorIds(vectorIds,userId)); + } catch (IllegalArgumentException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + } + + @GetMapping("/random") + public List getRandomItems() { + List randomIds = findRandomEntities.findRandomIds(); + List items = storedItemService.getProducts(randomIds); + java.util.Collections.shuffle(items); + return items; + } + + @PostMapping("/fav/:id") + private ResponseEntity addFav(@RequestParam("id") Long item_id){ + + return ResponseEntity.status(HttpStatus.CREATED).build(); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/controller/SegmentationController.java b/src/main/java/edu/alexu/fitfinder/controller/SegmentationController.java new file mode 100644 index 0000000000000000000000000000000000000000..aee6a3cea32aeb90483307c73affec91317d255c --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/controller/SegmentationController.java @@ -0,0 +1,65 @@ +package edu.alexu.fitfinder.controller; + +import edu.alexu.fitfinder.component.JobRegistry; +import edu.alexu.fitfinder.dto.ImageMasksDTO; +import edu.alexu.fitfinder.dto.ResegmentImageDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; +import edu.alexu.fitfinder.service.SegmentationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.socket.BinaryMessage; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketSession; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +@RestController +public class SegmentationController { + + @Autowired SegmentationService segmentationService; + @Autowired JobRegistry jobRegistry; + + @PostMapping("/segment/upload") + public ResponseEntity uploadImage( + @RequestParam MultipartFile image, @RequestParam String sessionId) + throws IOException, Exception { + + Map response = segmentationService.UploadImageAndSegment(image, sessionId); + return ResponseEntity.status(HttpStatus.OK).body(response); + } + + @PostMapping("/re-segment") + public ResponseEntity resegment( + @RequestParam String sessionId, @RequestBody ResegmentImageDTO resegmentInfo) + throws InvalidInputException, Exception { + + segmentationService.Resegment(sessionId, resegmentInfo); + return new ResponseEntity<>(HttpStatus.OK); + } + + @PutMapping("/segmentation/callback") + public void segmentationCallback(@RequestBody ImageMasksDTO masks) throws IOException { + System.out.println("mask has been received from hugging face!"); + WebSocketSession session = jobRegistry.getSession(masks.getJob_id()); + // make sure that session exists and still open + if (session != null && session.isOpen()) { + if (masks.getStatus().equals("re-segmented")) + session.sendMessage(new TextMessage(masks.getMasks().toString())); + else + session.sendMessage( + new TextMessage( + "{\"masks\": " + + masks.getMasks().toString() + + ", \"boxes\": " + + masks.getBoxes().toString() + + "}")); + + System.out.println("mask has been sent to client!"); + jobRegistry.removeJob(masks.getJob_id()); + } + } +} diff --git a/src/main/java/edu/alexu/fitfinder/controller/UserController.java b/src/main/java/edu/alexu/fitfinder/controller/UserController.java new file mode 100644 index 0000000000000000000000000000000000000000..2da65af40b9230c87d43bc1e2e60c3ef96fc8020 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/controller/UserController.java @@ -0,0 +1,118 @@ +package edu.alexu.fitfinder.controller; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.exception.UserNotFoundException; +import edu.alexu.fitfinder.service.ImageService; +import edu.alexu.fitfinder.service.UserService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.Map; + +@RestController() +@RequestMapping("/api/v1/auth") +@RequiredArgsConstructor +public class UserController { + + private final UserService userService; + + @PostMapping("/signup") + public ResponseEntity> signup( + @RequestBody UserDTO user, HttpServletResponse response) { + Map accessToken = userService.SignUP(user, response); + return ResponseEntity.status(HttpStatus.CREATED).body(accessToken); + } + + @PostMapping("/login") + public ResponseEntity> login( + @RequestBody UserDTO user, HttpServletResponse response) { + Map accessToken = userService.LogIn(user, response); + return ResponseEntity.status(HttpStatus.OK).body(accessToken); + } + + @PostMapping("/refresh") + public ResponseEntity> refresh(HttpServletRequest request) { + Map accessToken = userService.RefreshToken(request); + return ResponseEntity.status(HttpStatus.OK).body(accessToken); + } + + @PostMapping("logout") + public ResponseEntity logout(HttpServletResponse response) { + userService.LogOut(response); + return ResponseEntity.status(HttpStatus.OK).build(); + } + + @GetMapping("/profile") + public ResponseEntity getProfile(@RequestHeader("Authorization") String token) { + UserDTO user; + try { + if (token != null && token.startsWith("Bearer ")) { + token = token.substring(7); + } + else { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + user = userService.getUser(token); + } catch (UserNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + + return ResponseEntity.ok(user); + } + + @PutMapping("/profile/photo") + public ResponseEntity uploadImageProfile( + @RequestParam MultipartFile image, + @RequestHeader("Authorization") String token) { + + UserDTO user; + try { + if (token != null && token.startsWith("Bearer ")) { + token = token.substring(7); + } + else { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + user = userService.getUser(token); + userService.updateImageProfile(user.getId(), image); + return ResponseEntity.ok("Profile image Uploaded"); + } catch (UserNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } catch (IOException e){ + return ResponseEntity.internalServerError().body(e.getMessage()); + } + } + + @DeleteMapping("/profile/photo") + public ResponseEntity deleteImageProfile( + @RequestParam MultipartFile image, + @RequestHeader("Authorization") String token) { + + UserDTO user; + try { + if (token != null && token.startsWith("Bearer ")) { + token = token.substring(7); + } + else { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + user = userService.getUser(token); + + userService.deleteImageProfile(user.getId()); + return ResponseEntity.ok("Profile image Uploaded"); + } catch (UserNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } catch (IOException e){ + return ResponseEntity.internalServerError().body(e.getMessage()); + } + } +} diff --git a/src/main/java/edu/alexu/fitfinder/dto/ImageMasksDTO.java b/src/main/java/edu/alexu/fitfinder/dto/ImageMasksDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..a30aaea9a18c791915f7f5b3dda00dadee49f4f0 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/dto/ImageMasksDTO.java @@ -0,0 +1,14 @@ +package edu.alexu.fitfinder.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import java.util.List; + +@AllArgsConstructor +@Getter +public class ImageMasksDTO { + String job_id; + String status; + List> masks; + List> boxes; +} diff --git a/src/main/java/edu/alexu/fitfinder/dto/ItemDTO.java b/src/main/java/edu/alexu/fitfinder/dto/ItemDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..8d3d9ede07de54086d3553b1be3270ce8313f910 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/dto/ItemDTO.java @@ -0,0 +1,22 @@ +package edu.alexu.fitfinder.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@AllArgsConstructor +@Getter +@Setter +@ToString +public class ItemDTO { + private Long item_id; + private String category; + private String currency; + private String description; + private String imageURL; + private String itemWebURL; + private float price; + private String title; + private boolean isFavorite; +} diff --git a/src/main/java/edu/alexu/fitfinder/dto/ResegmentImageDTO.java b/src/main/java/edu/alexu/fitfinder/dto/ResegmentImageDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..58e2e73e963e477d53c2735125bcb66d99a967ff --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/dto/ResegmentImageDTO.java @@ -0,0 +1,17 @@ +package edu.alexu.fitfinder.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@AllArgsConstructor +@Getter +@Setter +public class ResegmentImageDTO { + String job_id; + String image_url; + int[][] pos_points; + int[][] neg_points; + int[][] boxes; + String callback_url; +} diff --git a/src/main/java/edu/alexu/fitfinder/dto/SearchRequestDTO.java b/src/main/java/edu/alexu/fitfinder/dto/SearchRequestDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..873d79016ad89f07078104ae07a22e8a7c7100bf --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/dto/SearchRequestDTO.java @@ -0,0 +1,16 @@ +package edu.alexu.fitfinder.dto; + +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@AllArgsConstructor +@Getter +@Setter +public class SearchRequestDTO { + String job_id; + String image_url; + List> mask_json; + String prompt; +} diff --git a/src/main/java/edu/alexu/fitfinder/dto/SearchResponseDTO.java b/src/main/java/edu/alexu/fitfinder/dto/SearchResponseDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..8632b633995b032880de3236d71442dabe9e6e8c --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/dto/SearchResponseDTO.java @@ -0,0 +1,23 @@ +package edu.alexu.fitfinder.dto; + +import lombok.*; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +@ToString +public class SearchResponseDTO { + + @AllArgsConstructor + @Getter + @Setter + @ToString + public static class Result { + long faiss_id; + double distance; + } + + String job_id; + Result[] results; +} diff --git a/src/main/java/edu/alexu/fitfinder/dto/UserDTO.java b/src/main/java/edu/alexu/fitfinder/dto/UserDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..791bc56dcd75d881e8cdab352c735f62e8bfcc9a --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/dto/UserDTO.java @@ -0,0 +1,18 @@ +package edu.alexu.fitfinder.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class UserDTO { + private Long id; + private String profileImageURL; + private String userName; + private String password; + private String email; +} diff --git a/src/main/java/edu/alexu/fitfinder/entity/Favorite.java b/src/main/java/edu/alexu/fitfinder/entity/Favorite.java new file mode 100644 index 0000000000000000000000000000000000000000..77a2b269aa2c903b9b2aa1e9cb6a2c711993f4e7 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/entity/Favorite.java @@ -0,0 +1,30 @@ +package edu.alexu.fitfinder.entity; + +import jakarta.persistence.*; +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@Data +@Table(name = "FAVORITES") +@NoArgsConstructor +@Getter +@Setter +public class Favorite { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + @Column(name = "fav_id") + private Long id; + + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) // Defines the Foreign Key column + private User user; + + @ManyToOne + @JoinColumn(name = "item_id", nullable = false) // Defines the Foreign Key column + private StoredItem item; + +} diff --git a/src/main/java/edu/alexu/fitfinder/entity/ItemVector.java b/src/main/java/edu/alexu/fitfinder/entity/ItemVector.java new file mode 100644 index 0000000000000000000000000000000000000000..b1cb7cd4fd20b5807b0a3869e74c5250a8b1456a --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/entity/ItemVector.java @@ -0,0 +1,26 @@ +package edu.alexu.fitfinder.entity; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.CreationTimestamp; +import java.time.LocalDateTime; + +@Entity +@Table(name = "ITEM_VECTOR") +@Data +@NoArgsConstructor +@Getter +@Setter +public class ItemVector { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @CreationTimestamp private LocalDateTime createdAt; + private Long vectorId; + + @ManyToOne + @JoinColumn(name = "item_id", nullable = false) + private StoredItem item; +} diff --git a/src/main/java/edu/alexu/fitfinder/entity/StoredItem.java b/src/main/java/edu/alexu/fitfinder/entity/StoredItem.java new file mode 100644 index 0000000000000000000000000000000000000000..8281c35409528c7354820bf3040d41e39d227ba1 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/entity/StoredItem.java @@ -0,0 +1,61 @@ +package edu.alexu.fitfinder.entity; + +import java.time.LocalDateTime; + +import org.hibernate.annotations.CreationTimestamp; + +import jakarta.persistence.*; +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@Data +@Table(name = "STORED_ITEMS") +@NoArgsConstructor +@Getter +@Setter +public class StoredItem { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long itemId; + + private String category; + @CreationTimestamp private LocalDateTime createdAt; + private String currency; + + @Column(columnDefinition = "TEXT", name = "description") + private String description; + + private boolean embedded; + private String imageURL; + private String itemWebURL; + private float price; + private String source; + private String title; + + public StoredItem( + String category, + LocalDateTime createdAt, + String currency, + String description, + boolean embedded, + String imageURL, + String itemWebURL, + float price, + String source, + String title) { + this.category = category; + this.createdAt = createdAt; + this.currency = currency; + this.description = description; + this.embedded = embedded; + this.imageURL = imageURL; + this.itemWebURL = itemWebURL; + this.price = price; + this.source = source; + this.title = title; + } +} diff --git a/src/main/java/edu/alexu/fitfinder/entity/UploadedImage.java b/src/main/java/edu/alexu/fitfinder/entity/UploadedImage.java new file mode 100644 index 0000000000000000000000000000000000000000..056f343d37dbf9c4eb73fac013d833f28ef83908 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/entity/UploadedImage.java @@ -0,0 +1,37 @@ +package edu.alexu.fitfinder.entity; + +import jakarta.persistence.*; +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@Data +@Table(name = "UPLOADED_IMAGES") +@NoArgsConstructor +@Getter +@Setter +public class UploadedImage { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long uploadedImgId; + + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) + private User user; + + private Long uploadedFAISSId; + private String imageURL; + private String croppedImageURL; + private String name; + + // private boolean[][] mask; + + public UploadedImage(User user, Long uploadedFAISSId, String imageURL /*, boolean[][] mask*/) { + this.user = user; + this.uploadedFAISSId = uploadedFAISSId; + this.imageURL = imageURL; + // this.mask = mask; + } +} diff --git a/src/main/java/edu/alexu/fitfinder/entity/User.java b/src/main/java/edu/alexu/fitfinder/entity/User.java new file mode 100644 index 0000000000000000000000000000000000000000..eb6f3a45b8d3baffb1ba8fb5816176b8d61adcd9 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/entity/User.java @@ -0,0 +1,41 @@ +package edu.alexu.fitfinder.entity; + +import jakarta.persistence.*; +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; + +@Entity +@Data +@Table(name = "USERS") +@NoArgsConstructor +@Getter +@Setter +public class User { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + @Column(name = "user_id") + private Long userId; + + private String userName; + private String password; + private String email; + + @Column(nullable = false) + private String profileImageURL = ""; + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) + private List images; + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) + private List favorites; + + public User(String userName, String password, String email) { + this.userName = userName; + this.password = password; + this.email = email; + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/FavoriteNotFoundException.java b/src/main/java/edu/alexu/fitfinder/exception/FavoriteNotFoundException.java new file mode 100644 index 0000000000000000000000000000000000000000..94b168bac12d3cf4fc8d247dd6271aaaa83a4e82 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/FavoriteNotFoundException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class FavoriteNotFoundException extends RuntimeException { + public FavoriteNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/ImageNotFoundException.java b/src/main/java/edu/alexu/fitfinder/exception/ImageNotFoundException.java new file mode 100644 index 0000000000000000000000000000000000000000..66f4d40c3ac3e54958af0b5d0861fa46616d81e3 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/ImageNotFoundException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class ImageNotFoundException extends RuntimeException { + public ImageNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/InvalidInputException.java b/src/main/java/edu/alexu/fitfinder/exception/InvalidInputException.java new file mode 100644 index 0000000000000000000000000000000000000000..373f40a577c4edd2f8907ce5b066e71d5e52a553 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/InvalidInputException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class InvalidInputException extends RuntimeException { + public InvalidInputException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/ItemNotFoundException.java b/src/main/java/edu/alexu/fitfinder/exception/ItemNotFoundException.java new file mode 100644 index 0000000000000000000000000000000000000000..251e7b41c0cc42b45feeefb46cf20140dc168929 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/ItemNotFoundException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class ItemNotFoundException extends RuntimeException { + public ItemNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/LogInException.java b/src/main/java/edu/alexu/fitfinder/exception/LogInException.java new file mode 100644 index 0000000000000000000000000000000000000000..a8afad3293e2e99cf88bde0fe7948da756246fbb --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/LogInException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class LogInException extends Exception { + public LogInException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/SocketException.java b/src/main/java/edu/alexu/fitfinder/exception/SocketException.java new file mode 100644 index 0000000000000000000000000000000000000000..8a91e2275b278d3d5d5f2c7857319ef40d402de1 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/SocketException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class SocketException extends RuntimeException { + public SocketException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/UnauthorizedException.java b/src/main/java/edu/alexu/fitfinder/exception/UnauthorizedException.java new file mode 100644 index 0000000000000000000000000000000000000000..df0b7ff71e5d165fb886561c0ec367c68f044423 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/UnauthorizedException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class UnauthorizedException extends RuntimeException { + public UnauthorizedException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/UserAlreadyExistsException.java b/src/main/java/edu/alexu/fitfinder/exception/UserAlreadyExistsException.java new file mode 100644 index 0000000000000000000000000000000000000000..8fb922d787145ff763a05e3bfe8765b6008897b2 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/UserAlreadyExistsException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class UserAlreadyExistsException extends RuntimeException { + public UserAlreadyExistsException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/UserNotFoundException.java b/src/main/java/edu/alexu/fitfinder/exception/UserNotFoundException.java new file mode 100644 index 0000000000000000000000000000000000000000..075dee257578bc2e5504392e9ad4d6473be09e00 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/UserNotFoundException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/exception/ValidatorException.java b/src/main/java/edu/alexu/fitfinder/exception/ValidatorException.java new file mode 100644 index 0000000000000000000000000000000000000000..27c42e69b715ac51c75f797e071c0c9ba55eac24 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/exception/ValidatorException.java @@ -0,0 +1,7 @@ +package edu.alexu.fitfinder.exception; + +public class ValidatorException extends Exception { + public ValidatorException(String message) { + super(message); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/handler/MyWebSocketHandler.java b/src/main/java/edu/alexu/fitfinder/handler/MyWebSocketHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..80775c3d93520cac036e9e95c85e8fe2f35ea5fb --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/handler/MyWebSocketHandler.java @@ -0,0 +1,26 @@ +package edu.alexu.fitfinder.handler; + +import org.springframework.web.socket.*; +import org.springframework.web.socket.handler.TextWebSocketHandler; +import java.util.concurrent.ConcurrentHashMap; + +public class MyWebSocketHandler extends TextWebSocketHandler { + + // store all active sessions + public static ConcurrentHashMap sessions = new ConcurrentHashMap<>(); + + @Override + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + String sessionId = session.getId(); + sessions.put(sessionId, session); + System.out.println("Websocket connected successfully with sessionId = " + sessionId); + session.sendMessage(new TextMessage("{\"sessionId\": \"" + sessionId + "\"}")); + } + + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { + String sessionId = session.getId(); + sessions.remove(sessionId); + System.out.println("Websocket disconnected successfully with sessionId = " + sessionId); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/mapper/ItemMapper.java b/src/main/java/edu/alexu/fitfinder/mapper/ItemMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..980be0d7aaa95d5330deff47556c6ee30b02d8d4 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/mapper/ItemMapper.java @@ -0,0 +1,42 @@ +package edu.alexu.fitfinder.mapper; + +import edu.alexu.fitfinder.dto.ItemDTO; +import edu.alexu.fitfinder.entity.StoredItem; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class ItemMapper { + + public ItemDTO toDTO(StoredItem item) { + if (item == null) return null; + + // Ensure these getters match your StoredItem Entity field names + return new ItemDTO( + item.getItemId(), + item.getCategory(), + item.getCurrency(), + item.getDescription(), + item.getImageURL(), + item.getItemWebURL(), + item.getPrice(), + item.getTitle(), + false + ); + } + + public ItemDTO toDTO(StoredItem item, boolean isFavorite) { + ItemDTO dto = toDTO(item); // Call your existing base method + dto.setFavorite(isFavorite); // Set the new field + return dto; + } + + // Helper to map a whole list at once + public List toDTOList(List items) { + return items.stream() + .map(this::toDTO) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/mapper/UserMapper.java b/src/main/java/edu/alexu/fitfinder/mapper/UserMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..afbb25ab7a3416c894cb6e6a92548fcfa16d1096 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/mapper/UserMapper.java @@ -0,0 +1,35 @@ +package edu.alexu.fitfinder.mapper; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.entity.User; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class UserMapper { + + public UserDTO toDTO(User user) { + if (user == null) { + return null; + } + + UserDTO dto = new UserDTO(); + + // Mapping fields + dto.setId(user.getUserId()); // Note the name change: userId -> id + dto.setUserName(user.getUserName()); + dto.setPassword("In Your Dreams 😛"); // Be careful sending passwords in DTOs! + dto.setEmail(user.getEmail()); + dto.setProfileImageURL(user.getProfileImageURL()); + + return dto; + } + + public List toDTOList(List users) { + return users.stream() + .map(this::toDTO) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/repository/FavoriteRepo.java b/src/main/java/edu/alexu/fitfinder/repository/FavoriteRepo.java new file mode 100644 index 0000000000000000000000000000000000000000..96f0c82d7d252436bdd602e4ca421a8243980f06 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/repository/FavoriteRepo.java @@ -0,0 +1,25 @@ +package edu.alexu.fitfinder.repository; + +import edu.alexu.fitfinder.entity.Favorite; +import edu.alexu.fitfinder.entity.StoredItem; +import edu.alexu.fitfinder.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +@Repository +public interface FavoriteRepo extends JpaRepository { + boolean existsByUserAndItem(User user, StoredItem item); + + Optional findByUserAndItem(User user, StoredItem item); + + List findAllByUser(User user); + + @Query("SELECT f.item.itemId FROM Favorite f WHERE f.user.userId = :userId") + Set findFavoriteItemIds(@Param("userId") Long userId); +} diff --git a/src/main/java/edu/alexu/fitfinder/repository/ImageRepo.java b/src/main/java/edu/alexu/fitfinder/repository/ImageRepo.java new file mode 100644 index 0000000000000000000000000000000000000000..3bc504503ad54d7f7ab5a80e3e58250e6a1d3f50 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/repository/ImageRepo.java @@ -0,0 +1,9 @@ +package edu.alexu.fitfinder.repository; + +import edu.alexu.fitfinder.entity.UploadedImage; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ImageRepo extends JpaRepository { +} diff --git a/src/main/java/edu/alexu/fitfinder/repository/ItemRepo.java b/src/main/java/edu/alexu/fitfinder/repository/ItemRepo.java new file mode 100644 index 0000000000000000000000000000000000000000..762193d472c7df6191b485aa015788838e9a1172 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/repository/ItemRepo.java @@ -0,0 +1,22 @@ +package edu.alexu.fitfinder.repository; + +import edu.alexu.fitfinder.entity.StoredItem; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import java.util.List; + +@Repository +public interface ItemRepo extends JpaRepository { + @Query(value = "SELECT item_id FROM stored_items ORDER BY RANDOM() LIMIT 20", nativeQuery = true) + List findRandomIds(); + + @Query(value = """ + SELECT DISTINCT si.* FROM STORED_ITEMS si + JOIN ITEM_VECTOR vi ON vi.item_id = si.item_id + WHERE vi.vector_id IN :vectorIds + """, nativeQuery = true) + List findItemsByVectorIds(@Param("vectorIds") List vectorIds); + +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/repository/UserRepo.java b/src/main/java/edu/alexu/fitfinder/repository/UserRepo.java new file mode 100644 index 0000000000000000000000000000000000000000..6f65443a70ce753bea52e4dfd8718e02a5abb872 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/repository/UserRepo.java @@ -0,0 +1,10 @@ +package edu.alexu.fitfinder.repository; + +import edu.alexu.fitfinder.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepo extends JpaRepository { + User findByEmail(String email); +} diff --git a/src/main/java/edu/alexu/fitfinder/service/AIService.java b/src/main/java/edu/alexu/fitfinder/service/AIService.java new file mode 100644 index 0000000000000000000000000000000000000000..ade80aa2f4e506e8efb5f3b5faa718ae9db31dd5 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/AIService.java @@ -0,0 +1,74 @@ +package edu.alexu.fitfinder.service; + +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; +import edu.alexu.fitfinder.dto.SearchRequestDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; +import edu.alexu.fitfinder.dto.SearchResponseDTO; +import java.util.LinkedList; +import java.util.List; + +@Service +public class AIService { + + @Value("${cloudinary.url}") + private Cloudinary cloudinary; + + @Value("${forwarding.url}") + private String forwardingUrl; + + private final WebClient webClient; + + public AIService() { + this.webClient = WebClient.builder().baseUrl("https://fitfinder-ai-service.hf.space").build(); + } + + public List getSimilarIndices(SearchRequestDTO searchInfo) + throws InvalidInputException, Exception { + + // Validate mask + if (searchInfo.getMask_json() == null) throw new InvalidInputException("Mask couldn't be null"); + + // Validate job_id + try { + searchInfo.setImage_url( + cloudinary + .api() + .resource(searchInfo.getJob_id(), ObjectUtils.emptyMap()) + .get("secure_url") + .toString()); + } catch (Exception e) { + throw new InvalidInputException("There is no image associated with job Id"); + } + System.out.println(searchInfo.getImage_url()); + + // Call AI Service + SearchResponseDTO response = + webClient + .post() + .uri("/api/v1/job/search/") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(searchInfo) + .retrieve() + .bodyToMono(SearchResponseDTO.class) + .block(); + + // Validate response + System.out.println("response : " + response); + if (response == null) throw new Exception(); + + // No matched elements + LinkedList vectorIds = new LinkedList<>(); + if (response.getResults() == null || response.getResults().length == 0) return vectorIds; + + // Extract Vector Ids + for (SearchResponseDTO.Result result : response.getResults()) + vectorIds.add(result.getFaiss_id()); + System.out.println(vectorIds); + return vectorIds; + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/FavoriteService.java b/src/main/java/edu/alexu/fitfinder/service/FavoriteService.java new file mode 100644 index 0000000000000000000000000000000000000000..044b625d8ed9a2f219083471923cae7854683d7a --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/FavoriteService.java @@ -0,0 +1,88 @@ +package edu.alexu.fitfinder.service; + +import edu.alexu.fitfinder.dto.ItemDTO; +import edu.alexu.fitfinder.entity.Favorite; +import edu.alexu.fitfinder.entity.StoredItem; +import edu.alexu.fitfinder.entity.User; +import edu.alexu.fitfinder.exception.FavoriteNotFoundException; +import edu.alexu.fitfinder.exception.ItemNotFoundException; +import edu.alexu.fitfinder.exception.UserNotFoundException; +import edu.alexu.fitfinder.mapper.ItemMapper; +import edu.alexu.fitfinder.repository.FavoriteRepo; +import edu.alexu.fitfinder.repository.ItemRepo; +import edu.alexu.fitfinder.repository.UserRepo; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor // Lombok for constructor injection +public class FavoriteService { + + private final FavoriteRepo favoriteRepo; + private final UserRepo userRepo; + private final ItemRepo itemRepo; + private final ItemMapper itemMapper; + + @Transactional + public Long addFavorite(Long userId, Long itemId) { + User user = userRepo.findById(userId) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + StoredItem item = itemRepo.findById(itemId) + .orElseThrow(() -> new ItemNotFoundException("Item not found")); + + if (favoriteRepo.existsByUserAndItem(user, item)) { + throw new RuntimeException("Item is already in favorites"); + } + + Favorite favorite = new Favorite(); + favorite.setUser(user); + favorite.setItem(item); + + Favorite savedFav = favoriteRepo.save(favorite); + + return savedFav.getId(); + } + + @Transactional + public void deleteFavoriteById(Long userId, Long favoriteId){ + Favorite fav = favoriteRepo.findById(favoriteId) + .orElseThrow(() -> new FavoriteNotFoundException("Favorite not found")); + + if (!fav.getUser().getUserId().equals(userId)) { + throw new RuntimeException("Unauthorized: You do not own this favorite"); + } + + favoriteRepo.delete(fav); + } + + @Transactional + public void deleteFavoriteByItem(Long userId, Long itemId) { + User user = userRepo.findById(userId) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + StoredItem item = itemRepo.findById(itemId) + .orElseThrow(() -> new ItemNotFoundException("Item not found")); + + Favorite fav = favoriteRepo.findByUserAndItem(user, item) + .orElseThrow(() -> new FavoriteNotFoundException("Favorite not found")); + + favoriteRepo.delete(fav); + } + + public List getUserFavorites(Long userId) { + User user = userRepo.findById(userId) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + List favorites = favoriteRepo.findAllByUser(user); + + return favorites.stream() + .map(fav -> itemMapper.toDTO(fav.getItem(), true)) + .collect(Collectors.toList()); + + } +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/service/ImageService.java b/src/main/java/edu/alexu/fitfinder/service/ImageService.java new file mode 100644 index 0000000000000000000000000000000000000000..f644d2bef93fc20996f04f219251a1c0c875c2d5 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/ImageService.java @@ -0,0 +1,74 @@ +package edu.alexu.fitfinder.service; + +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; +import edu.alexu.fitfinder.entity.UploadedImage; +import edu.alexu.fitfinder.entity.User; +import edu.alexu.fitfinder.exception.ImageNotFoundException; +import edu.alexu.fitfinder.exception.UserNotFoundException; +import edu.alexu.fitfinder.repository.ImageRepo; +import edu.alexu.fitfinder.repository.UserRepo; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class ImageService { + + // FIX 1: Removed @Value. Spring now injects the Bean from CloudinaryConfig + private final Cloudinary cloudinary; + + private final ImageRepo imageRepo; + private final UserRepo userRepo; + + public String uploadImage(MultipartFile image, String imageName) throws IOException { + var params = ObjectUtils.asMap( + "public_id", imageName, + "overwrite", true + ); + var uploadResult = cloudinary.uploader().upload(image.getBytes(), params); + return uploadResult.get("secure_url").toString(); + } + + @Transactional + public UploadedImage saveImage(MultipartFile image, User user) throws IOException { + UploadedImage img = new UploadedImage(); + img.setUser(user); + + // FIX 2: Use UUID for unique naming. + // Using .size() causes overwrites if images are deleted later. + String imageName = "user_" + user.getUserId() + "_" + UUID.randomUUID().toString(); + + String url = this.uploadImage(image, imageName); + + img.setImageURL(url); + img.setName(imageName); + + return imageRepo.save(img); + } + + public void deleteImage(String publicId) throws IOException { + cloudinary.uploader().destroy(publicId, ObjectUtils.emptyMap()); + } + + @Transactional + public void deleteImageRow(Long imageId, Long userId) throws IOException { + + + UploadedImage img = imageRepo.findById(imageId) + .orElseThrow(() -> new ImageNotFoundException("Image not found")); + + if (!img.getUser().getUserId().equals(userId)) { + throw new RuntimeException("Unauthorized: You do not own this Image"); + } + + this.deleteImage(img.getName()); + + imageRepo.delete(img); + } +} \ No newline at end of file diff --git a/src/main/java/edu/alexu/fitfinder/service/JwtService.java b/src/main/java/edu/alexu/fitfinder/service/JwtService.java new file mode 100644 index 0000000000000000000000000000000000000000..10b85e551dc22355d83f7acafba276d2e1b29b29 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/JwtService.java @@ -0,0 +1,88 @@ +package edu.alexu.fitfinder.service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class JwtService { + @Value("${security.jwt.secret-key}") + private String secretKey; + + @Value("${security.jwt.access-expiration-time}") + private long accessExpiration; + + @Value("${security.jwt.refresh-expiration-time}") + private long refreshExpiration; + + + private Claims extractAllClaims(String token) { + return Jwts.parserBuilder() + .setSigningKey(getSignInKey()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + private T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + public Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + public String extractUserId(String token) { + return extractClaim(token, Claims::getSubject); + } + + public String generateAccessToken(String id) { + return generateToken(new HashMap<>(), id, accessExpiration); + } + + public String generateRefreshToken(String id) { + return generateToken(new HashMap<>(), id, refreshExpiration); + } + + private String generateToken(Map extraClaims, String id, long expiration) { + return buildToken(extraClaims, id, expiration); + } + + private String buildToken(Map extraClaims, String id, long expiration) { + return Jwts.builder() + .setClaims(extraClaims) + .setSubject(id) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(getSignInKey(), SignatureAlgorithm.HS256) + .compact(); + } + + public boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } + + public Long extractUserFromToken(String token) { + if (token == null || !token.startsWith("Bearer ")) { + throw new IllegalArgumentException("Invalid Token"); + } + // Clean the token once + String cleanToken = token.substring(7); + return Long.parseLong(this.extractUserId(cleanToken)); + } + + private Key getSignInKey() { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + return Keys.hmacShaKeyFor(keyBytes); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/SearchService.java b/src/main/java/edu/alexu/fitfinder/service/SearchService.java new file mode 100644 index 0000000000000000000000000000000000000000..ed217357f21414f0331692859b01c345987fde35 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/SearchService.java @@ -0,0 +1,74 @@ +package edu.alexu.fitfinder.service; + +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; +import edu.alexu.fitfinder.dto.SearchRequestDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; +import edu.alexu.fitfinder.dto.SearchResponseDTO; +import java.util.LinkedList; +import java.util.List; + +@Service +public class SearchService { + + @Value("${cloudinary.url}") + private Cloudinary cloudinary; + + @Value("${forwarding.url}") + private String forwardingUrl; + + private final WebClient webClient; + + public SearchService() { + this.webClient = WebClient.builder().baseUrl("https://fitfinder-ai-service.hf.space").build(); + } + + public List getSimilarIndices(SearchRequestDTO searchInfo) + throws InvalidInputException, Exception { + + // Validate mask + if (searchInfo.getMask_json() == null) throw new InvalidInputException("Mask couldn't be null"); + + // Validate job_id + try { + searchInfo.setImage_url( + cloudinary + .api() + .resource(searchInfo.getJob_id(), ObjectUtils.emptyMap()) + .get("secure_url") + .toString()); + } catch (Exception e) { + throw new InvalidInputException("There is no image associated with job Id"); + } + System.out.println(searchInfo.getImage_url()); + + // Call AI Service + SearchResponseDTO response = + webClient + .post() + .uri("/api/v1/job/search/") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(searchInfo) + .retrieve() + .bodyToMono(SearchResponseDTO.class) + .block(); + + // Validate response + System.out.println("response : " + response); + if (response == null) throw new Exception(); + + // No matched elements + LinkedList vectorIds = new LinkedList<>(); + if (response.getResults() == null || response.getResults().length == 0) return vectorIds; + + // Extract Vector Ids + for (SearchResponseDTO.Result result : response.getResults()) + vectorIds.add(result.getFaiss_id()); + System.out.println(vectorIds); + return vectorIds; + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/SegmentationService.java b/src/main/java/edu/alexu/fitfinder/service/SegmentationService.java new file mode 100644 index 0000000000000000000000000000000000000000..0a560d5fa067dc7d0c15d438a1b9e107a97d60d8 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/SegmentationService.java @@ -0,0 +1,141 @@ +package edu.alexu.fitfinder.service; + +import com.cloudinary.*; +import com.cloudinary.utils.ObjectUtils; +import edu.alexu.fitfinder.component.JobRegistry; +import edu.alexu.fitfinder.dto.ResegmentImageDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; +import edu.alexu.fitfinder.exception.SocketException; +import edu.alexu.fitfinder.handler.MyWebSocketHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.socket.WebSocketSession; +import reactor.core.publisher.Mono; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@Service +public class SegmentationService { + @Value("${cloudinary.url}") + private Cloudinary cloudinary; + + @Value("${forwarding.url}") + private String forwardingUrl; + + private final WebClient webClient; + @Autowired JobRegistry jobRegistry; + + public SegmentationService() { + this.webClient = WebClient.builder().baseUrl("https://fitfinder-ai-service.hf.space").build(); + } + + public Map UploadImageAndSegment(MultipartFile image, String sessionId) + throws IOException, SocketException, Exception { + + // Get websocket session related to this session id + WebSocketSession session = MyWebSocketHandler.sessions.get(sessionId); + if (session == null) throw new SocketException("WebSocket not connected"); + + // create unique job id and upload it to cloudinary service + String jobId = UUID.randomUUID().toString(); // 128-bit collision free random string + var params = ObjectUtils.asMap("public_id", jobId, "overwrite", true); + var uploadResult = cloudinary.uploader().upload(image.getBytes(), params); + String imageUrl = uploadResult.get("secure_url").toString(); + + System.out.println("Image url :" + imageUrl); + // register this job with the session + jobRegistry.registerJob(jobId, session); + + // send the image to the AI service for segmentation + webClient + .post() + .uri("/api/v1/job/segment/") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body( + BodyInserters.fromFormData("job_id", jobId) + .with("image_url", imageUrl) + .with("callback_url", forwardingUrl + "/segmentation/callback")) + .exchangeToMono(response -> Mono.just(response.statusCode())) + .block(); + System.out.println("Image is uploaded successfully to hugging face"); + + // return job id and image url to the client + Map response = new HashMap<>(); + response.put("job_id", jobId); + return response; + } + + private void validatePointsAndBoxes(int[][] posPoints, int[][] negPoints, int[][] boxes) + throws InvalidInputException { + if ((negPoints == null || negPoints.length == 0) + && (posPoints == null || posPoints.length == 0)) { + throw new InvalidInputException("Pos points or neg points should be given"); + } + + boolean isNegPointsInValid = + negPoints != null && negPoints.length != 0 && negPoints[0].length != 2; + boolean isPosPointsInValid = + posPoints != null && posPoints.length != 0 && posPoints[0].length != 2; + + if (isNegPointsInValid || isPosPointsInValid) { + throw new InvalidInputException("Pos points and neg points should be of shape (N,2)"); + } + + if (boxes != null && boxes.length != 0 && boxes[0].length != 4) { + throw new InvalidInputException("Boxes should be of shape (N,4)"); + } + } + + public void Resegment(String sessionId, ResegmentImageDTO resegmentInfo) { + // Get websocket session related to this id + WebSocketSession session = MyWebSocketHandler.sessions.get(sessionId); + if (session == null) throw new SocketException("WebSocket not connected"); + + // Validate job_id + try { + resegmentInfo.setImage_url( + cloudinary + .api() + .resource(resegmentInfo.getJob_id(), ObjectUtils.emptyMap()) + .get("secure_url") + .toString()); + } catch (Exception e) { + throw new InvalidInputException("There is no image associated with job Id"); + } + System.out.println(resegmentInfo.getImage_url()); + + // Validate points and boxes + validatePointsAndBoxes( + resegmentInfo.getPos_points(), resegmentInfo.getNeg_points(), resegmentInfo.getBoxes()); + + // Refactor dimension for null and empty inputs + if (resegmentInfo.getNeg_points() == null) resegmentInfo.setNeg_points(new int[0][0]); + if (resegmentInfo.getPos_points() == null) resegmentInfo.setPos_points(new int[0][0]); + if (resegmentInfo.getBoxes() != null && resegmentInfo.getBoxes().length == 0) + resegmentInfo.setBoxes(null); + + // register this job with the session + System.out.println("SessionId is correctly connected with Websocket!"); + jobRegistry.registerJob(resegmentInfo.getJob_id(), session); + + resegmentInfo.setCallback_url(forwardingUrl + "/segmentation/callback"); + String response = + webClient + .post() + .uri("/api/v1/job/re-segment/") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(resegmentInfo) + .retrieve() + .bodyToMono(String.class) + .block(); + System.out.println(response); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/StoredItemService.java b/src/main/java/edu/alexu/fitfinder/service/StoredItemService.java new file mode 100644 index 0000000000000000000000000000000000000000..d9e64c24ce5ebcbd73ca4fb1da104adc27b5205a --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/StoredItemService.java @@ -0,0 +1,91 @@ +package edu.alexu.fitfinder.service; + +import edu.alexu.fitfinder.dto.ItemDTO; +import edu.alexu.fitfinder.entity.StoredItem; +import edu.alexu.fitfinder.mapper.ItemMapper; +import edu.alexu.fitfinder.repository.FavoriteRepo; +import edu.alexu.fitfinder.repository.ItemRepo; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class StoredItemService { + + private final ItemRepo itemRepo; + private final FavoriteRepo favoriteRepo; + private final ItemMapper itemMapper; + + // REPLACES: getProductsByVectorIds + public List getProductsByVectorIds(List vectorIds, Long userId) { + if (vectorIds == null || vectorIds.isEmpty()) return Collections.emptyList(); + + // 1. Get Entities using the Repository (Native Query) + List items = itemRepo.findItemsByVectorIds(vectorIds); + + // 2. Map them + return mapItemsToDTOs(items, userId); + } + + public List getProducts(List itemIds, Long userId) { + if (itemIds == null || itemIds.isEmpty()) return Collections.emptyList(); + + // 1. Get Entities using standard JPA + List items = itemRepo.findAllById(itemIds); + + // 2. Map them, respecting the order of input IDs + // (Optional: Re-sort items to match 'itemIds' order if strict ordering is needed) + List dtos = mapItemsToDTOs(items, userId); + + return preserveOrder(dtos, itemIds); + } + + public List getProducts(List itemIds) { + if (itemIds == null || itemIds.isEmpty()) return Collections.emptyList(); + + // 1. Get Entities using standard JPA + List items = itemRepo.findAllById(itemIds); + + + List dtos = mapItemsToDTOs(items); + + return preserveOrder(dtos, itemIds); + } + + private List mapItemsToDTOs(List items, Long userId) { + Set likedIds = (userId != null) + ? favoriteRepo.findFavoriteItemIds(userId) + : Collections.emptySet(); + + return items.stream() + .map(item -> itemMapper.toDTO(item, likedIds.contains(item.getItemId()))) + .collect(Collectors.toList()); + } + + private List mapItemsToDTOs(List items) { + + return items.stream() + .map(itemMapper::toDTO) + .collect(Collectors.toList()); + } + + private List preserveOrder(List unsortedDtos, List orderedIds) { + Map map = unsortedDtos.stream() + .collect(Collectors.toMap(ItemDTO::getItem_id, Function.identity())); + + return orderedIds.stream() + .filter(map::containsKey) + .map(map::get) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/UserService.java b/src/main/java/edu/alexu/fitfinder/service/UserService.java new file mode 100644 index 0000000000000000000000000000000000000000..23b267fa678323efc171658c9fb35e4a4d316e1e --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/UserService.java @@ -0,0 +1,173 @@ +package edu.alexu.fitfinder.service; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.entity.User; +import edu.alexu.fitfinder.exception.InvalidInputException; +import edu.alexu.fitfinder.exception.UnauthorizedException; +import edu.alexu.fitfinder.exception.UserAlreadyExistsException; +import edu.alexu.fitfinder.exception.UserNotFoundException; +import edu.alexu.fitfinder.mapper.UserMapper; +import edu.alexu.fitfinder.repository.UserRepo; +import edu.alexu.fitfinder.service.signup.EmailValidator; +import edu.alexu.fitfinder.service.signup.PasswordValidator; +import edu.alexu.fitfinder.service.signup.Validator; +import edu.alexu.fitfinder.service.signup.UserNameValidator; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.mindrot.jbcrypt.BCrypt; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +@Service +@RequiredArgsConstructor +public class UserService { + + private final UserRepo userRepo; + private final JwtService jwtService; + private final UserMapper userMapper; + private final ImageService imageService; + + + private final int REFRESH_TOKEN_MAX_AGE = 3 * 60 * 60; // 3 hours + private final String REFRESH_TOKEN_PATH = "/auth"; + + private Cookie GenerateRefreshCookie(long id) { + String refreshToken = jwtService.generateRefreshToken(id + ""); + + Cookie cookie = new Cookie("refreshToken", refreshToken); + cookie.setHttpOnly(true); + // cookie.setSecure(true); // only on HTTPS + cookie.setPath(REFRESH_TOKEN_PATH); + cookie.setMaxAge(REFRESH_TOKEN_MAX_AGE); + cookie.setAttribute("SameSite", "Strict"); + return cookie; + } + + private Cookie DeleteRefreshToken() { + Cookie cookie = new Cookie("refreshToken", null); + cookie.setHttpOnly(true); + // cookie.setSecure(true); // only on https + cookie.setPath(REFRESH_TOKEN_PATH); + cookie.setMaxAge(0); + cookie.setAttribute("SameSite", "Strict"); + return cookie; + } + + public Map SignUP(UserDTO user, HttpServletResponse response) + throws InvalidInputException, UserAlreadyExistsException { + + Validator userNameValidator = new UserNameValidator(); + Validator passwordValidator = new PasswordValidator(); + Validator emailValidator = new EmailValidator(userRepo); + userNameValidator.setNext(passwordValidator); + passwordValidator.setNext(emailValidator); + userNameValidator.validate(user); + + // save record in the database + String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(12)); + User databaseRecord = new User(user.getUserName(), hashedPassword, user.getEmail()); + userRepo.save(databaseRecord); + + // generate jwt refresh token + response.addCookie(GenerateRefreshCookie(databaseRecord.getUserId())); + + String accessToken = jwtService.generateAccessToken(databaseRecord.getUserId() + ""); + Map jwtAccessToken = new HashMap<>(); + jwtAccessToken.put("accessToken", accessToken); + jwtAccessToken.put("expiresIn", jwtService.extractExpiration(accessToken).toString()); + return jwtAccessToken; + } + + public Map LogIn(UserDTO user, HttpServletResponse response) + throws InvalidInputException { + String email = user.getEmail(); + String password = user.getPassword(); + if (email == null || password == null) { + throw new InvalidInputException("Email and password are required"); + } + + User existingUser = userRepo.findByEmail(email); + if (existingUser == null || !BCrypt.checkpw(password, existingUser.getPassword())) { + throw new InvalidInputException("Invalid email or password"); + } + + // generate jwt refresh token + response.addCookie(GenerateRefreshCookie(existingUser.getUserId())); + + // generate jwt authentication token + Map jwtAccessToken = new HashMap<>(); + String accessToken = jwtService.generateAccessToken(existingUser.getUserId() + ""); + jwtAccessToken.put("accessToken", accessToken); + jwtAccessToken.put("expiresIn", jwtService.extractExpiration(accessToken).toString()); + return jwtAccessToken; + } + + public Map RefreshToken(HttpServletRequest request) throws UnauthorizedException { + String refreshToken = null; + if (request.getCookies() != null) { + for (Cookie cookie : request.getCookies()) { + if ("refreshToken".equals(cookie.getName())) { + refreshToken = cookie.getValue(); + break; + } + } + } + + if (refreshToken == null) { + throw new UnauthorizedException("No refresh Token is found"); + } + + if (jwtService.isTokenExpired(refreshToken)) { + throw new UnauthorizedException("Refresh token is expired"); + } + + // check that user still exists + String userId = jwtService.extractUserId(refreshToken); + if (!userRepo.existsById(Long.parseLong(userId))) + throw new UnauthorizedException("User doesn't exist"); + + // Create new access token + String newAccessToken = jwtService.generateAccessToken(userId); + Map jwtAccessToken = new HashMap<>(); + jwtAccessToken.put("accessToken", newAccessToken); + jwtAccessToken.put("expiresIn", jwtService.extractExpiration(newAccessToken).toString()); + return jwtAccessToken; + } + + public void LogOut(HttpServletResponse response) { + response.addCookie(DeleteRefreshToken()); + } + + public UserDTO getUser(String token) { + Long userID = Long.parseLong(jwtService.extractUserId(token)); + User user = userRepo.findById(userID) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + return userMapper.toDTO(user); + } + + public void updateImageProfile(Long userId, MultipartFile image) throws IOException { + User user = userRepo.findById(userId) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + String imageName = user.getUserId() + "_0"; + user.setProfileImageURL(imageService.uploadImage(image, imageName)); + userRepo.save(user); + } + + public void deleteImageProfile(Long id) throws IOException { + User user = userRepo.findById(id) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + String imageName = user.getUserId() + "_0"; + imageService.deleteImage(imageName); + user.setProfileImageURL(""); + userRepo.save(user); + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/signup/EmailValidator.java b/src/main/java/edu/alexu/fitfinder/service/signup/EmailValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..3aff0254a8b0a2dd0e6af1a1a7a1e3c2031842ee --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/signup/EmailValidator.java @@ -0,0 +1,35 @@ +package edu.alexu.fitfinder.service.signup; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.entity.User; +import edu.alexu.fitfinder.exception.InvalidInputException; +import edu.alexu.fitfinder.exception.UserAlreadyExistsException; +import edu.alexu.fitfinder.repository.UserRepo; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class EmailValidator extends Validator { + + UserRepo userRepo; + + @Override + protected void check(UserDTO user) throws InvalidInputException, UserAlreadyExistsException { + + String email = user.getEmail(); + + if (email == null) { + throw new InvalidInputException("Email is required."); + } + + boolean isValid = + org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email); + if (!isValid) { + throw new InvalidInputException("Email isn't valid"); + } + + User existingUser = userRepo.findByEmail(email); + if (existingUser != null) { + throw new UserAlreadyExistsException("Email already exists."); + } + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/signup/PasswordValidator.java b/src/main/java/edu/alexu/fitfinder/service/signup/PasswordValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..2ce4d58e22349d5ab22ab2ce2e901257328cb4e1 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/signup/PasswordValidator.java @@ -0,0 +1,33 @@ +package edu.alexu.fitfinder.service.signup; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; + +public class PasswordValidator extends Validator { + + /** + * at least one uppercase, letter at least one lowercase letter, at least one digit, at least one + * special char, no leading or trailing spaces and length between 8 and 64 + */ + private final String PASSWORD_PATTERN = + "^(?=.*[A-Z])" + + "(?=.*[a-z])" + + "(?=.*\\d)" + + "(?=.*[!@#$%^&*()_+\\-=\\[\\]{};:,.<>?])" + + "(?!.*^ |.* $)" + + ".{8,64}$"; + + @Override + protected void check(UserDTO user) throws InvalidInputException { + + String password = user.getPassword(); + if (password == null) { + throw new InvalidInputException("Password is required."); + } + + if (!password.matches(PASSWORD_PATTERN)) { + throw new InvalidInputException( + "Password must be 8–64 chars long, contain uppercase, lowercase, digit, and special character, and not start/end with spaces."); + } + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/signup/UserNameValidator.java b/src/main/java/edu/alexu/fitfinder/service/signup/UserNameValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..1ede7d4d4135584ef23764d0b013bcdcff6d49a3 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/signup/UserNameValidator.java @@ -0,0 +1,27 @@ +package edu.alexu.fitfinder.service.signup; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; + +public class UserNameValidator extends Validator { + + /** + * length between 3 and 30 contains only letters, digits, spaces and start only with letters and + * not end with space + */ + private final String USERNAME_PATTERN = "^(?=.{3,30}$)" + "[A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9]$"; + + @Override + protected void check(UserDTO user) throws InvalidInputException { + + String userName = user.getUserName(); + if (userName == null) { + throw new InvalidInputException("User Name is required."); + } + + if (!userName.matches(USERNAME_PATTERN)) { + throw new InvalidInputException( + "Username must be 3–30 characters, start with a letter, contain only letters, digits, or spaces, and not end with a space."); + } + } +} diff --git a/src/main/java/edu/alexu/fitfinder/service/signup/Validator.java b/src/main/java/edu/alexu/fitfinder/service/signup/Validator.java new file mode 100644 index 0000000000000000000000000000000000000000..eb969fb12f3c10885d865d7a28944c9f472fe551 --- /dev/null +++ b/src/main/java/edu/alexu/fitfinder/service/signup/Validator.java @@ -0,0 +1,24 @@ +package edu.alexu.fitfinder.service.signup; + +import edu.alexu.fitfinder.dto.UserDTO; +import edu.alexu.fitfinder.exception.InvalidInputException; +import edu.alexu.fitfinder.exception.UserAlreadyExistsException; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public abstract class Validator { + + private Validator next; + + public void validate(UserDTO user) throws InvalidInputException, UserAlreadyExistsException { + check(user); + if (next != null) { + next.validate(user); + } + } + + protected abstract void check(UserDTO user) + throws InvalidInputException, UserAlreadyExistsException; +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..42d2acd21e6940f620998f5df12f8752e80a60a2 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,20 @@ +spring.application.name=FitFinder +server.port=7860 +spring.datasource.url=jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME} +spring.datasource.username=${DB_USER} +spring.datasource.password=${DB_PASSWORD} +spring.jpa.hibernate.ddl-auto=update +logging.level.org.springframework.web.socket=TRACE +logging.level.org.apache.tomcat.websocket=DEBUG +security.jwt.secret-key=${SECURITY_JWT_SECRET_KEY} +security.jwt.access-expiration-time=${SECURITY_JWT_ACCESS_EXPIRATION_TIME} +security.jwt.refresh-expiration-time=${SECURITY_JWT_REFRESH_EXPIRATION_TIME} +cloudinary.url=${CLOUDINARY_URL} +spring.servlet.multipart.max-file-size=10MB +spring.servlet.multipart.max-request-size=10MB +forwarding.url=${FORWARDING_URL} +# Tell Spring to trust the headers sent by the ngrok proxy +server.forward-headers-strategy=framework +# Optional: If you encounter issues with the host specifically +server.tomcat.remoteip.remote-ip-header=x-forwarded-for +server.tomcat.remoteip.protocol-header=x-forwarded-proto diff --git a/src/test/java/edu/alexu/fitfinder/FitFinderApplicationTests.java b/src/test/java/edu/alexu/fitfinder/FitFinderApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..93c387802b596ac4e0ca743042982365980ffbec --- /dev/null +++ b/src/test/java/edu/alexu/fitfinder/FitFinderApplicationTests.java @@ -0,0 +1,11 @@ +package edu.alexu.fitfinder; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class FitFinderApplicationTests { + + @Test + void contextLoads() {} +}