diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index c1dd12f..0000000 Binary files a/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index b74bf7f..0000000 --- a/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar diff --git a/README.md b/README.md index 70a9e4a..e48d13a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ -# Spring-boot-e-commerce-rest-api -Spring Boot E-commerce Rest Api +# Spring-boot-e-commerce-rest-api \ No newline at end of file diff --git a/mvnw b/mvnw deleted file mode 100755 index 8a8fb22..0000000 --- a/mvnw +++ /dev/null @@ -1,316 +0,0 @@ -#!/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 -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /usr/local/etc/mavenrc ] ; then - . /usr/local/etc/mavenrc - fi - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`\\unset -f command; \\command -v java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - $MAVEN_DEBUG_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" \ - "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd deleted file mode 100644 index 1d8ab01..0000000 --- a/mvnw.cmd +++ /dev/null @@ -1,188 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* -if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - -FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% ^ - %JVM_CONFIG_MAVEN_PROPS% ^ - %MAVEN_OPTS% ^ - %MAVEN_DEBUG_OPTS% ^ - -classpath %WRAPPER_JAR% ^ - "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ - %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" -if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%"=="on" pause - -if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% - -cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 083ab16..0000000 --- a/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-parent</artifactId> - <version>2.7.5</version> - <relativePath/> <!-- lookup parent from repository --> - </parent> - <groupId>com.manir</groupId> - <artifactId>spring-boot-e-commerce-rest-api</artifactId> - <version>0.0.1-SNAPSHOT</version> - <name>spring-boot-e-commerce-rest-api</name> - <description>spring-boot-e-commerce-rest-api</description> - <properties> - <java.version>11</java.version> - </properties> - <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-jpa</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-web</artifactId> - </dependency> - - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-devtools</artifactId> - <scope>runtime</scope> - <optional>true</optional> - </dependency> - <dependency> - <groupId>com.mysql</groupId> - <artifactId>mysql-connector-j</artifactId> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>org.projectlombok</groupId> - <artifactId>lombok</artifactId> - <optional>true</optional> - </dependency> - <!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper --> - <dependency> - <groupId>org.modelmapper</groupId> - <artifactId>modelmapper</artifactId> - <version>3.1.0</version> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-security</artifactId> - </dependency> - <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --> - <dependency> - <groupId>io.jsonwebtoken</groupId> - <artifactId>jjwt</artifactId> - <version>0.9.1</version> - </dependency> - - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - <configuration> - <excludes> - <exclude> - <groupId>org.projectlombok</groupId> - <artifactId>lombok</artifactId> - </exclude> - </excludes> - </configuration> - </plugin> - </plugins> - </build> - -</project> diff --git a/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java b/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java deleted file mode 100644 index 6b03645..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.manir.springbootecommercerestapi; - -import org.modelmapper.ModelMapper; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; - -@SpringBootApplication -@EnableJpaAuditing(auditorAwareRef = "auditAwareImpl") -public class SpringBootECommerceRestApiApplication { - - public static void main(String[] args) { - - SpringApplication.run(SpringBootECommerceRestApiApplication.class, args); - } - - @Bean - public ModelMapper modelMapper(){ - return new ModelMapper(); - } - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/audit/AuditAwareImpl.java b/src/main/java/com/manir/springbootecommercerestapi/audit/AuditAwareImpl.java deleted file mode 100644 index 2ba6d01..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/audit/AuditAwareImpl.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.manir.springbootecommercerestapi.audit; - -import org.springframework.data.domain.AuditorAware; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Optional; - -@Component("auditAwareImpl") -public class AuditAwareImpl implements AuditorAware<String> { - @Override - public Optional<String> getCurrentAuditor() { - return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java b/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java deleted file mode 100644 index e2a691e..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.manir.springbootecommercerestapi.config; - -import com.manir.springbootecommercerestapi.security.CustomUserDetailsService; -import com.manir.springbootecommercerestapi.security.JwtAuthenticationEntryPoint; -import com.manir.springbootecommercerestapi.security.JwtAuthenticationFilter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -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.configuration.WebSecurityConfigurerAdapter; -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.authentication.UsernamePasswordAuthenticationFilter; - -@Configuration -@EnableWebSecurity -/*** - global security is used for enable security at method level for example permitting get methods - Ex: PreAuthorize("hasRole('ADMIN')") - ***/ -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private CustomUserDetailsService customUserDetailsService; - @Autowired - private JwtAuthenticationEntryPoint authenticationEntryPoint; - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .csrf().disable() - /*-------------------------JWT Starts------------------------------*/ - .exceptionHandling() - .authenticationEntryPoint(authenticationEntryPoint) - .and() - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - /*-------------------------JWT ends------------------------------*/ - .and() - .authorizeRequests() - //to permit all get request and secure post put and delete methods - .antMatchers(HttpMethod.GET, "/api/**").permitAll() - //authorize singIn and signUp - .antMatchers("/api/v*/auth/**").permitAll() - .antMatchers(HttpMethod.POST, "/api/v*/contact/**").permitAll() - .anyRequest() - .authenticated(); - - /** - Basic auth used before JWT implementation - .and() - .httpBasic(); - **/ - http - .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); - - } - - //Jwt auth filter method - @Bean - public JwtAuthenticationFilter jwtAuthenticationFilter(){ - return new JwtAuthenticationFilter(); - } - - //In memory Auth - /** - @Override - @Bean - protected UserDetailsService userDetailsService() { - UserDetails user = User.builder().username("customer").password(passwordEncoder().encode("customer")).roles("USER").build(); - UserDetails admin = User.builder().username("admin").password(passwordEncoder().encode("admin")).roles("ADMIN").build(); - - return new InMemoryUserDetailsManager(user, admin); - } - **/ - - //DB Auth - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); - } - - @Bean - PasswordEncoder passwordEncoder(){ - return new BCryptPasswordEncoder(); - } - - //User authentication manager bean - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/AuthController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/AuthController.java deleted file mode 100644 index 672f51a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/AuthController.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.LoginDto; -import com.manir.springbootecommercerestapi.dto.SignUpDto; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import com.manir.springbootecommercerestapi.response.JWTAuthResponse; -import com.manir.springbootecommercerestapi.security.JwtTokenProvider; -import com.manir.springbootecommercerestapi.service.UserRegisterService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - - - -@RestController -@RequestMapping(value = "api/v1/auth") -public class AuthController { - - @Autowired - private AuthenticationManager authenticationManager; - @Autowired - private UserRepository userRepository; - @Autowired - private UserRegisterService userRegisterService; - @Autowired - private JwtTokenProvider tokenProvider; - - //login api - @PostMapping("/login") - public ResponseEntity<JWTAuthResponse> authenticateUser(@RequestBody LoginDto loginDto){ - - Authentication authentication = authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken( - loginDto.getUserNameOrEmail(), - loginDto.getPassword() - ) - ); - SecurityContextHolder.getContext().setAuthentication(authentication); - - //get token from token provider - String token = tokenProvider.generateToken(authentication); - - return new ResponseEntity<>(new JWTAuthResponse(token), HttpStatus.OK); - } - - //register api - @PostMapping("/register") - public ResponseEntity<?> registerUser(@RequestBody SignUpDto signUpDto){ - - //check for username exists in DB - if (userRepository.existsByUserName(signUpDto.getUsername())){ - return new ResponseEntity<>("Username already exists", HttpStatus.BAD_REQUEST); - } - if (userRepository.existsByEmail(signUpDto.getEmail())){ - return new ResponseEntity<>("Email already exists", HttpStatus.BAD_REQUEST); - } - userRegisterService.registerUser(signUpDto); - return new ResponseEntity<>("User is successfully registered", HttpStatus.OK); - } - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/CategoryController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/CategoryController.java deleted file mode 100644 index 23544d0..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/CategoryController.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.CategoryDto; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import com.manir.springbootecommercerestapi.service.CategoryService; -import com.manir.springbootecommercerestapi.utils.Constant; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - - -@RestController -@RequestMapping(value = "api/v1/categories") -public class CategoryController { - - @Autowired - private CategoryService categoryService; - - //create category api - @PreAuthorize("hasRole('ADMIN')") - @PostMapping("/createCategory") - public ResponseEntity<CategoryDto> createCategory(@RequestBody CategoryDto categoryDto){ - CategoryDto responseCategory = categoryService.createCategory(categoryDto); - return new ResponseEntity<>(responseCategory, HttpStatus.CREATED); - } - - //get all categories api - @GetMapping("/getAllCategory") - public CommonResponse getAllCategory(@RequestParam(value = "pageNo", defaultValue = Constant.DEFAULT_PAGE_NUMBER, required = false) int pageNo, - @RequestParam(value = "pageSize", defaultValue = Constant.DEFAULT_PAGE_SIZE, required = false) int pageSize, - @RequestParam(value = "sortBy", defaultValue = Constant.DEFAULT_SORT_BY, required = false) String sortBy, - @RequestParam(value = "sortDir", defaultValue = Constant.DEFAULT_SORT_DIRECTION, required = false) String sortDir){ - CommonResponse categoryResponse = categoryService.getAllCategory(pageNo, pageSize, sortBy, sortDir); - return categoryResponse; - } - - //get category by id api - @GetMapping("{categoryId}") - public ResponseEntity<CategoryDto> getCatecoryById(@PathVariable Long categoryId){ - CategoryDto responseCategory = categoryService.getCategoryById(categoryId); - return ResponseEntity.ok(responseCategory); - } - - //update category api - @PreAuthorize("hasRole('ADMIN')") - @PutMapping("/updateCategory/{categoryId}") - public ResponseEntity<CategoryDto> updateCategory(@RequestBody CategoryDto categoryDto, - @PathVariable Long categoryId){ - CategoryDto responseCategory = categoryService.updateCategory(categoryDto, categoryId); - return new ResponseEntity<>(responseCategory, HttpStatus.OK); - } - - //delete category api - @PreAuthorize("hasRole('ADMIN')") - @DeleteMapping("/deleteCategory/{categoryId}") - public ResponseEntity<String> deleteCategory(@PathVariable Long categoryId){ - categoryService.deleteCategory(categoryId); - return ResponseEntity.ok("Category with id: "+ categoryId + " is deleted successfully:)"); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java deleted file mode 100644 index b119ef8..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.CommentDto; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.service.CommentService; -import com.manir.springbootecommercerestapi.service.CommonService; -import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import java.util.List; - -@RestController -@RequestMapping(value = "api/v1/products") -public class CommentController { - - @Autowired - private CommentService commentService; - @Autowired - private CommonService commonService; - - //create comment api - @isAuthenticatedAsAdminOrUser - @PostMapping("/{productId}/createComment") - public ResponseEntity<CommentDto> createComment(@AuthenticationPrincipal Authentication authentication, - @PathVariable Long productId, - @RequestBody CommentDto commentDto){ - User customer = commonService.getCurrentAuthenticatedUser(authentication); - CommentDto responseComment = commentService.createComment(customer, productId, commentDto); - return new ResponseEntity<>(responseComment, HttpStatus.CREATED); - } - - //get comment by user - @isAuthenticatedAsAdminOrUser - @GetMapping("/comment/findByUser") - public List<CommentDto> findByUser(@AuthenticationPrincipal Authentication authentication){ - User customer = commonService.getCurrentAuthenticatedUser(authentication); - return commentService.findCommentByCustomer(customer); - } - - //get all comments api - @GetMapping("/getAllComments") - public List<CommentDto> getAllComments(){ - return commentService.getAllComments(); - } - - //get comments by product id api - @GetMapping("/{productId}/getCommentByProductId") - public List<CommentDto> getCommentByProductId(@PathVariable Long productId){ - return commentService.getAllCommentsByProductId(productId); - } - - //get comment by id api - @GetMapping("/{productId}/comment/{commentId}") - public ResponseEntity<CommentDto> getCommentById(@PathVariable Long productId, @PathVariable Long commentId){ - CommentDto responseComment = commentService.getCommentById(productId, commentId); - return ResponseEntity.ok(responseComment); - } - - //update comment api - @PutMapping("/{productId}/update/{commentId}") - public ResponseEntity<CommentDto> updateComment(@PathVariable Long productId, - @RequestBody CommentDto commentDto, - @PathVariable Long commentId){ - CommentDto responseComment = commentService.updateComment(productId, commentDto, commentId); - return ResponseEntity.ok(responseComment); - } - - //delete comment api - @DeleteMapping("/{productId}/delete/{commentId}") - public ResponseEntity<String> deleteComment(@PathVariable Long productId, @PathVariable Long commentId){ - commentService.deleteComment(productId, commentId); - return ResponseEntity.ok("Comment with id: "+commentId+" is successfully:)"); - } - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ContactController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ContactController.java deleted file mode 100644 index d440aed..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/ContactController.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.ContactDto; -import com.manir.springbootecommercerestapi.service.ContactService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@RestController -@RequestMapping(value = "api/v1/contact") -public class ContactController { - @Autowired - private ContactService contactService; - - @PostMapping("/sendMessage") - public ResponseEntity<ContactDto> sendMessage(@RequestBody ContactDto contactDto, - HttpServletRequest request){ - ContactDto responseMessage = contactService.sendMessage(contactDto, request); - return new ResponseEntity<>(responseMessage, HttpStatus.CREATED); - } - - //get messages api - @PreAuthorize("hasRole('ADMIN')") - @GetMapping("/allMessages") - public List<ContactDto> getAllMessages(){ - return contactService.getMessages(); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/FaqController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/FaqController.java deleted file mode 100644 index 4c3ea0a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/FaqController.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.FaqDto; -import com.manir.springbootecommercerestapi.service.FaqService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping("api/v1/faq") -public class FaqController { - @Autowired - private FaqService faqService; - - //add faq api - @PreAuthorize("hasRole('ADMIN')") - @PostMapping("/addFaq") - public ResponseEntity<FaqDto> addFaq(@RequestBody FaqDto faqDto){ - FaqDto addedFaq = faqService.addFaq(faqDto); - return new ResponseEntity<>(addedFaq, HttpStatus.CREATED); - } - //list all faqs api - @PreAuthorize("hasRole('ADMIN')") - @GetMapping("/getAllFaqs") - public List<FaqDto> listAllFaqs(){ - List<FaqDto> faqs = faqService.listAllFaqs(); - return faqs; - } - - //get faq by id api - @PreAuthorize("hasRole('ADMIN')") - @GetMapping("/{id}") - public ResponseEntity<FaqDto> getFaqById(@PathVariable Long id){ - FaqDto faq = faqService.getFaqById(id); - return new ResponseEntity<>(faq, HttpStatus.OK); - } - - //update faq api - @PreAuthorize("hasRole('ADMIN')") - @PutMapping("/updateFaq/{id}") - public ResponseEntity<FaqDto> updateFaq(@RequestBody FaqDto faqDto, @PathVariable Long id){ - FaqDto updatedFaq = faqService.updateFaq(faqDto, id); - return new ResponseEntity<>(updatedFaq, HttpStatus.OK); - } - - //delete faq api - @PreAuthorize("hasRole('ADMIN')") - @DeleteMapping("/deleteFaq/{id}") - public ResponseEntity<String> deleteFaq(@PathVariable Long id){ - faqService.deleteFaq(id); - return new ResponseEntity<>("Faq with id: "+id+ " is deleted successfully", HttpStatus.OK); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java deleted file mode 100644 index 302422b..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.OrderDto; -import com.manir.springbootecommercerestapi.dto.OrderProductsDto; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import com.manir.springbootecommercerestapi.service.CommonService; -import com.manir.springbootecommercerestapi.service.OrderProductsService; -import com.manir.springbootecommercerestapi.service.OrderService; -import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -@RequestMapping(value = "api/v1/order") -public class OrderController { - - @Autowired - private OrderService orderService; - @Autowired - private OrderProductsService orderProductsService; - @Autowired - private CommonService commonService; - - //place order complete order api - @isAuthenticatedAsAdminOrUser - @PostMapping("/placeOrder") - public ResponseEntity<?> placeOrder(@AuthenticationPrincipal Authentication authentication){ - User customer = commonService.getCurrentAuthenticatedUser(authentication); - orderService.placeOrder(customer); - return new ResponseEntity<>("Order placed successfully", HttpStatus.CREATED); - } - - //find order by customer api - @isAuthenticatedAsAdminOrUser - @GetMapping("/findByCustomer") - public List<OrderDto> listOrdersByCustomer(@AuthenticationPrincipal Authentication authentication){ - - User customer = commonService.getCurrentAuthenticatedUser(authentication); - - List<OrderDto> customerOrders = orderService.listOrdersByCustomer(customer); - return customerOrders; - } - - - - //find ordered items by Customer - @isAuthenticatedAsAdminOrUser - @GetMapping("/findOrderedItemsByCustomer") - public List<OrderProductsDto> findOrderedItemsByCustomer(@AuthenticationPrincipal Authentication authentication){ - User customer = commonService.getCurrentAuthenticatedUser(authentication); - List<OrderProductsDto> customerOrderedItems = orderProductsService.findOrderItemsByCustomer(customer); - return customerOrderedItems; - } - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java deleted file mode 100644 index b34e2ed..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.ProductDto; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import com.manir.springbootecommercerestapi.response.ProductResponse; -import com.manir.springbootecommercerestapi.service.ProductService; -import com.manir.springbootecommercerestapi.utils.Constant; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.util.List; - -@RestController -@RequestMapping(value = "api/v1/products") -public class ProductController { - - @Autowired - private ProductService productService; - - //product create api - @PreAuthorize("hasRole('ADMIN')") - @RequestMapping(value = "/createProduct", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}) - public ResponseEntity<ProductDto> createProduct(@RequestPart("productDto") ProductDto productDto, - @RequestPart("file") MultipartFile file){ - ProductDto responseProduct = productService.createProduct(productDto, file); - return new ResponseEntity<>(responseProduct, HttpStatus.CREATED); - } - - //create product with category - @PreAuthorize("hasRole('ADMIN')") - @PostMapping("/{categoryId}/saveProductByCategoryId") - public ResponseEntity<ProductDto> saveProductByCategoryId(@PathVariable Long categoryId, - @RequestBody ProductDto productDto){ - ProductDto responseProduct = productService.saveProductByCategoryId(categoryId, productDto); - return new ResponseEntity<>(responseProduct, HttpStatus.CREATED); - } - - - - //get all products api - @GetMapping("/getAllProduct") - public CommonResponse getAllProduct(@RequestParam(value = "pageNo", defaultValue = Constant.DEFAULT_PAGE_NUMBER, required = false) int pageNo, - @RequestParam(value = "pageSize", defaultValue = Constant.DEFAULT_PAGE_SIZE, required = false) int pageSize, - @RequestParam(value = "sortBy", defaultValue = Constant.DEFAULT_SORT_BY, required = false) String sortBy, - @RequestParam(value = "sortDir", defaultValue = Constant.DEFAULT_SORT_DIRECTION, required = false) String sortDir){ - CommonResponse responseProductDtoList = productService.getAllProduct(pageNo, pageSize, sortBy, sortDir); - return responseProductDtoList; - } - - //get product by id api - @GetMapping("/{productId}") - public ResponseEntity<ProductDto> getProductById(@PathVariable Long productId){ - ProductDto responseProduct = productService.getProductById(productId); - return ResponseEntity.ok(responseProduct); - } - - //update product api - @PreAuthorize("hasRole('ADMIN')") - @PutMapping("/{categoryId}/updateProduct/{productId}") - public ResponseEntity<ProductDto> updateProduct(@PathVariable Long categoryId, - @RequestBody ProductDto productDto, - @PathVariable Long productId){ - ProductDto responseProduct = productService.updateProduct(categoryId, productDto, productId); - return ResponseEntity.ok(responseProduct); - } - - //delete product api - @PreAuthorize("hasRole('ADMIN')") - @DeleteMapping("/deleteProduct/{productId}") - public ResponseEntity<String> deleteProduct(@PathVariable Long productId){ - productService.deleteProduct(productId); - return new ResponseEntity<>("Product with id: "+ productId +" is deleted successfully:)", HttpStatus.OK); - } - - //search product api - @GetMapping("/search") - public List<ProductDto> searchProduct(@RequestParam(value = "query") String query){ - return productService.searchProduct(query); - } - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ProductImageGalleryController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ProductImageGalleryController.java deleted file mode 100644 index 028cee9..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/ProductImageGalleryController.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.service.ProductImageGalleryService; -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; - -@RestController -@RequestMapping(value = "api/v1/products") -public class ProductImageGalleryController { - - @Autowired - private ProductImageGalleryService productImageGalleryService; - - - //add image to product api - @PostMapping("/{productId}/addImage") - public ResponseEntity<String> addImageToProduct(@PathVariable Long productId, - @RequestParam("file")MultipartFile file){ - productImageGalleryService.addImageToProduct(productId, file); - return new ResponseEntity<>("Image successfully added to product with id : " + productId, HttpStatus.CREATED); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/SettingController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/SettingController.java deleted file mode 100644 index 053edbd..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/SettingController.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.dto.SettingDto; -import com.manir.springbootecommercerestapi.model.Setting; -import com.manir.springbootecommercerestapi.repository.SettingRepository; -import com.manir.springbootecommercerestapi.service.SettingService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import java.util.Optional; - -@RestController -@RequestMapping(value = "api/v1/setting") -public class SettingController { - @Autowired - private SettingService settingService; - @Autowired - private SettingRepository settingRepository; - - //post first setting api - @PreAuthorize("hasRole('ADMIN')") - @PostMapping("/createSetting") - public ResponseEntity<SettingDto> createSetting(@RequestBody SettingDto settingDto){ - SettingDto createdSetting = settingService.addSettingFirstTime(settingDto); - return new ResponseEntity<>(createdSetting, HttpStatus.CREATED); - } - - //edit existing setting api - @PreAuthorize("hasRole('ADMIN')") - @PutMapping("/editSetting") - public ResponseEntity<SettingDto> editSetting(@RequestBody SettingDto settingDto){ - Optional<Setting> existingSetting = settingRepository.findAll().stream().findFirst(); - SettingDto editedSetting = settingService.updateSetting(settingDto, existingSetting.get().getId()); - - return ResponseEntity.ok(editedSetting); - } - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java deleted file mode 100644 index c3bdfc5..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.manir.springbootecommercerestapi.controller; - -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.response.CartItemResponse; -import com.manir.springbootecommercerestapi.service.CommonService; -import com.manir.springbootecommercerestapi.service.ShoppingCartService; -import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; - -@RestController -@RequestMapping("api/v1/cart") -public class ShoppingCartController { - - @Resource - private ShoppingCartService shoppingCartService; - @Autowired - private CommonService commonService; - - //find by customer api - @isAuthenticatedAsAdminOrUser - @GetMapping("/findByCustomer") - public CartItemResponse findByCustomerId(@AuthenticationPrincipal Authentication authentication){ - - User customer = commonService.getCurrentAuthenticatedUser(authentication); - CartItemResponse responseCartItems = shoppingCartService.findByCustomer(customer); - return responseCartItems; - } - - //add item to the cart api - @isAuthenticatedAsAdminOrUser - @PostMapping("/addItem/{productId}/{quantity}") - public ResponseEntity<CartItemResponse> addCartItem(@AuthenticationPrincipal Authentication authentication, - @PathVariable Long productId, - @PathVariable Integer quantity){ - - User customer = commonService.getCurrentAuthenticatedUser(authentication); - CartItemResponse responseCartItem = shoppingCartService.addCartItem(customer, productId, quantity); - return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED); - } - - //update item quantity api - @isAuthenticatedAsAdminOrUser - @PutMapping("/updateItemQuantity/{productId}/{quantity}") - public ResponseEntity<CartItemResponse> updateItemQuantity(@AuthenticationPrincipal Authentication authentication, - @PathVariable Long productId, - @PathVariable Integer quantity){ - User customer = commonService.getCurrentAuthenticatedUser(authentication); - CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customer, productId, quantity); - return new ResponseEntity<>(responseCartItem, HttpStatus.OK); - } - - //delete item product api - @isAuthenticatedAsAdminOrUser - @DeleteMapping("/deleteItemProduct/{productId}") - public ResponseEntity<String> deleteItemProduct(@AuthenticationPrincipal Authentication authentication, - @PathVariable Long productId){ - - User customer = commonService.getCurrentAuthenticatedUser(authentication); - shoppingCartService.deleteItemProduct(customer, productId); - return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart"); - } - - - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/CartItemDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/CartItemDto.java deleted file mode 100644 index b5baf24..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/CartItemDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.manir.springbootecommercerestapi.model.Product; -import lombok.Data; - -@Data -public class CartItemDto { - private Long id; - private Integer quantity; - private String status; - @JsonIgnore - private Product product; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/CategoryDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/CategoryDto.java deleted file mode 100644 index c67eb17..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/CategoryDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; -import com.fasterxml.jackson.databind.annotation.JsonNaming; -import com.manir.springbootecommercerestapi.model.Category; -import lombok.Data; - -import java.util.Set; - -@Data -public class CategoryDto { - - private Long id; - private String title; - private String keywords; - private String description; - private String status; - - //private Category parent; - private Set<Category> children; - - //private Set<ProductDto> products; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/CommentDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/CommentDto.java deleted file mode 100644 index ab2284c..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/CommentDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class CommentDto { - - private Long id; - private String review; - private Integer rate; - private String status; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/ContactDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/ContactDto.java deleted file mode 100644 index 338891d..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/ContactDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class ContactDto { - private Long id; - private String name; - private String email; - private String phone; - private String subject; - private String message; - private String ipAddress; - private String status; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/FaqDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/FaqDto.java deleted file mode 100644 index a476603..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/FaqDto.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import com.manir.springbootecommercerestapi.model.BaseEntity; -import lombok.Data; - -@Data -public class FaqDto extends BaseEntity { - private Long id; - private String question; - private String answer; - private String status; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/ImageDataDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/ImageDataDto.java deleted file mode 100644 index b4ebf09..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/ImageDataDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class ImageDataDto { - - private Long id; - private String name; - private String type; - private byte[] imageData; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/LoginDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/LoginDto.java deleted file mode 100644 index 1c3c8a1..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/LoginDto.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class LoginDto { - private String userNameOrEmail; - private String password; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/OrderDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/OrderDto.java deleted file mode 100644 index e4c5156..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/OrderDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.manir.springbootecommercerestapi.model.User; -import lombok.Data; - -@Data -public class OrderDto { - private Long id; - private String name; - private String email; - private String phone; - private String address; - private double totalPrice; - private String note; - private String status; - - @JsonIgnore - private User customer; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/OrderProductsDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/OrderProductsDto.java deleted file mode 100644 index 166dad0..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/OrderProductsDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class OrderProductsDto { - private Long id; - private double productPrice; - private Integer productQuantity; - private double totalPrice; - private String note; - private String status; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/ProductDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/ProductDto.java deleted file mode 100644 index daee9ef..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/ProductDto.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; -import com.fasterxml.jackson.databind.annotation.JsonNaming; -import lombok.Data; - -import java.util.Set; - -@Data -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class) -@JsonIgnoreProperties({"hibernate_lazy_initializer", "handler"}) -public class ProductDto { - private Long id; - private String title; - private String keywords; - private String description; - private String detail; - private double price; - private Integer quantity; - private String status; - - private String image; - - private CategoryDto category; - - private Set<ImageDataDto> images; - - private Set<CommentDto> comments; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/ProfileDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/ProfileDto.java deleted file mode 100644 index ae0c350..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/ProfileDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class ProfileDto { - private Long id; - private String image; - private String address; - private String phone; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/SettingDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/SettingDto.java deleted file mode 100644 index 676cbc7..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/SettingDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class SettingDto { - private Long id; - private String title; - private String keywords; - private String description; - private String company; - private String address; - private String phone; - private String fax; - private String email; - private String smtpServer; - private String smtpEmail; - private String smtpPassword; - private Integer smtpPort; - private String facebook; - private String instagram; - private String twitter; - private String aboutUs; - private String contact; - private String reference; - private String status; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/SignUpDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/SignUpDto.java deleted file mode 100644 index a2e2eaa..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/dto/SignUpDto.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.manir.springbootecommercerestapi.dto; - -import lombok.Data; - -@Data -public class SignUpDto { - private String name; - private String username; - private String email; - private String password; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/exception/EcommerceApiException.java b/src/main/java/com/manir/springbootecommercerestapi/exception/EcommerceApiException.java deleted file mode 100644 index b536bfb..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/exception/EcommerceApiException.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.manir.springbootecommercerestapi.exception; - -import org.springframework.http.HttpStatus; - -public class EcommerceApiException extends RuntimeException{ - private String message; - private HttpStatus status; - - public EcommerceApiException(String message, HttpStatus status) { - this.message = message; - this.status = status; - } - - public EcommerceApiException(String message, String message1, HttpStatus status) { - super(message); - this.message = message1; - this.status = status; - } - - @Override - public String getMessage() { - return message; - } - - public HttpStatus getStatus() { - return status; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/exception/GlobalExceptionHandler.java b/src/main/java/com/manir/springbootecommercerestapi/exception/GlobalExceptionHandler.java deleted file mode 100644 index a9f69fd..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/exception/GlobalExceptionHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.manir.springbootecommercerestapi.exception; - -import com.manir.springbootecommercerestapi.response.ErrorDetail; -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.context.request.WebRequest; -import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; - -import java.util.Date; - -@RestControllerAdvice -public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { - - //Resource not found handler - @ExceptionHandler(ResourceNotFoundException.class) - public ResponseEntity<ErrorDetail> handleResourceNotFoundException(ResourceNotFoundException exception, WebRequest webRequest){ - ErrorDetail errorDetail = new ErrorDetail(new Date(), exception.getMessage(), webRequest.getDescription(false)); - return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND); - } - - //Ecommerce exception handler - @ExceptionHandler(EcommerceApiException.class) - public ResponseEntity<ErrorDetail> handleEcommerceApiException(EcommerceApiException exception, WebRequest webRequest){ - ErrorDetail errorDetail = new ErrorDetail(new Date(), exception.getMessage(), webRequest.getDescription(false)); - return new ResponseEntity<>(errorDetail, HttpStatus.BAD_REQUEST); - } - - //Global Exception handler - @ExceptionHandler(Exception.class) - public ResponseEntity<ErrorDetail> handleGlobalException(Exception exception, WebRequest webRequest){ - ErrorDetail errorDetail = new ErrorDetail(new Date(), exception.getMessage(), webRequest.getDescription(false)); - return new ResponseEntity<>(errorDetail, HttpStatus.INTERNAL_SERVER_ERROR); - } - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/exception/ResourceNotFoundException.java b/src/main/java/com/manir/springbootecommercerestapi/exception/ResourceNotFoundException.java deleted file mode 100644 index 66fc11e..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/exception/ResourceNotFoundException.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.manir.springbootecommercerestapi.exception; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(value = HttpStatus.NOT_FOUND) -public class ResourceNotFoundException extends RuntimeException{ - private String resourceName; - private Long fieldValue; - - public ResourceNotFoundException(String resourceName, Long fieldValue) { - super(String.format("%s with id : %s is not found !", resourceName, fieldValue)); - this.resourceName = resourceName; - this.fieldValue = fieldValue; - } - - public String getResourceName() { - return resourceName; - } - - public Long getFieldValue() { - return fieldValue; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/BaseEntity.java b/src/main/java/com/manir/springbootecommercerestapi/model/BaseEntity.java deleted file mode 100644 index e9e620f..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/BaseEntity.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.Data; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import javax.persistence.Column; -import javax.persistence.EntityListeners; -import javax.persistence.MappedSuperclass; -import java.time.LocalDateTime; - -@Data -@MappedSuperclass -/** - Auditing allows us : to see who created data and who updated - then we should enable jpa auditing... - **/ -@EntityListeners(AuditingEntityListener.class) -public abstract class BaseEntity { - - @CreatedDate - @Column(name = "created_at", updatable = false) - private LocalDateTime createdAt; - @CreatedBy - @Column(updatable = false) - private String createdBy; - - @LastModifiedDate - @Column(name = "updated_at", insertable = false) - private LocalDateTime updatedAt; - @LastModifiedBy - @Column(insertable = false) - private String updatedBy; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java b/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java deleted file mode 100644 index 5a1c4ea..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.persistence.*; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Entity -@Table(name = "cart_item") -public class CartItem extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @Column(name = "quantity") - private Integer quantity; - @Column(name = "status") - private String status; //pending, ordered - - //relation with product - @ManyToOne() - @JoinColumn(name = "product_id") - private Product product; - - //relation with customer - @ManyToOne() - @JoinColumn(name = "customer_id") - private User customer; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Category.java b/src/main/java/com/manir/springbootecommercerestapi/model/Category.java deleted file mode 100644 index 3862154..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Category.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import com.fasterxml.jackson.annotation.*; -import lombok.*; - -import javax.persistence.*; -import java.util.HashSet; -import java.util.Set; - -@AllArgsConstructor -@NoArgsConstructor -@Getter -@Setter -@Entity -@Table(name = "categories") -@JsonIgnoreProperties(value = {"children"}) -public class Category extends BaseEntity{ - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @Column(name = "title") - private String title; - @Column(name = "keywords") - private String keywords; - @Column(name = "description") - private String description; - @Column(name = "status") - private String status; - - //relation between parent and child categories - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "parent_id") - private Category parent; - @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL) - private Set<Category> children = new HashSet<>(); - - //relation between category and product - @JsonIgnore - @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) - private Set<Product> products = new HashSet<>(); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java b/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java deleted file mode 100644 index cd69ca0..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.*; - -import javax.persistence.*; -@AllArgsConstructor -@NoArgsConstructor -@Setter -@Getter -@Entity -@Table(name = "product_comments") -public class Comment extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @Column(name = "review") - private String review; - @Column(name = "rate") - private Integer rate; - @Column(name = "status") - private String status; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "product_id") - private Product product; - - //relation with user - @ManyToOne() - @JoinColumn(name = "customer_id") - private User customer; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Contact.java b/src/main/java/com/manir/springbootecommercerestapi/model/Contact.java deleted file mode 100644 index e321566..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Contact.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.persistence.*; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Entity -@Table(name = "contact") -public class Contact extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String name; - private String email; - private String phone; - private String subject; - private String message; - private String ipAddress; - private String status; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Faq.java b/src/main/java/com/manir/springbootecommercerestapi/model/Faq.java deleted file mode 100644 index 369f411..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Faq.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.persistence.*; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Entity -@Table(name = "faqs") -public class Faq extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String question; - private String answer; - private String status; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java b/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java deleted file mode 100644 index 45b3d3d..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.*; - -import javax.persistence.*; - -@Getter -@Setter -@AllArgsConstructor -@NoArgsConstructor -@Entity -@Table(name = "product_image_gallery") -public class ImageData extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @Column(name = "name") - private String name; - @Column(name = "type") - private String type; - - @Column(name = "imageData", length = 1000) - @Lob - private byte[] imageData; - - //relation with product entity - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "product_id") - private Product product; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Order.java b/src/main/java/com/manir/springbootecommercerestapi/model/Order.java deleted file mode 100644 index 189875c..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Order.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.*; - -import javax.persistence.*; -import java.util.Set; - -@AllArgsConstructor -@NoArgsConstructor -@Getter -@Setter -@Entity -@Table(name = "orders") -public class Order extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String name; - private String email; - private String phone; - private String address; - private double totalPrice; - private String note; - private String status; - - //relation with user - @ManyToOne() - @JoinColumn(name = "customer_id") - private User customer; - - //relation with order_products - @OneToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY, orphanRemoval = true, - mappedBy = "order") - private Set<OrderProducts> orderProducts; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java b/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java deleted file mode 100644 index 084ea70..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.persistence.*; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Entity -@Table(name = "order_products") -public class OrderProducts extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private double productPrice; - private Integer productQuantity; - private double totalPrice; - private String note; - private String status; - - //relation with user - @ManyToOne() - @JoinColumn(name = "customer_id") - private User customer; - - //relation with product - @ManyToOne() - @JoinColumn(name = "product_id") - private Product product; - - //relation with order - @ManyToOne() - @JoinColumn(name = "order_id") - private Order order; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Product.java b/src/main/java/com/manir/springbootecommercerestapi/model/Product.java deleted file mode 100644 index 1333432..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Product.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.*; - -import javax.persistence.*; -import java.util.Set; - -@AllArgsConstructor -@NoArgsConstructor -@Getter -@Setter -@Entity -@Table(name = "products") -public class Product extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @Column(name = "title") - private String title; - @Column(name = "keywords") - private String keywords; - @Column(name = "description") - private String description; - @Column(name = "detail") - private String detail; - @Column(name = "price") - private double price; - @Column(name = "quantity") - private Integer quantity; - @Column(name = "status") - private String status; - - //product image - @Lob - @Column(name = "image") - private String image; - - - //relation between category and product - @ManyToOne() - @JoinColumn(name = "category_id") - private Category category; - - //relation image gallery - @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true) - private Set<ImageData> images; - - //relation to product comment - @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true) - private Set<Comment> comments; - - - //relation to cart item - @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true) - private Set<CartItem> cartItems; - - //relation with order_products - @OneToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY, orphanRemoval = true, - mappedBy = "product") - private Set<OrderProducts> orderProducts; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Profile.java b/src/main/java/com/manir/springbootecommercerestapi/model/Profile.java deleted file mode 100644 index da592e4..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Profile.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.persistence.*; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Entity -@Table(name = "user_profile") -public class Profile extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String image; - private String address; - private String phone; - - //relation with user - @OneToOne(cascade = CascadeType.ALL) - @JoinColumn(name = "user_id", referencedColumnName = "id") - private User user; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Role.java b/src/main/java/com/manir/springbootecommercerestapi/model/Role.java deleted file mode 100644 index 4f792f4..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Role.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.Data; - -import javax.persistence.*; - -@Data -@Entity -@Table(name = "roles") -public class Role extends BaseEntity{ - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @Column(length = 60) - private String name; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Setting.java b/src/main/java/com/manir/springbootecommercerestapi/model/Setting.java deleted file mode 100644 index ea839f9..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Setting.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.persistence.*; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Entity -@Table(name = "settings") -public class Setting extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String title; - private String keywords; - private String description; - private String company; - private String address; - private String phone; - private String fax; - private String email; - private String smtpServer; - private String smtpEmail; - private String smtpPassword; - private Integer smtpPort; - private String facebook; - private String instagram; - private String twitter; - private String aboutUs; - private String contact; - private String reference; - private String status; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/User.java b/src/main/java/com/manir/springbootecommercerestapi/model/User.java deleted file mode 100644 index 5ca2a50..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/model/User.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.manir.springbootecommercerestapi.model; - -import lombok.*; - -import javax.persistence.*; -import java.util.Set; - -@Getter -@Setter -@AllArgsConstructor -@NoArgsConstructor -@Entity -@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = {"userName"}), - @UniqueConstraint(columnNames = {"email"}) -}) -public class User extends BaseEntity{ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - private String name; - private String userName; - private String email; - private String password; - - //relation with cart item - @OneToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY, orphanRemoval = true, - mappedBy = "customer") - private Set<CartItem> cartItems; - - //relation with role - @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinTable(name = "user_roles", - joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - private Set<Role> roles; - - //relation with order - @OneToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY, orphanRemoval = true, - mappedBy = "customer") - private Set<Order> orders; - - //relation with order_product - @OneToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY, orphanRemoval = true, - mappedBy = "customer") - private Set<OrderProducts> orderProducts; - - //relation with comment or review - @OneToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY, orphanRemoval = true, - mappedBy = "customer") - private Set<Comment> comments; - - //relation with profile - @OneToOne(mappedBy = "user") - private Profile user_profile; - } diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/CartItemRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/CartItemRepository.java deleted file mode 100644 index 5ff677a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/CartItemRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.CartItem; -import com.manir.springbootecommercerestapi.model.Product; -import com.manir.springbootecommercerestapi.model.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; - -import java.util.List; - -public interface CartItemRepository extends JpaRepository<CartItem, Long> { - - List<CartItem> findByCustomer(User customer); - - //CartItem findByCustomerAndProduct(User customer, Product product); - CartItem findByCustomerAndProduct(User customer, Product product); - - @Query("UPDATE CartItem c SET c.quantity = ?3 WHERE c.product.id = ?2 AND c.customer.id = ?1") - void updateItemQuantity(Long customerId, Long productId, Integer quantity); - - @Query("DELETE FROM CartItem c WHERE c.customer.id = ?1 AND c.product.id = ?2") - @Modifying - void deleteByCustomerAndProduct(Long customerId, Long productId); - - @Query("DELETE FROM CartItem c WHERE c.customer.id = ?1") - @Modifying - void deleteByCustomerId(Long customerId); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/CategoryRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/CategoryRepository.java deleted file mode 100644 index 04bd035..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/CategoryRepository.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Category; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.List; - -public interface CategoryRepository extends JpaRepository<Category, Long> { - -// @Query( -// value = "WITH RECURSIVE ancestors(id, parent_id, name, lvl) AS (" -// + " SELECT cat.id, cat.parent_id, cat.name, 1 AS lvl " -// + " FROM categories cat " -// + " WHERE cat.id = :categoryId " -// + " UNION ALL " -// + " SELECT parent.id, parent.parent_id, parent.name, child.lvl + 1 AS lvl " -// + " FROM categories parent " -// + " JOIN ancestors child " -// + " ON parent.id = child.parent_id " -// + " )" -// + "SELECT category_name from ancestors ORDER BY lvl DESC" -// , nativeQuery = true) -// List<String> findAncestry(@Param("categoryId") Long categoryId); - -// @Query("select distinct c from Category c " + -// "left join fetch c.parent cc " + -// "left join fetch c.children ch " + -// "where cc is null") -// List<Category> findAll(); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java deleted file mode 100644 index 8fa17c5..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Comment; -import com.manir.springbootecommercerestapi.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface CommentRepository extends JpaRepository<Comment, Long> { - List<Comment> findByProductId(Long productId); - List<Comment> findByCustomer(User customer); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/ContactRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/ContactRepository.java deleted file mode 100644 index 3e2911a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/ContactRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Contact; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface ContactRepository extends JpaRepository<Contact, Long> { -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/FaqRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/FaqRepository.java deleted file mode 100644 index 3fc9ed1..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/FaqRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Faq; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface FaqRepository extends JpaRepository<Faq, Long> { -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/OrderProductsRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/OrderProductsRepository.java deleted file mode 100644 index 03d331d..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/OrderProductsRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.OrderProducts; -import com.manir.springbootecommercerestapi.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface OrderProductsRepository extends JpaRepository<OrderProducts, Long> { - List<OrderProducts> findByCustomer(User customer); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/OrderRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/OrderRepository.java deleted file mode 100644 index d0e3573..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/OrderRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Order; -import com.manir.springbootecommercerestapi.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface OrderRepository extends JpaRepository<Order, Long> { - - List<Order> findByCustomer(User customer); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/ProductImageGalleryRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/ProductImageGalleryRepository.java deleted file mode 100644 index 930f15a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/ProductImageGalleryRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.ImageData; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface ProductImageGalleryRepository extends JpaRepository<ImageData, Long> { -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java deleted file mode 100644 index 419dd56..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Product; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - -import java.util.List; - -public interface ProductRepository extends JpaRepository<Product, Long> { - - @Query( - "SELECT p FROM Product p WHERE " + - "p.title LIKE CONCAT('%', :query, '%') " + - "or p.description LIKE CONCAT('%', :query, '%')" + - "or p.keywords LIKE CONCAT('%', :query, '%')" + - "or p.detail LIKE CONCAT('%', :query, '%')" - ) - List<Product> searchProduct(String query); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/RoleRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/RoleRepository.java deleted file mode 100644 index 1681e21..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/RoleRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Role; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.Optional; - -public interface RoleRepository extends JpaRepository<Role, Long> { - Optional<Role> findByName(String name); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/SettingRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/SettingRepository.java deleted file mode 100644 index 94b6cb4..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/SettingRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.Setting; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface SettingRepository extends JpaRepository<Setting, Long> { -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/UserRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/UserRepository.java deleted file mode 100644 index 9b9bc19..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/UserRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.manir.springbootecommercerestapi.repository; - -import com.manir.springbootecommercerestapi.model.User; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.Optional; - -public interface UserRepository extends JpaRepository<User, Long>{ - - Optional<User> findByEmail(String email); - Optional<User> findByUserNameOrEmail(String username, String email); - Optional<User> findByUserName(String username); - Boolean existsByUserName(String username); - Boolean existsByEmail(String email); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/response/CartItemResponse.java b/src/main/java/com/manir/springbootecommercerestapi/response/CartItemResponse.java deleted file mode 100644 index 5f07ec7..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/response/CartItemResponse.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.manir.springbootecommercerestapi.response; - - -import com.manir.springbootecommercerestapi.dto.CartItemDto; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class CartItemResponse { - private List<CartItemDto> content; - private double totalCost; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/response/CategoryResponse.java b/src/main/java/com/manir/springbootecommercerestapi/response/CategoryResponse.java deleted file mode 100644 index 87426f2..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/response/CategoryResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.manir.springbootecommercerestapi.response; - -import com.manir.springbootecommercerestapi.dto.CategoryDto; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class CategoryResponse { - - private List<CategoryDto> content; - private int pageNo; - private int pageSize; - private long totalElements; - private int totalPages; - private boolean last; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/response/CommonResponse.java b/src/main/java/com/manir/springbootecommercerestapi/response/CommonResponse.java deleted file mode 100644 index e1a8bc1..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/response/CommonResponse.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.manir.springbootecommercerestapi.response; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class CommonResponse <T> { - private List<T> content; - private int pageNo; - private int pageSize; - private long totalElements; - private int totalPages; - private boolean last; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/response/ErrorDetail.java b/src/main/java/com/manir/springbootecommercerestapi/response/ErrorDetail.java deleted file mode 100644 index 2a19589..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/response/ErrorDetail.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.manir.springbootecommercerestapi.response; - -import java.util.Date; - -public class ErrorDetail { - private Date timestamp; - private String message; - private String details; - - public ErrorDetail(Date timestamp, String message, String details) { - this.timestamp = timestamp; - this.message = message; - this.details = details; - } - - public Date getTimestamp() { - return timestamp; - } - - public String getMessage() { - return message; - } - - public String getDetails() { - return details; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/response/JWTAuthResponse.java b/src/main/java/com/manir/springbootecommercerestapi/response/JWTAuthResponse.java deleted file mode 100644 index 52c7ae9..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/response/JWTAuthResponse.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.manir.springbootecommercerestapi.response; - -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -public class JWTAuthResponse { - private String accessToken; - private String tokenType = "Bearer"; - - public JWTAuthResponse(String accessToken) { - this.accessToken = accessToken; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/response/ProductResponse.java b/src/main/java/com/manir/springbootecommercerestapi/response/ProductResponse.java deleted file mode 100644 index c68ca06..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/response/ProductResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.manir.springbootecommercerestapi.response; - -import com.manir.springbootecommercerestapi.dto.ProductDto; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class ProductResponse { - - private List<ProductDto> content; - private int pageNo; - private int pageSize; - private long totalElements; - private int totalPages; - private boolean last; -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/security/CustomUserDetails.java b/src/main/java/com/manir/springbootecommercerestapi/security/CustomUserDetails.java deleted file mode 100644 index 0fe8a10..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/security/CustomUserDetails.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.manir.springbootecommercerestapi.security; - -import com.manir.springbootecommercerestapi.model.User; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.util.Collection; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class CustomUserDetails implements UserDetails { - private User user; - @Override - public Collection<? extends GrantedAuthority> getAuthorities() { - return null; - } - - @Override - public String getPassword() { - return null; - } - - @Override - public String getUsername() { - return user.getEmail(); - } - - @Override - public boolean isAccountNonExpired() { - return false; - } - - @Override - public boolean isAccountNonLocked() { - return false; - } - - @Override - public boolean isCredentialsNonExpired() { - return false; - } - - @Override - public boolean isEnabled() { - return false; - } - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/security/CustomUserDetailsService.java b/src/main/java/com/manir/springbootecommercerestapi/security/CustomUserDetailsService.java deleted file mode 100644 index a21131b..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/security/CustomUserDetailsService.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.manir.springbootecommercerestapi.security; - -import com.manir.springbootecommercerestapi.model.Role; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import lombok.AllArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.Collection; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -public class CustomUserDetailsService implements UserDetailsService { - private final UserRepository userRepository; - - @Override - public UserDetails loadUserByUsername(String userNameOrEmail) throws UsernameNotFoundException { - User user = userRepository.findByUserNameOrEmail(userNameOrEmail, userNameOrEmail) - .orElseThrow( - () -> new UsernameNotFoundException("User not found with username or email: " + userNameOrEmail) - ); - return new org.springframework.security.core.userdetails.User( - user.getEmail(), - user.getPassword(), - mapRolesToAuthorities(user.getRoles()) - ); - } - - private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Set<Role> roles){ - return roles.stream() - .map(role -> new SimpleGrantedAuthority(role.getName())) - .collect(Collectors.toList()); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/security/JwtAuthenticationEntryPoint.java b/src/main/java/com/manir/springbootecommercerestapi/security/JwtAuthenticationEntryPoint.java deleted file mode 100644 index 5b485e4..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/security/JwtAuthenticationEntryPoint.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.manir.springbootecommercerestapi.security; - -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@Component -public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { - @Override - public void commence(HttpServletRequest request, - HttpServletResponse response, - AuthenticationException authException) throws IOException, ServletException { - - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/security/JwtAuthenticationFilter.java b/src/main/java/com/manir/springbootecommercerestapi/security/JwtAuthenticationFilter.java deleted file mode 100644 index 620ef9e..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/security/JwtAuthenticationFilter.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.manir.springbootecommercerestapi.security; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -public class JwtAuthenticationFilter extends OncePerRequestFilter { - - @Autowired - private JwtTokenProvider tokenProvider; - @Autowired - private CustomUserDetailsService userDetailsService; - - @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { - - //get jwt token from http request - String token = getJWTFromToken(request); - //validate token - if (StringUtils.hasText(token) && tokenProvider.validateToken(token)){ - //retrieve user form token - String userName = tokenProvider.getUserNameFromToken(token); - //load user associated with the token - UserDetails userDetails = userDetailsService.loadUserByUsername(userName); - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( - userDetails, null, userDetails.getAuthorities() - ); - //set spring security - authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - SecurityContextHolder.getContext().setAuthentication(authenticationToken); - } - filterChain.doFilter(request, response); - } - - //get jwt from token - //Bearer <accessToken> - private String getJWTFromToken(HttpServletRequest request){ - - String bearerToken = request.getHeader("Authorization"); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){ - return bearerToken.substring(7, bearerToken.length()); - } - return null; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/security/JwtTokenProvider.java b/src/main/java/com/manir/springbootecommercerestapi/security/JwtTokenProvider.java deleted file mode 100644 index 5e18a26..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/security/JwtTokenProvider.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.manir.springbootecommercerestapi.security; - -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import io.jsonwebtoken.*; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; - -import java.util.Date; - -@Component -public class JwtTokenProvider { - - @Value("${app.jwt-secret}") - private String jwtSecret; - @Value("${app.jwt-expiration-milliseconds}") - private int jwtExpirationTime; - - //generate token method - - public String generateToken(Authentication authentication){ - String userName = authentication.getName(); - Date currentDate = new Date(); - Date expireDate = new Date(currentDate.getTime() + jwtExpirationTime); - - String token = Jwts.builder() - .setSubject(userName) - .setIssuedAt(new Date()) - .setExpiration(expireDate) - .signWith(SignatureAlgorithm.HS512, jwtSecret) - .compact(); - - return token; - } - - //get username from the token, retrieve username from generated token - public String getUserNameFromToken(String token){ - Claims claims = Jwts.parser() - .setSigningKey(jwtSecret) - .parseClaimsJws(token) - .getBody(); - - return claims.getSubject(); - } - - //validate JWT token - public boolean validateToken(String token){ - try { - Jwts.parser() - .setSigningKey(jwtSecret) - .parseClaimsJws(token); - return true; - }catch (SignatureException e){ - throw new EcommerceApiException("Invalid JWT signature", HttpStatus.BAD_REQUEST); - }catch (MalformedJwtException e){ - throw new EcommerceApiException("Invalid JWT token", HttpStatus.BAD_REQUEST); - }catch (ExpiredJwtException e){ - throw new EcommerceApiException("Expired JWT token", HttpStatus.BAD_REQUEST); - }catch (UnsupportedJwtException e){ - throw new EcommerceApiException("Unsupported JWT token", HttpStatus.BAD_REQUEST); - }catch (IllegalArgumentException e){ - throw new EcommerceApiException("JWT claims string is empty", HttpStatus.BAD_REQUEST); - } - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/CategoryService.java b/src/main/java/com/manir/springbootecommercerestapi/service/CategoryService.java deleted file mode 100644 index ee7468c..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/CategoryService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.CategoryDto; -import com.manir.springbootecommercerestapi.response.CategoryResponse; -import com.manir.springbootecommercerestapi.response.CommonResponse; - -import java.util.List; - -public interface CategoryService { - - CategoryDto createCategory(CategoryDto categoryDto); - CommonResponse getAllCategory(int pageNo, int pageSize, String sortBy, String sortDir); - CategoryDto getCategoryById(Long categoryId); - CategoryDto updateCategory(CategoryDto categoryDto, Long categoryId); - void deleteCategory(Long categoryId); - - //List<CategoryDto> findChildren(Long parentId); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java b/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java deleted file mode 100644 index 575ad74..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - - -import com.manir.springbootecommercerestapi.dto.CommentDto; -import com.manir.springbootecommercerestapi.model.User; - -import java.util.List; - -public interface CommentService { - - CommentDto createComment(User customer, Long productId, CommentDto commentDto); - - List<CommentDto> findCommentByCustomer(User customer); - List<CommentDto> getAllComments(); - List<CommentDto> getAllCommentsByProductId(Long productId); - CommentDto getCommentById(Long productId, Long commentId); - CommentDto updateComment(Long productId, CommentDto commentDto, Long commentId); - void deleteComment(Long productId, Long commentId); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java b/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java deleted file mode 100644 index f973fb0..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.CartItemDto; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.response.CartItemResponse; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import org.springframework.data.domain.Page; -import org.springframework.security.core.Authentication; - -import java.util.List; - -public interface CommonService<T> { - - //CommonResponse getAllCategoryOrProduct(int pageNo, int pageSize, String sortBy, String sortDir); - CommonResponse getResponseContent(Page<T> page, List<T> dtoList); - - //cart iem response handler - CartItemResponse getResponse(CartItemDto cartItemDto); - - //get current authenticated user - User getCurrentAuthenticatedUser(Authentication authentication); - - //entity mapper - T mapToEntity(T type); - - //dto mapper - T mapToDto(T type); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/ContactService.java b/src/main/java/com/manir/springbootecommercerestapi/service/ContactService.java deleted file mode 100644 index 65223b0..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/ContactService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.ContactDto; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -public interface ContactService { - ContactDto sendMessage(ContactDto contactDto, HttpServletRequest request); - List<ContactDto> getMessages(); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/FaqService.java b/src/main/java/com/manir/springbootecommercerestapi/service/FaqService.java deleted file mode 100644 index acfe24e..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/FaqService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.FaqDto; - -import java.util.List; - -public interface FaqService { - FaqDto addFaq(FaqDto faqDto); - List<FaqDto> listAllFaqs(); - FaqDto getFaqById(Long id); - FaqDto updateFaq(FaqDto faqDto, Long id); - void deleteFaq(Long id); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CategoryServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CategoryServiceImpl.java deleted file mode 100644 index 8c0ef5d..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CategoryServiceImpl.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.CategoryDto; -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.repository.CategoryRepository; -import com.manir.springbootecommercerestapi.model.Category; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import com.manir.springbootecommercerestapi.service.CategoryService; -import com.manir.springbootecommercerestapi.service.CommonService; -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.List; -import java.util.stream.Collectors; - -@Service -public class CategoryServiceImpl implements CategoryService { - - private static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class); - - @Resource(name = "categoryRepository") - private CategoryRepository categoryRepository; - @Resource(name = "modelMapper") - private ModelMapper modelMapper; - - @Resource - private CommonService commonService; - - @Override - public CategoryDto createCategory(CategoryDto categoryDto) { - //map dto to entity - Category category = mapToEntity(categoryDto); - //save entity - Category newCategory = categoryRepository.save(category); - //map back entity to dto - CategoryDto responseCategoryDto = mapToDto(newCategory); - - return responseCategoryDto; - } - - @Override - public CommonResponse getAllCategory(int pageNo, int pageSize, String sortBy, String sortDir) { - Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending(); - Pageable pageable = PageRequest.of(pageNo, pageSize, sort); - Page<Category> categories = categoryRepository.findAll(pageable); - - List<Category> categoryList = categories.getContent(); - //map all categories to dto - List<CategoryDto> categoryDtoList = categoryList.stream() - .map(category -> mapToDto(category)) - .collect(Collectors.toList()); - - CommonResponse categoryResponse = commonService.getResponseContent(categories, categoryDtoList); - return categoryResponse; - } - - @Override - public CategoryDto getCategoryById(Long categoryId) { - - Category category = categoryRepository.findById(categoryId) - .orElseThrow( - () -> new ResourceNotFoundException("Category", categoryId) - ); - //map entity to dto - CategoryDto responseCategory = mapToDto(category); - - return responseCategory; - } - - @Override - public CategoryDto updateCategory(CategoryDto categoryDto, Long categoryId) { - - Category category = categoryRepository.findById(categoryId) - .orElseThrow( - () -> new ResourceNotFoundException("Category", categoryId) - ); - - category.setTitle(categoryDto.getTitle()); - category.setDescription(categoryDto.getDescription()); - category.setKeywords(categoryDto.getKeywords()); - category.setStatus(categoryDto.getStatus()); - Category updatedCategory = categoryRepository.save(category); - //map entity to dto - CategoryDto responseCategory = mapToDto(updatedCategory); - return responseCategory; - } - - @Override - public void deleteCategory(Long categoryId) { - Category category = categoryRepository.findById(categoryId) - .orElseThrow( - () -> new ResourceNotFoundException("Category", categoryId) - ); - categoryRepository.delete(category); - } - - private CategoryDto mapToDto(Category category){ - CategoryDto categoryDto = modelMapper.map(category, CategoryDto.class); - return categoryDto; - } - - private Category mapToEntity(CategoryDto categoryDto){ - Category category = modelMapper.map(categoryDto, Category.class); - return category; - } - -// private static void listCategories(Session session) { -// Category electronics = session.get(Category.class, 1); -// -// Set<Category> children = electronics.getChildren(); -// -// System.out.println(electronics.getTitle()); -// -// for (Category child : children) { -// System.out.println("--" + child.getTitle()); -// printChildren(child, 1); -// } -// } -// -// private static void printChildren(Category parent, int subLevel) { -// Set<Category> children = parent.getChildren(); -// -// for (Category child : children) { -// for (int i = 0; i <= subLevel; i++) System.out.print("--"); -// -// System.out.println(child.getTitle()); -// -// printChildren(child, subLevel + 1); -// } -// } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java deleted file mode 100644 index f3ade8d..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.CommentDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.CommentRepository; -import com.manir.springbootecommercerestapi.repository.ProductRepository; -import com.manir.springbootecommercerestapi.model.Comment; -import com.manir.springbootecommercerestapi.model.Product; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import com.manir.springbootecommercerestapi.service.CommentService; -import org.modelmapper.ModelMapper; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.List; -import java.util.stream.Collectors; - -@Service -public class CommentServiceImpl implements CommentService { - - @Resource - private ModelMapper modelMapper; - @Resource - private CommentRepository commentRepository; - @Resource - private ProductRepository productRepository; - @Resource - private UserRepository userRepository; - - @Override - public CommentDto createComment(User customer, Long productId, CommentDto commentDto) { - User user = findCustomerById(customer.getId()); - Product product = findProductById(productId); - //convert to entity - Comment comment = mapToEntity(commentDto); - //save to db - comment.setProduct(product); - comment.setCustomer(user); - Comment createdComment = commentRepository.save(comment); - //convert to dto - CommentDto responseComment = mapToDto(createdComment); - - return responseComment; - } - - @Override - public List<CommentDto> findCommentByCustomer(User customer) { - List<Comment> comments = commentRepository.findByCustomer(customer); - if (comments.size() == 0){ - throw new EcommerceApiException("User has no comment or review", HttpStatus.BAD_REQUEST); - } - List<CommentDto> commentDtoList = comments.stream() - .map(comment -> mapToDto(comment)) - .collect(Collectors.toList()); - return commentDtoList; - } - - @Override - public List<CommentDto> getAllComments() { - List<Comment> comments = commentRepository.findAll(); - List<CommentDto> commentDtoList = comments.stream() - .map(comment -> mapToDto(comment)) - .collect(Collectors.toList()); - return commentDtoList; - } - - @Override - public List<CommentDto> getAllCommentsByProductId(Long productId) { - List<Comment> comments = commentRepository.findByProductId(productId); - List<CommentDto> commentDtoList = comments.stream() - .map(comment -> mapToDto(comment)) - .collect(Collectors.toList()); - return commentDtoList; - } - - @Override - public CommentDto getCommentById(Long productId, Long commentId) { - - Product product = findProductById(productId); - Comment comment = findCommentById(commentId); - - if (!comment.getProduct().getId().equals(product.getId())){ - throw new EcommerceApiException("Comment does not belong to product", HttpStatus.BAD_REQUEST); - } - - return mapToDto(comment); - } - - @Override - public CommentDto updateComment(Long productId, CommentDto commentDto, Long commentId) { - Product product = findProductById(productId); - Comment comment = findCommentById(commentId); - - if (!comment.getProduct().getId().equals(product.getId())){ - throw new EcommerceApiException("Comment does not belong to product", HttpStatus.BAD_REQUEST); - } - comment.setReview(commentDto.getReview()); - comment.setRate(commentDto.getRate()); - comment.setStatus(commentDto.getStatus()); - Comment updatedComment = commentRepository.save(comment); - - return mapToDto(updatedComment); - } - - @Override - public void deleteComment(Long productId, Long commentId) { - Product product = findProductById(productId); - Comment comment = findCommentById(commentId); - if (!comment.getProduct().getId().equals(product.getId())){ - throw new EcommerceApiException("Comment does not belong to product", HttpStatus.BAD_REQUEST); - } - commentRepository.delete(comment); - } - - //map to dto - private CommentDto mapToDto(Comment comment){ - CommentDto commentDto = modelMapper.map(comment, CommentDto.class); - return commentDto; - } - - //map to entity - private Comment mapToEntity(CommentDto commentDto){ - Comment comment = modelMapper.map(commentDto, Comment.class); - return comment; - } - - private Product findProductById(Long productId){ - Product product = productRepository.findById(productId).orElseThrow(()->new ResourceNotFoundException("Product", productId)); - return product; - } - - private Comment findCommentById(Long commentId){ - Comment comment = commentRepository.findById(commentId).orElseThrow(()->new ResourceNotFoundException("Comment", commentId)); - return comment; - } - - private User findCustomerById(Long customerId){ - User customer = userRepository.findById(customerId).orElseThrow(()->new ResourceNotFoundException("Customer", customerId)); - return customer; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java deleted file mode 100644 index bc633ab..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.CartItemDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import com.manir.springbootecommercerestapi.response.CartItemResponse; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import com.manir.springbootecommercerestapi.service.CommonService; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.http.HttpStatus; -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - - -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.List; - -@Service -@Slf4j -@AllArgsConstructor -@Component("commonService") -public class CommonServiceImpl implements CommonService{ - - private static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class); - - @Resource(name = "userRepository") - private final UserRepository userRepository; - @Resource(name = "modelMapper") - private final ModelMapper modelMapper; - - @Override - public CommonResponse getResponseContent(Page page, List dtoList) { - - CommonResponse commonResponse = new CommonResponse(); - commonResponse.setContent(dtoList); - commonResponse.setPageNo(page.getNumber()); - commonResponse.setPageSize(page.getSize()); - commonResponse.setTotalPages(page.getTotalPages()); - commonResponse.setTotalElements(page.getTotalElements()); - commonResponse.setLast(page.isLast()); - - return commonResponse; - } - - @Override - public CartItemResponse getResponse(CartItemDto cartItemDto) { - - CartItemResponse cartItemResponse = new CartItemResponse(); - - double totalPrice = cartItemDto.getProduct().getPrice() * cartItemDto.getQuantity(); - List<CartItemDto> cartItemDtoList = new ArrayList<>(); - cartItemDtoList.add(cartItemDto); - cartItemResponse.setContent(cartItemDtoList); - cartItemResponse.setTotalCost(totalPrice); - return cartItemResponse; - } - - @Override - public User getCurrentAuthenticatedUser(Authentication authentication) { - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null || authentication instanceof AnonymousAuthenticationToken){ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } - String currentUserEmail = authentication.getName(); - User currentUser = userRepository.findByEmail(currentUserEmail) - .orElseThrow( - () -> new UsernameNotFoundException("User Not found") - ); - - return currentUser; - } - - @Override - public Object mapToEntity(Object type) { - Object entityObject = modelMapper.map(type, Object.class); - return entityObject; - } - - @Override - public Object mapToDto(Object type) { - Object dtoObject = modelMapper.map(type, Object.class); - return dtoObject; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ContactServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ContactServiceImpl.java deleted file mode 100644 index db39d0a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ContactServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.ContactDto; -import com.manir.springbootecommercerestapi.model.Contact; -import com.manir.springbootecommercerestapi.repository.ContactRepository; -import com.manir.springbootecommercerestapi.service.ContactService; -import com.manir.springbootecommercerestapi.utils.RequestClientIP; -import lombok.AllArgsConstructor; -import org.modelmapper.ModelMapper; -import org.springframework.stereotype.Service; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -public class ContactServiceImpl implements ContactService { - - @Resource(name = "contactRepository") - private final ContactRepository contactRepository; - @Resource(name = "modelMapper") - private final ModelMapper modelMapper; - @Override - public ContactDto sendMessage(ContactDto contactDto, HttpServletRequest request) { - - Contact contact = mapToEntity(contactDto); - String ipAddress = RequestClientIP.getClientIpAddress(request); - contact.setIpAddress(ipAddress); - Contact createdMessage = contactRepository.save(contact); - - return mapToDto(createdMessage); - } - - @Override - public List<ContactDto> getMessages() { - List<Contact> messages = contactRepository.findAll(); - - return messages.stream() - .map(message -> mapToDto(message)) - .collect(Collectors.toList()); - } - - //map to entity - private Contact mapToEntity(ContactDto contactDto){ - Contact contact = modelMapper.map(contactDto, Contact.class); - return contact; - } - //map to dto - private ContactDto mapToDto(Contact contact){ - ContactDto contactDto = modelMapper.map(contact, ContactDto.class); - return contactDto; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/FaqServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/FaqServiceImpl.java deleted file mode 100644 index 1732722..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/FaqServiceImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.FaqDto; -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.model.Faq; -import com.manir.springbootecommercerestapi.repository.FaqRepository; -import com.manir.springbootecommercerestapi.service.CommonService; -import com.manir.springbootecommercerestapi.service.FaqService; -import com.manir.springbootecommercerestapi.service.MapperService; -import lombok.AllArgsConstructor; -import org.modelmapper.ModelMapper; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -public class FaqServiceImpl implements FaqService { - @Resource(name = "faqRepository") - private final FaqRepository faqRepository; - @Resource(name = "modelMapper") - private final ModelMapper modelMapper; - @Resource(name = "mapperService") - private final MapperService<Faq, FaqDto> mapperService; - - @Override - public FaqDto addFaq(FaqDto faqDto) { - Faq faq = mapperService.mapToEntity(faqDto); - Faq addedFaq = faqRepository.save(faq); - - return mapperService.mapToDto(addedFaq); - } - - @Override - public List<FaqDto> listAllFaqs() { - List<Faq> faqs = faqRepository.findAll(); - return faqs.stream().map(faq -> mapperService.mapToDto(faq)).collect(Collectors.toList()); - } - - @Override - public FaqDto getFaqById(Long id) { - Faq faq = faqRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Faq", id)); - return mapToDto(faq); - } - - @Override - public FaqDto updateFaq(FaqDto faqDto, Long id) { - Faq faq = faqRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Faq", id)); - faq.setQuestion(faqDto.getQuestion()); - faq.setAnswer(faqDto.getAnswer()); - Faq updatedFaq = faqRepository.save(faq); - return mapToDto(updatedFaq); - } - - @Override - public void deleteFaq(Long id) { - Faq faq = faqRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Faq", id)); - faqRepository.delete(faq); - } - - private FaqDto mapToDto(Faq faq){ - FaqDto faqDto = modelMapper.map(faq, FaqDto.class); - return faqDto; - } - //map to entity - private Faq mapToEntity(FaqDto faqDto){ - Faq faq = modelMapper.map(faqDto, Faq.class); - return faq; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderProductsServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderProductsServiceImpl.java deleted file mode 100644 index 0a3e532..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderProductsServiceImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.OrderProductsDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.model.OrderProducts; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.OrderProductsRepository; -import com.manir.springbootecommercerestapi.service.OrderProductsService; -import lombok.AllArgsConstructor; -import org.modelmapper.ModelMapper; -import org.modelmapper.convention.MatchingStrategies; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -public class OrderProductsServiceImpl implements OrderProductsService { - - @Resource(name = "orderProductsRepository") - private final OrderProductsRepository orderProductsRepository; - @Resource(name = "modelMapper") - private final ModelMapper modelMapper; - - @Override - public void addOrderProducts(OrderProducts orderProducts) { - orderProductsRepository.save(orderProducts); - } - - @Override - public List<OrderProductsDto> findOrderItemsByCustomer(User customer) { - - List<OrderProducts> orderProducts = orderProductsRepository.findByCustomer(customer); - if (orderProducts.size() == 0){ - throw new EcommerceApiException("User has no ordered products", HttpStatus.BAD_REQUEST); - } - List<OrderProductsDto> orderProductsDtoList = orderProducts.stream() - .map(orderProduct -> mapToDto(orderProduct)) - .collect(Collectors.toList()); - return orderProductsDtoList; - } - - //map to dto - private OrderProductsDto mapToDto(OrderProducts orderProducts){ - modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); - OrderProductsDto orderProductsDto = modelMapper.map(orderProducts, OrderProductsDto.class); - - return orderProductsDto; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java deleted file mode 100644 index 72a6138..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.CartItemDto; -import com.manir.springbootecommercerestapi.dto.OrderDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.model.Order; -import com.manir.springbootecommercerestapi.model.OrderProducts; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.CartItemRepository; -import com.manir.springbootecommercerestapi.repository.OrderRepository; -import com.manir.springbootecommercerestapi.response.CartItemResponse; -import com.manir.springbootecommercerestapi.service.OrderProductsService; -import com.manir.springbootecommercerestapi.service.OrderService; -import com.manir.springbootecommercerestapi.service.ShoppingCartService; -import lombok.AllArgsConstructor; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - -import javax.transaction.Transactional; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -public class OrderServiceImpl implements OrderService { - - @Autowired - private final OrderRepository orderRepository; - @Autowired - private final OrderProductsService orderProductsService; - @Autowired - private final CartItemRepository cartItemRepository; - @Autowired - private final ShoppingCartService shoppingCartService; - @Autowired - private final ModelMapper modelMapper; - - @Override - @Transactional - public void placeOrder(User customer) { - CartItemResponse cartItemDto = shoppingCartService.findByCustomer(customer); - //set order fields - OrderDto orderDto = setFields(cartItemDto, customer); - //save order to the db - OrderDto savedOrder = saveOrder(orderDto); - List<CartItemDto> cartItemDtoList = cartItemDto.getContent(); - for(CartItemDto cartItem : cartItemDtoList){ - OrderProducts orderProducts = new OrderProducts(); - orderProducts.setCustomer(customer); - orderProducts.setProduct(cartItem.getProduct()); - orderProducts.setOrder(mapToEntity(savedOrder)); - orderProducts.setProductPrice(cartItem.getProduct().getPrice()); - orderProducts.setProductQuantity(cartItem.getQuantity()); - orderProducts.setTotalPrice(cartItem.getProduct().getPrice()*cartItem.getQuantity()); - orderProductsService.addOrderProducts(orderProducts); - } - cartItemRepository.deleteByCustomerId(customer.getId()); - } - - @Override - public OrderDto saveOrder(OrderDto orderDto) { - //convert to entity - Order order = mapToEntity(orderDto); - //save order to db - Order placedOrder = orderRepository.save(order); - return mapToDto(placedOrder); - } - - private OrderDto setFields(CartItemResponse cartItemDto, User customer){ - OrderDto orderDto = new OrderDto(); - orderDto.setTotalPrice(cartItemDto.getTotalCost()); - orderDto.setEmail(customer.getEmail()); - orderDto.setName(customer.getName()); - orderDto.setCustomer(customer); - - return orderDto; - } - @Override - public List<OrderDto> listOrdersByCustomer(User customer) { - List<Order> orders = orderRepository.findByCustomer(customer); - if (orders.size() == 0){ - throw new EcommerceApiException("User has no order", HttpStatus.BAD_REQUEST); - } - List<OrderDto> orderDtoList = orders.stream() - .map(order -> mapToDto(order)) - .collect(Collectors.toList()); - return orderDtoList; - } - - //map to Entity - private Order mapToEntity(OrderDto orderDto){ - Order order = modelMapper.map(orderDto, Order.class); - return order; - } - //map to Dto - private OrderDto mapToDto(Order order){ - OrderDto orderDto = modelMapper.map(order, OrderDto.class); - return orderDto; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductImageGalleryServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductImageGalleryServiceImpl.java deleted file mode 100644 index 42c149a..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductImageGalleryServiceImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.repository.ProductImageGalleryRepository; -import com.manir.springbootecommercerestapi.repository.ProductRepository; -import com.manir.springbootecommercerestapi.model.ImageData; -import com.manir.springbootecommercerestapi.model.Product; -import com.manir.springbootecommercerestapi.service.ProductImageGalleryService; -import com.manir.springbootecommercerestapi.utils.ImageUtils; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import javax.annotation.Resource; -import java.io.IOException; - -@Service -public class ProductImageGalleryServiceImpl implements ProductImageGalleryService { - - @Resource - private ProductImageGalleryRepository productImageGalleryRepository; - @Resource - private ProductRepository productRepository; - - @Override - public ImageData addImageToProduct(Long productId, MultipartFile file) { - - Product product = productRepository.findById(productId) - .orElseThrow( - () -> new ResourceNotFoundException("Product", productId) - ); - - ImageData addedImage = null; - try { - addedImage = productImageGalleryRepository.save(uploadImage(file,product)); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return addedImage; - } - - - private ImageData uploadImage(MultipartFile file, Product product ) throws IOException { - ImageData imageData = new ImageData(); - imageData.setName(file.getOriginalFilename()); - imageData.setType(file.getContentType()); - imageData.setImageData(ImageUtils.compressImage(file.getBytes())); - - imageData.setProduct(product); - return imageData; - } - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java deleted file mode 100644 index 9b3dcb6..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.ProductDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.repository.CategoryRepository; -import com.manir.springbootecommercerestapi.repository.ProductRepository; -import com.manir.springbootecommercerestapi.model.Category; -import com.manir.springbootecommercerestapi.model.Product; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import com.manir.springbootecommercerestapi.service.CommonService; -import com.manir.springbootecommercerestapi.service.ProductService; -import lombok.extern.slf4j.Slf4j; -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import javax.annotation.Resource; -import java.io.IOException; -import java.util.Base64; -import java.util.List; -import java.util.stream.Collectors; - -@Service -@Slf4j -public class ProductServiceImpl implements ProductService { - - private static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class); - - @Resource(name = "modelMapper") - private ModelMapper modelMapper; - @Resource(name = "productRepository") - private ProductRepository productRepository; - @Resource(name = "categoryRepository") - private CategoryRepository categoryRepository; - - @Resource - private CommonService commonService; - - @Override - public ProductDto createProduct(ProductDto productDto, MultipartFile file) { - //map to entity - productDto.setImage(uploadProductImage(file)); - Product product = mapToEntity(productDto); - Product createdProduct = productRepository.save(product); - //map to dto - ProductDto responseProduct = mapToDto(createdProduct); - return responseProduct; - } - - @Override - public CommonResponse getAllProduct(int pageNo, int pageSize, String sortBy, String sortDir) { - - Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending(); - - Pageable pageable = PageRequest.of(pageNo, pageSize, sort); - Page<Product> products = productRepository.findAll(pageable); - - List<Product> productList = products.getContent(); - //map to dtos - List<ProductDto> productDtoList = productList.stream() - .map(product -> mapToDto(product)) - .collect(Collectors.toList()); - - CommonResponse productResponse = commonService.getResponseContent(products, productDtoList); - return productResponse; - } - - @Override - public ProductDto getProductById(Long productId) { - - Product product = productRepository.findById(productId) - .orElseThrow( - ()->new ResourceNotFoundException("Product", productId) - ); - //map to dto - ProductDto responseProduct = mapToDto(product); - - return responseProduct; - } - - @Override - public ProductDto updateProduct(Long categoryId, ProductDto productDto, Long productId) { - Product product = productRepository.findById(productId) - .orElseThrow( - ()->new ResourceNotFoundException("Product", productId) - ); - Category category = categoryRepository.findById(categoryId) - .orElseThrow( - ()->new ResourceNotFoundException("Category", categoryId) - ); - product.setTitle(productDto.getTitle()); - product.setDescription(productDto.getDescription()); - product.setKeywords(productDto.getKeywords()); - product.setPrice(productDto.getPrice()); - product.setDetail(productDto.getDetail()); - product.setQuantity(productDto.getQuantity()); - product.setStatus(productDto.getStatus()); - product.setCategory(category); - Product updatedProduct = productRepository.save(product); - //map to dto - ProductDto responseProduct = mapToDto(updatedProduct); - return responseProduct; - } - - @Override - public void deleteProduct(Long productId) { - Product product = productRepository.findById(productId) - .orElseThrow( - ()->new ResourceNotFoundException("Product", productId) - ); - productRepository.delete(product); - } - - @Override - public ProductDto saveProductByCategoryId(Long categoryId, ProductDto productDto) { - Category category = categoryRepository.findById(categoryId) - .orElseThrow( () -> new ResourceNotFoundException("Category", categoryId)); - Product product = mapToEntity(productDto); - - product.setCategory(category); - Product createdProduct = productRepository.save(product); - ProductDto responseProduct = mapToDto(createdProduct); - - return responseProduct; - } - - @Override - public List<ProductDto> searchProduct(String query) { - List<Product> products = productRepository.searchProduct(query); - if (products.size() == 0){ - throw new EcommerceApiException("No product is found", HttpStatus.BAD_REQUEST); - } - List<ProductDto> productDtoList = products.stream() - .map(product -> mapToDto(product)) - .collect(Collectors.toList()); - return productDtoList; - } - - //upload image - private String uploadProductImage(MultipartFile file){ - ProductDto productDto = new ProductDto(); - String fileName = StringUtils.cleanPath(file.getOriginalFilename()); - if(fileName.contains("..")){ - logger.error("It is a valid file"); - } - try { - productDto.setImage(Base64.getEncoder().encodeToString(file.getBytes())); - } catch (IOException e) { - throw new RuntimeException(e); - } - return productDto.getImage(); - } - - - //map to dto - private ProductDto mapToDto(Product product){ - ProductDto productDto = modelMapper.map(product, ProductDto.class); - return productDto; - } - //map to entity - private Product mapToEntity(ProductDto productDto){ - Product product = modelMapper.map(productDto, Product.class); - return product; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/SettingServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/SettingServiceImpl.java deleted file mode 100644 index b697560..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/SettingServiceImpl.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.SettingDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.model.Setting; -import com.manir.springbootecommercerestapi.repository.SettingRepository; -import com.manir.springbootecommercerestapi.service.SettingService; -import lombok.AllArgsConstructor; -import org.modelmapper.ModelMapper; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.Optional; - -@Service -@AllArgsConstructor -public class SettingServiceImpl implements SettingService { - @Resource(name = "settingRepository") - private final SettingRepository settingRepository; - @Resource(name = "modelMapper") - private final ModelMapper modelMapper; - - @Override - public SettingDto addSettingFirstTime(SettingDto settingDto) { - - Optional<Setting> setting = settingRepository.findAll().stream().findFirst(); - if (!setting.isPresent()){ - Setting firstSetting = mapToEntity(settingDto); - Setting saveSetting = settingRepository.save(firstSetting); - return mapToDto(saveSetting); - }else { - throw new EcommerceApiException("Setting already exists, please edit it only", HttpStatus.BAD_REQUEST); - } - } - - @Override - public SettingDto updateSetting(SettingDto settingDto, Long id) { - Setting setting = settingRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Setting", id)); - setting.setTitle(settingDto.getTitle()); - setting.setKeywords(settingDto.getKeywords()); - setting.setDescription(settingDto.getDescription()); - setting.setCompany(settingDto.getCompany()); - setting.setAddress(settingDto.getAddress()); - setting.setPhone(settingDto.getPhone()); - setting.setFax(settingDto.getFax()); - setting.setEmail(settingDto.getEmail()); - setting.setSmtpServer(settingDto.getSmtpServer()); - setting.setSmtpEmail(settingDto.getSmtpEmail()); - setting.setSmtpPassword(settingDto.getSmtpPassword()); - setting.setSmtpPort(settingDto.getSmtpPort()); - setting.setFacebook(settingDto.getFacebook()); - setting.setInstagram(settingDto.getInstagram()); - setting.setTwitter(settingDto.getTwitter()); - setting.setAboutUs(settingDto.getAboutUs()); - setting.setContact(settingDto.getContact()); - setting.setContact(settingDto.getReference()); - //save setting changes - Setting editedSetting = settingRepository.save(setting); - - return mapToDto(editedSetting); - } - - //map to dto - private SettingDto mapToDto(Setting setting){ - SettingDto settingDto = modelMapper.map(setting, SettingDto.class); - return settingDto; - } - //map to entity - private Setting mapToEntity(SettingDto settingDto){ - Setting setting = modelMapper.map(settingDto, Setting.class); - return setting; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ShoppingCartServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ShoppingCartServiceImpl.java deleted file mode 100644 index cc98060..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ShoppingCartServiceImpl.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.CartItemDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; -import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; -import com.manir.springbootecommercerestapi.model.CartItem; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.model.Product; -import com.manir.springbootecommercerestapi.repository.CartItemRepository; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import com.manir.springbootecommercerestapi.repository.ProductRepository; -import com.manir.springbootecommercerestapi.response.CartItemResponse; -import com.manir.springbootecommercerestapi.service.CommonService; -import com.manir.springbootecommercerestapi.service.ShoppingCartService; -import lombok.extern.slf4j.Slf4j; -import org.modelmapper.ModelMapper; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import javax.transaction.Transactional; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.DoubleStream; - -@Service -@Slf4j -public class ShoppingCartServiceImpl implements ShoppingCartService { - - @Resource - private CartItemRepository cartItemRepository; - @Resource - private ModelMapper modelMapper; - @Resource - private ProductRepository productRepository; - @Resource - private UserRepository userRepository; - @Resource - private CommonService commonService; - @Override - public CartItemResponse findByCustomer(User customer) { - - List<CartItem> cartItems = cartItemRepository.findByCustomer(customer); - - if (cartItems.size() == 0){ - throw new EcommerceApiException("User has no product in cart item", HttpStatus.BAD_REQUEST); - } - - List<CartItemDto> cartItemDtoList = cartItems.stream() - .map(cartItem -> mapToDto(cartItem)) - .collect(Collectors.toList()); - DoubleStream totalPrice = cartItemDtoList.stream() - .mapToDouble(cartItemDto -> cartItemDto.getProduct().getPrice() * cartItemDto.getQuantity()); - CartItemResponse cartItemResponse = new CartItemResponse(); - cartItemResponse.setContent(cartItemDtoList); - cartItemResponse.setTotalCost(totalPrice.sum()); - return cartItemResponse; - } - - @Override - public CartItemResponse addCartItem(User customer, Long productId, Integer quantity) { - Integer addedQuantity = quantity; - Product product = findProductById(productId); - - CartItem cartItem = cartItemRepository.findByCustomerAndProduct(customer, product); - if(cartItem != null){ - addedQuantity = cartItem.getQuantity() + quantity; - cartItem.setQuantity(addedQuantity); - }else { - cartItem = new CartItem(); - cartItem.setCustomer(customer); - cartItem.setProduct(product); - cartItem.setQuantity(quantity); - } - - CartItem addedCartItem = cartItemRepository.save(cartItem); - CartItemDto cartItemDto = mapToDto(addedCartItem); - - CartItemResponse cartItemResponse = commonService.getResponse(cartItemDto); - return cartItemResponse; - } - - @Override - public CartItemResponse updateItemQuantity(User customer, Long productId, Integer quantity) { - Product product = findProductById(productId); - CartItem cartItem = cartItemRepository.findByCustomerAndProduct(customer, product); - if (cartItem == null){ - throw new EcommerceApiException("Product is not in the cart item", HttpStatus.BAD_REQUEST); - } - cartItem.setQuantity(quantity); - CartItem updatedItemQuantity = cartItemRepository.save(cartItem); - CartItemDto cartItemDto = mapToDto(updatedItemQuantity); - - CartItemResponse cartItemResponse = commonService.getResponse(cartItemDto); - return cartItemResponse; - } - - @Override - @Transactional - public void deleteItemProduct(User customer, Long productId) { - Product product = findProductById(productId); - CartItem cartItem = cartItemRepository.findByCustomerAndProduct(customer, product); - if (cartItem == null){ - throw new EcommerceApiException("Product is not in the cart item", HttpStatus.BAD_REQUEST); - } - cartItemRepository.deleteByCustomerAndProduct(customer.getId(), productId); - } - - //map to dto - private CartItemDto mapToDto(CartItem cartItem){ - CartItemDto cartItemDto = modelMapper.map(cartItem, CartItemDto.class); - return cartItemDto; - } - - //map to entity - private CartItem mapToEntity(CartItemDto cartItemDto){ - CartItem cartItem = modelMapper.map(cartItemDto, CartItem.class); - return cartItem; - } - - private User findCustomerById(Long customerId){ - User user = userRepository.findById(customerId) - .orElseThrow( - () -> new ResourceNotFoundException("User", customerId) - ); - return user; - } - - private Product findProductById(Long productId){ - Product product = productRepository.findById(productId) - .orElseThrow( - () -> new ResourceNotFoundException("Product", productId) - ); - return product; - } - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/UserRegisterServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/UserRegisterServiceImpl.java deleted file mode 100644 index 7458041..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/UserRegisterServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.manir.springbootecommercerestapi.service.Impl; - -import com.manir.springbootecommercerestapi.dto.SignUpDto; -import com.manir.springbootecommercerestapi.model.Role; -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.RoleRepository; -import com.manir.springbootecommercerestapi.repository.UserRepository; -import com.manir.springbootecommercerestapi.service.UserRegisterService; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; - -import java.util.Collections; - -@Service -public class UserRegisterServiceImpl implements UserRegisterService { - - @Autowired - private UserRepository userRepository; - @Autowired - private RoleRepository roleRepository; - @Autowired - private PasswordEncoder passwordEncoder; - @Autowired - private ModelMapper modelMapper; - - @Override - public SignUpDto registerUser(SignUpDto signUpDto) { - - //convert dto to entity - User user = mapToEntity(signUpDto); - //save user to db - User registeredUser = userRepository.save(user); - return mapToDto(registeredUser); - } - - //map to dto - private SignUpDto mapToDto(User user){ - SignUpDto signUpDto = modelMapper.map(user, SignUpDto.class); - return signUpDto; - } - - //map to entity - private User mapToEntity(SignUpDto signUpDto){ - User user = new User(); - user.setName(signUpDto.getName()); - user.setUserName(signUpDto.getUsername()); - user.setEmail(signUpDto.getEmail()); - user.setPassword(passwordEncoder.encode(signUpDto.getPassword())); - - //add role to the user - Role role = roleRepository.findByName("ROLE_USER").get(); - user.setRoles(Collections.singleton(role)); - return user; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/MapperService.java b/src/main/java/com/manir/springbootecommercerestapi/service/MapperService.java deleted file mode 100644 index 33a4150..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/MapperService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -public interface MapperService<E, D>{ - //entity mapper - E mapToEntity(D type); - - //dto mapper - D mapToDto(E type); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/MapperServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/MapperServiceImpl.java deleted file mode 100644 index 9857292..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/MapperServiceImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - - -import lombok.Data; -import org.modelmapper.ModelMapper; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; - - -@Service -@Component("mapperService") -@Data -public class MapperServiceImpl<E, D> implements MapperService<E, D> { - - - @Resource(name = "modelMapper") - private final ModelMapper modelMapper; - - private Class<E> entityClass; - - private Class<D> dtoClass; - - public MapperServiceImpl(ModelMapper modelMapper) { - this.modelMapper = modelMapper; - } - - @Override - public E mapToEntity(D type) { - E model = modelMapper.map(type, getEntityClass()); - return model; - } - - @Override - public D mapToDto(E type) { - D dto = modelMapper.map(type, getDtoClass()); - return dto; - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/OrderProductsService.java b/src/main/java/com/manir/springbootecommercerestapi/service/OrderProductsService.java deleted file mode 100644 index 2fec5dc..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/OrderProductsService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.OrderProductsDto; -import com.manir.springbootecommercerestapi.model.OrderProducts; -import com.manir.springbootecommercerestapi.model.User; - -import java.util.List; - -public interface OrderProductsService { - void addOrderProducts(OrderProducts orderProducts); - List<OrderProductsDto> findOrderItemsByCustomer(User customer); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java b/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java deleted file mode 100644 index 2ff968d..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.OrderDto; -import com.manir.springbootecommercerestapi.model.User; - -import java.util.List; - -public interface OrderService { - - void placeOrder(User customer); - OrderDto saveOrder(OrderDto orderDto); - List<OrderDto> listOrdersByCustomer(User customer); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/ProductImageGalleryService.java b/src/main/java/com/manir/springbootecommercerestapi/service/ProductImageGalleryService.java deleted file mode 100644 index 4d210f2..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/ProductImageGalleryService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.model.ImageData; -import org.springframework.web.multipart.MultipartFile; - -public interface ProductImageGalleryService { - - ImageData addImageToProduct(Long productId, MultipartFile file); - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java b/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java deleted file mode 100644 index 803e650..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.ProductDto; -import com.manir.springbootecommercerestapi.response.CommonResponse; -import com.manir.springbootecommercerestapi.response.ProductResponse; -import org.springframework.web.multipart.MultipartFile; - -import java.util.List; - -public interface ProductService { - ProductDto createProduct(ProductDto productDto, MultipartFile file); - CommonResponse getAllProduct(int pageNo, int pageSize, String sortBy, String sortDir); - ProductDto getProductById(Long productId); - ProductDto updateProduct(Long categoryId, ProductDto productDto, Long productId); - void deleteProduct(Long productId); - - ProductDto saveProductByCategoryId(Long categoryId, ProductDto productDto); - - List<ProductDto> searchProduct(String query); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/SettingService.java b/src/main/java/com/manir/springbootecommercerestapi/service/SettingService.java deleted file mode 100644 index 05c010e..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/SettingService.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.SettingDto; - -public interface SettingService { - SettingDto addSettingFirstTime(SettingDto settingDto); - SettingDto updateSetting(SettingDto settingDto, Long id); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/ShoppingCartService.java b/src/main/java/com/manir/springbootecommercerestapi/service/ShoppingCartService.java deleted file mode 100644 index f657c98..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/ShoppingCartService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.response.CartItemResponse; - -public interface ShoppingCartService { - - CartItemResponse findByCustomer(User customer); - - CartItemResponse addCartItem(User customer, Long productId, Integer quantity); - - CartItemResponse updateItemQuantity(User customer, Long productId, Integer quantity); - - void deleteItemProduct(User customer, Long productId); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/UserRegisterService.java b/src/main/java/com/manir/springbootecommercerestapi/service/UserRegisterService.java deleted file mode 100644 index 9096440..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/service/UserRegisterService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.manir.springbootecommercerestapi.service; - -import com.manir.springbootecommercerestapi.dto.SignUpDto; - -public interface UserRegisterService { - SignUpDto registerUser(SignUpDto signUpDto); -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/utils/Constant.java b/src/main/java/com/manir/springbootecommercerestapi/utils/Constant.java deleted file mode 100644 index f37b4a0..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/utils/Constant.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.manir.springbootecommercerestapi.utils; - -public class Constant { - - //pagination properties - public static final String DEFAULT_PAGE_NUMBER = "0"; - public static final String DEFAULT_PAGE_SIZE = "10"; - public static final String DEFAULT_SORT_BY = "id"; - public static final String DEFAULT_SORT_DIRECTION = "asc"; - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/utils/ImageUtils.java b/src/main/java/com/manir/springbootecommercerestapi/utils/ImageUtils.java deleted file mode 100644 index 60e1916..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/utils/ImageUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.manir.springbootecommercerestapi.utils; - -import java.io.ByteArrayOutputStream; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - -public class ImageUtils { - - public static byte[] compressImage(byte[] data) { - Deflater deflater = new Deflater(); - deflater.setLevel(Deflater.BEST_COMPRESSION); - deflater.setInput(data); - deflater.finish(); - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); - byte[] tmp = new byte[4*1024]; - while (!deflater.finished()) { - int size = deflater.deflate(tmp); - outputStream.write(tmp, 0, size); - } - try { - outputStream.close(); - } catch (Exception ignored) { - } - return outputStream.toByteArray(); - } - - - - public static byte[] decompressImage(byte[] data) { - Inflater inflater = new Inflater(); - inflater.setInput(data); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); - byte[] tmp = new byte[4*1024]; - try { - while (!inflater.finished()) { - int count = inflater.inflate(tmp); - outputStream.write(tmp, 0, count); - } - outputStream.close(); - } catch (Exception ignored) { - } - return outputStream.toByteArray(); - } - - -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/utils/PasswordEncoderGenerator.java b/src/main/java/com/manir/springbootecommercerestapi/utils/PasswordEncoderGenerator.java deleted file mode 100644 index e466684..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/utils/PasswordEncoderGenerator.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.manir.springbootecommercerestapi.utils; - -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -public class PasswordEncoderGenerator { - public static void main(String[] args) { - PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - System.out.println("ADMIN: " + passwordEncoder.encode("admin")); - System.out.println("USER: " + passwordEncoder.encode("user")); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/utils/RequestClientIP.java b/src/main/java/com/manir/springbootecommercerestapi/utils/RequestClientIP.java deleted file mode 100644 index 5920839..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/utils/RequestClientIP.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.manir.springbootecommercerestapi.utils; - -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; - -public class RequestClientIP { - - private static final String[] IP_HEADER_CANDIDATES = { - "X-Forwarded-For", - "Proxy-Client-IP", - "WL-Proxy-Client-IP", - "HTTP_X_FORWARDED_FOR", - "HTTP_X_FORWARDED", - "HTTP_X_CLUSTER_CLIENT_IP", - "HTTP_CLIENT_IP", - "HTTP_FORWARDED_FOR", - "HTTP_FORWARDED", - "HTTP_VIA", - "REMOTE_ADDR" - }; - - public static String getClientIpAddress(HttpServletRequest request) { - - if (RequestContextHolder.getRequestAttributes() == null) { - return "0.0.0.0"; - } - - request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); - for (String header: IP_HEADER_CANDIDATES) { - String ipList = request.getHeader(header); - if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) { - String ip = ipList.split(",")[0]; - return ip; - } - } - - return request.getRemoteAddr(); - } -} diff --git a/src/main/java/com/manir/springbootecommercerestapi/utils/isAuthenticatedAsAdminOrUser.java b/src/main/java/com/manir/springbootecommercerestapi/utils/isAuthenticatedAsAdminOrUser.java deleted file mode 100644 index 83c6333..0000000 --- a/src/main/java/com/manir/springbootecommercerestapi/utils/isAuthenticatedAsAdminOrUser.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.manir.springbootecommercerestapi.utils; - -import org.springframework.security.access.prepost.PreAuthorize; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -@PreAuthorize("hasRole('ADMIN') || hasRole('USER')") -public @interface isAuthenticatedAsAdminOrUser { -} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index bf443c7..0000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -1,18 +0,0 @@ -spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect -spring.jpa.show-sql =true -spring.jpa.properties.hibernate.format_sql= true -spring.datasource.password=Password123#@! -spring.datasource.username=root -spring.datasource.url=jdbc:mysql://localhost:3306/springBootEcommerceRestApi?serverTimezone=UTC -spring.jpa.hibernate.ddl-auto=update - -#TO see security is working on the console -logging.level.org.springframework.security=DEBUG -#Spring security default auth credential -#spring.security.customer.password= customer -#spring.security.customer.name= customer -#spring.security.customer.roles= ADMIN - -#JWT properties -app.jwt-secret = JWTSecretKey -app.jwt-expiration-milliseconds = 604800000 diff --git a/src/test/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplicationTests.java b/src/test/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplicationTests.java deleted file mode 100644 index 3c6ec21..0000000 --- a/src/test/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.manir.springbootecommercerestapi; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class SpringBootECommerceRestApiApplicationTests { - - @Test - void contextLoads() { - } - -}